var index;
var width;
var done = false;
var finished = false;
var ajaxLoading;

window.addEvent('domready', function() {

	contentScroll();
	makeSelectables();
	bussola();
	resetWarning();
	highslide();
	validateContattiForm();
	finale();

	ajaxLoading = new AjaxLoading('contentMask').setMessage('elaborazione dati in corso...');

});

function highslide() {

	hs.registerOverlay({
		overlayId: 'closebutton',
		position: 'top right',
		fade: 2 // fading the semi-transparent overlay looks bad in IE
	});

	hs.graphicsDir = 'highslide/graphics/';
	
	$$(".highslide").each(function(item) {

		item.addEvent('click', function(){
			return hs.expand(this);
		});

	});

}

function contentScroll() {

	$("contentHScroll").set('tween', {duration: 500, transition: Fx.Transitions.Expo.easeOut});
	$("prev").fade('hide');

	index = 0;
	width = parseInt($$(".content")[0].getSize().x);
	heightTitle = parseInt($("title").getSize().y);

	$("next").addEvent('click', function(){
		if(index >= 4) return;
		checkStep(index);
	});

	$("prev").addEvent('click', function(){
		goPrev();
	});
	
	$("calcola").addEvent('click', function(){
		getCharts();
		$("prev").fade('out');
		$("azzera").fade('in');
		this.fade('out');
		finished = true;
	});
	
	$("azzera").addEvent('click', function(){
		document.location = "index.php";
	});
	
	$$('.charts').each(function(item){
		item.fade('hide');
		item.addEvent('load', function(){
			this.fade(1);
		});
	});

}

function riepilogoSlide() {

	$("riepilogoContent").fade('show');
	$$("#riepilogoTitle img")[0].set("styles", { "margin-top" : "-65px" });

	$("riepilogoTitle").addEvent('click', function(){

		if(!$("riepilogoContent").retrieve('visible')){
			$("riepilogoContent").store('visible', true);
			$("riepilogoContent").fade(1);
			$$("#riepilogoTitle img")[0].set("styles", { "margin-top" : "-65px" });
		}
		else {
			$("riepilogoContent").store('visible', false);
			$("riepilogoContent").fade(0);
			$$("#riepilogoTitle img")[0].set("styles", { "margin-top" : "0" });
		}
		return false;

	});

}

function makeSelectables(){

	var duration = 50;
	var controlloClick = false;

	$$('.selectableContainer').each(function(item) {

		item.store('selected', null);

		item.getChildren('.selectable').each(function(item) {

			item.addEvent('mouseover', function(){

				if (this.getParent('.selectableContainer').retrieve('selected') == this) return;

				this.getFirst("img").fade(0.01);

			});

			item.addEvent('mouseout', function(){

				if (this.getParent('.selectableContainer').retrieve('selected') == this) return;

				this.getFirst("img").fade(1);

			});

			item.addEvent('click', function(){

				var selected = this.getParent('.selectableContainer').retrieve('selected');

				if (selected == this) return;

				//deseleziono
				if(selected){
					selected.getFirst("img").fade(1);
					selected.set('styles', { 'font-weight': 'normal', 'color': '#666' });
				}

				//seleziono
				this.getFirst("img").fade(0.01);
				this.set('styles', { 'font-weight': 'bold', 'color': '#ff8000' });

				this.getParent('.selectableContainer').setAttribute('value', this.getAttribute('value'));
				this.getParent('.selectableContainer').store('selected', this);

			});

		});
	});

}

function bussola() {

	var position = new Array();
	position['ovest'] = '-206px';
	position['sud-ovest'] = '-412px';
	position['sud'] = '-618px';
	position['sud-est'] = '-824px';
	position['est'] = '-1030px';

	$('bussolaMap').getChildren().each(function(item){
		item.addEvent('click', function(){
			$('bussola').setAttribute('value', item.get('id'));
			$('bussola').set('styles', {'background-position': '0px ' + position[item.get('id')]});
			return false;
		});
	});

}

function resetWarning() {
	$('warning').setStyle('display', 'block');
	$('warning').fade('hide');
	$$('#warning span').each(function(item){ item.set('styles', {'display': 'none'}); });
}

function showWarning(codice) {
	if(!codice) return;
	
	//rendo visibile il l'errore relativo al codice giusto
	$(codice).set('styles', {'display': 'inline'});
	
	//visualizzo il warning
	$("warning").fade(1);
}

function updateRiepilogo() {
	
	var paramsObj = { 'step': index+1 };
	
	new Request.HTML({url:'ajax/updateRiepilogo.php', onComplete: updateRiepilogoComplete}).post(paramsObj).send();
}

