/*	bar2smpte.js
	copyleft Thomas Baspeyras 2005

requires :
	dom.js
	js_lib.js

index:
	Bar2smpte()
*/

function Bar2smpte() {
/*	prototype of bars-smpte converter
	prototype de convertisseur mesures-smpte
*/

	var figures = new Array();
	var barNumber;
	var beatsPerBar;
	var tempo;

	var hour;
	var minute;
	var second;
	var palFrame;
	var cinemaFrame;
	var ntscFrame;

	var tapeLength76;
	var tapeLength38;

	addLoadEvent(
		function() {
			tempo = document.getElementById("bar2smpteTempo");
			tempo.onchange = updateSmpteTape;

			beatsPerBar = document.getElementById("beatsPerBar");
			beatsPerBar.onchange = updateSmpteTape;

			barNumber = document.getElementById("barNumber");
			barNumber.onchange = updateSmpteTape;

			hour = document.getElementById("hour");
			hour.onchange = updateFromSmpte;
			minute = document.getElementById("minute");
			minute.onchange = updateFromSmpte;
			second = document.getElementById("second");
			second.onchange = updateFromSmpte;
			palFrame = document.getElementById("palFrame");
			palFrame.onchange = function() { updateFromSmpte(25); };
			cinemaFrame = document.getElementById("cinemaFrame");
			cinemaFrame.onchange = function() { updateFromSmpte(24); };
			ntscFrame = document.getElementById("ntscFrame");
			ntscFrame.onchange = function() { updateFromSmpte(30); };

			tapeLength76 = document.getElementById("tapeLength76");
			tapeLength76.onchange = function() { updateFromTape(76); };
			tapeLength38 = document.getElementById("tapeLength38");
			tapeLength38.onchange = function() { updateFromTape(38); };

			updateSmpteTape();
		}
	)

	updateSmpteTape = function() {
		var song = 60 * barNumber.value * beatsPerBar.value / tempo.value;
		tapeLength76.value = Math.round(76 * song) / 100;
		tapeLength38.value = Math.round(38 * song) / 100;
		hour.value = Math.floor(song / 3600);
		song -= hour.value * 3600;
		minute.value = Math.floor(song / 60);
		song -= minute.value * 60;
		second.value = Math.floor(song);
		song -= second.value;
		palFrame.value = Math.floor(song * 25);
		cinemaFrame.value = Math.floor(song * 24);
		ntscFrame.value = Math.floor(song * 29.97);
	}

	updateFromSmpte = function(rate) {
		var song;
		switch(rate) {
			case 24: song = cinemaFrame.value / 24; break;
			case 30: song = ntscFrame.value / 29.97; break;
			default: song = palFrame.value / 25; break;
		}
		song = 3600 * hour.value + 60 * minute.value + 1*second.value + song;
		tempo.value = Math.round(60000 * barNumber.value * beatsPerBar.value / song) / 1000;
		updateSmpteTape();
	}

	updateFromTape = function(speed) {
		var song;
		switch(speed) {
			case 76: song = 100 * tapeLength76.value / 76; break;
			case 38: song = 100 * tapeLength38.value / 38; break;
		}
		tempo.value = Math.round(60000 * barNumber.value * beatsPerBar.value / song) / 1000;
		updateSmpteTape();
	}
}

bar2smpte = new Bar2smpte();

