var total = 0;
function startCalc(){
	interval = setInterval("calc()",1);
}
function calc(){
	var total = 0;
	var qnt = $$('div.quantita select');
	qnt.each(function(item, index){
		total = total + (parseInt(item.value) * parseFloat(item.className.replace(",", ".")));
	});
	total = total.toFixed(2);
	total = total.replace(".", ","); 
	$("totalBox").value = total;
	stopCalc();
}
function stopCalc(){
	clearInterval(interval);
}

function checkDisp(){
	var biglietti = $$('div.biglietto');
	gruppiTwo = new Array();
	biglietti.each(function(item, index){
		item.group = item.getElement('div.disponibilita span').className;
		item.disp = item.getElement('div.disponibilita span div').className;
		gruppiTwo[item.group] = parseFloat(item.disp);
	});
	biglietti.each(function(item, index){
		item.group = item.getElement('div.disponibilita span').className;
		item.value = item.getElement('div.quantita select').value;
		item.disp = item.getElement('div.disponibilita span div').innerHTML;
		gruppiTwo[item.group] = gruppiTwo[item.group]-item.value;
		//alert(gruppiTwo[item.group]);
	});
	biglietti.each(function(item, index){
		item.group = item.getElement('div.disponibilita span').className;
		item.value = item.getElement('div.quantita select').value;
		item.disp = item.getElement('div.disponibilita span div').innerHTML;
		item.getElement('div.disponibilita span div').innerHTML = gruppiTwo[item.group];
		
		var options = item.getElements('div.quantita select option');
		window.maxdisp = parseInt(gruppiTwo[item.group]);
		options.each(function(item, index){
			var value = parseInt(item.value);
			if (value <= window.maxdisp || item.parentNode.value >= value-window.maxdisp) {
				item.set('disabled', false);
			} else {
				item.set('disabled', true);
			}
		});
	});
}

window.addEvent('domready', function() {
	window.gruppi = new Array();
	var biglietti = $$('div.biglietto');
	biglietti.each(function(item, index){
		item.group = item.getElement('div.disponibilita span').className;
		item.disp = item.getElement('div.disponibilita span').innerHTML;
		window.gruppi[item.group] = parseFloat(item.disp);
	});
	if ($('prenotazione')) {
		var myVerticalSlide = new Fx.Slide('prenotazione');
		var myVerticalSlide2 = new Fx.Slide('prenota');
		myVerticalSlide.hide();
		$('prenota').addEvent('click', function(e){
			e.stop();
			myVerticalSlide.toggle();
			myVerticalSlide2.toggle();
		});
		checkDisp();
	}
	if ($('submit')) {
		myVerticalSlide.show();
		myVerticalSlide2.hide();
	}
	if ($('totalBox')) {
		$('totalBox').addEvent('change', function(){
			startCalc();
		});
	}
	var selects = $$('div.quantita select');
	selects.each(function(item, index){
		item.addEvent('change', function(){
			checkDisp();
			startCalc();
		});
	});
});