function updateRiepilogoComplete(responseTree, responseElements, valoriRiepilogo, responseJavaScript) {

	valoriRiepilogo = valoriRiepilogo.split("|");
	
	for(var i=0; i< valoriRiepilogo.length; i+=2) $("riepilogoField"+valoriRiepilogo[i]).set('text', valoriRiepilogo[i+1]);
	
} 

function checkStep(i) {

	var paramsObj = {
		'step': i,
		'provincia': $('provincia').get('value'),
		'superficie': $('superficie').get('value'),
		'acs': $('acs').getAttribute('value'),
		'inclinazioni': $('inclinazioni').getAttribute('value'),
		'orientamento': $('bussola').getAttribute('value'),
		'bussola': $('bussola').get('value')
	};
	
	ajaxLoading.setMessage('elaborazione dati in corso...').show();
	
	new Request.HTML({url:'ajax/checkStep.php', onComplete: checkStepComplete}).post(paramsObj).send();
}

function checkStepComplete(responseTree, responseElements, codice, responseJavaScript) {

	resetWarning();
	
	ajaxLoading.hide();
	
	if(codice == "E000") {
		updateRiepilogo();
		goNext();
	}
	else showWarning(codice);
}

function goNext() {
	
	var offset =  width * ++index + 1;
	var offsetTitle =  heightTitle * index;

	if(index >= 4) {
		$("next").fade('out');
		$("calcola").fade('in');
	}
	else $("next").fade('in');

	if(index <= 0) $("prev").fade('out');
	else $("prev").fade('in');

	$("contentHScroll").tween("margin" , "0 0 0 -"+offset+"px");
	
	$("title").set('styles', {"background-position" : "0 -"+offsetTitle+"px"});
	
}

function goPrev() {

	var offset = width * --index + 1;
	var offsetTitle =  heightTitle * index;

	if(index <= 0 || finished == true) $("prev").fade('out');
	else $("prev").fade('in');

	if(index >= 4) {
			$("next").fade('out');
		}
	else {
		$("next").fade('in');
		$("calcola").fade('out');
	}

	$("contentHScroll").tween("margin" , "0 0 0 -"+offset+"px");
	
	$("title").set('styles', {"background-position" : "0 -"+offsetTitle+"px"});
	
}

function getCharts() {
	var paramsObj = { 'step': 4 };
	new Request.HTML({url:'ajax/checkStep.php', onComplete: getChartsComplete}).post(paramsObj).send();
}

function getChartsComplete(responseTree, responseElements, urlsAndData, responseJavaScript) {
	
	//url per ridimensionare il grafico + sharpen
	var getChartSmall = "getCharts/260/";
	var getChartBig = "getCharts/520/";
	var noChartSmall = "images/jpg/noChart.jpg";
	var noChartBig = "images/jpg/noChart.jpg";
	
	//splitto i dati a coppie URL->PERCENTUALE ANNUA
	urlsAndData = urlsAndData.split("§");
	
	$('chart1').set('src', urlsAndData[0] != "NO_CHART" ? getChartSmall + urlsAndData[0] : noChartSmall);
	$('chart2').set('src', urlsAndData[2] != "NO_CHART" ? getChartSmall + urlsAndData[2] : noChartSmall);
	$('chart3').set('src', urlsAndData[4] != "NO_CHART" ? getChartSmall + urlsAndData[4] : noChartSmall);
	$('chart4').set('src', urlsAndData[6] != "NO_CHART" ? getChartSmall + urlsAndData[6] : noChartSmall);
	$('chart1Big').set('href', urlsAndData[0] != "NO_CHART" ? getChartBig + urlsAndData[0] : noChartBig);
	$('chart2Big').set('href', urlsAndData[2] != "NO_CHART" ? getChartBig + urlsAndData[2] : noChartBig);
	$('chart3Big').set('href', urlsAndData[4] != "NO_CHART" ? getChartBig + urlsAndData[4] : noChartBig);
	$('chart4Big').set('href', urlsAndData[6] != "NO_CHART" ? getChartBig + urlsAndData[6] : noChartBig);
	
	var showDynamicInvite1_2 = 0;
	var sup = new Array();
	
	if(urlsAndData[1] >= 50) { showDynamicInvite1_2++; sup.push(urlsAndData[1]); }
	if(urlsAndData[3] >= 50) { showDynamicInvite1_2++; sup.push(urlsAndData[3]); }
	if(urlsAndData[5] >= 50) { showDynamicInvite1_2++; sup.push(urlsAndData[5]); }
	if(urlsAndData[7] >= 50) { showDynamicInvite1_2++; sup.push(urlsAndData[7]); }
	
	if(showDynamicInvite1_2 == 1) {
		$("dynamicInvite1").setStyle('visibility', 'visible');
		$('percent1').set('text', sup[0]+"%");
	}
	
	if(showDynamicInvite1_2 > 1) {
		sup.sort();
		$('percent2').set('text', sup[0]+"%");
		$('percent3').set('text', sup[sup.length-1]+"%");
		$("dynamicInvite2").setStyle('visibility', 'visible');
	}

	var showDynamicInvite3 = false;
	if(urlsAndData[1] < 50 && urlsAndData[3] < 50 && urlsAndData[5] < 50 && urlsAndData[7] < 50) showDynamicInvite3 = true;
	if(showDynamicInvite3) $("dynamicInvite3").setStyle('visibility', 'visible');
	
	$('collettore1').set('text', urlsAndData[1]+"%");
	$('collettore2').set('text', urlsAndData[3]+"%");
	$('collettore3').set('text', urlsAndData[5]+"%");
	$('collettore4').set('text', urlsAndData[7]+"%");
	
	new Request.HTML({url:'ajax/sendReport.php'}).send();
	new Request.HTML({url:'ajax/getPdfContent.php', onComplete: getPdfContentComplete}).send();

	showCharts();
}

function getPdfContentComplete(responseTree, responseElements, pdfContent, responseJavaScript) {
	$("c").set('value', Base64.encode(pdfContent));
	$("pdfTitle").fade('hide');
	$("pdfTitle").setStyle('display', 'block');
	$("pdfTitle").fade('in');
}

function showCharts() {
	$("totale").set("styles", {"display" : "block"});
	$("results").set("styles", {"display" : "none"});
}

function finale() {
	$("contactsFinale").addEvent('click', function(){

		var offset =  width * ++index + 1;

		$("next").fade('out');
		$("calcola").fade('out');
		$("prev").fade('in');
		
		$("contentHScroll").tween("margin" , "0 0 0 -"+offset+"px");
		
	});
}

//validazione

function validateContattiForm(){

	var wait = 1500;

	var nome = new LiveValidation('nome', {
		insertAfterWhatNode: $("label_nome"),
		validMessage: "",
		failureMessage: "",
		wait: wait
	});
	nome.add(Validate.Presence, { failureMessage: $("nome").get("error") });
	
	var cognome = new LiveValidation('cognome', {
		insertAfterWhatNode: $("label_cognome"),
		validMessage: "",
		failureMessage: "",
		wait: wait
	});
	cognome.add(Validate.Presence, { failureMessage: $("cognome").get("error") });

	var mail = new LiveValidation('email', {
		insertAfterWhatNode: $("label_email"),
		validMessage: "none",
		failureMessage: "",
		wait: wait
	});
	mail.add(Validate.Presence, { failureMessage: $("email").get("error") });
	mail.add(Validate.Email, { failureMessage: $("email").get("error") });
	
	var contatti_provincia = new LiveValidation('contatti_provincia', {
		insertAfterWhatNode: $("label_provincia"),
		validMessage: "none",
		failureMessage: "",
		wait: wait
	});
	contatti_provincia.add(Validate.Presence, { failureMessage: $("contatti_provincia").get("error") });
	
	var motivazione = new LiveValidation('motivazione', {
		insertAfterWhatNode: $("label_motivazione"),
		validMessage: "none",
		failureMessage: "",
		wait: wait
	});
	motivazione.add(Validate.Presence, { failureMessage: $("motivazione").get("error") });
	
	var privacy = new LiveValidation('privacy', {
		insertAfterWhatNode: $("label_privacy"),
		validMessage: "none",
		failureMessage: "",
		wait: wait
	});
	privacy.add(Validate.Acceptance, { failureMessage: $("privacy").get("error") });

	var automaticOnSubmit = $("formContatti").onsubmit;

	$("formContatti").onsubmit = function(){
		if(automaticOnSubmit()) sendContatti();
		return false;
	}
}

function sendContatti() {
	$("formContatti").set('send', { onSuccess: setResponse });
	ajaxLoading.show();
	$("formContatti").send();
}

function setResponse(responseText, responseXML) {
	$("formContatti").set("styles", {"display": "none"});
	$("response_"+responseText).fade('hide');
	$("response_"+responseText).set("styles", {"display": "block"});
	$("response_"+responseText).fade('in');
	ajaxLoading.hide();
}