$(document).ready(initFunction);

initArray = new Array(); //viene creato l'array
initArray.push("Drag.init(document.getElementById(\"popupTitolo\"), document.getElementById(\"popup\"));");

function initFunction() {
	// attendo che l'intero documento sia stato caricato
	//iterazione dell'array initArray ed esecuzione cone js di tutte le stringhe contenute
	$.each(initArray,function(index,item){eval(item);});
}

function caricaPaginaGET(url){
	if (arguments.length > 2) {
		//Elementi per fare il focus su un campo di un modulo nella nuova pagina
		//p1 = nome modulo; p2 = nome campo;
		p1=arguments[1];
		p2=arguments[2];
	} else {
		p1=false;
		p2=false;
	}
	if (arguments.length == 4) contenuto = arguments[3]; else contenuto = "contenuto";
	elemento=$("#"+contenuto);
	$.get(url, function(dati){
		elemento.html(dati);
		if (p1 && p2) {
			field=eval("document."+p1+"."+p2);
			field.focus();
		}
	});
	return false;
}

function caricaPaginaGET_alt(url){
	if (arguments.length == 4) contenuto = arguments[3]; else contenuto = "contenuto";
	$("#"+contenuto).load(url);
	return false;
}

/**
 *  Funzione che richiede una pagina spedendo dei dati in post e
 *  scrivendo l'output della richiesta in un elemento predefinito.
 */
function caricaPaginaPOST(url,nomeform){
	if (arguments.length > 3) {
		//Elementi per fare il focus su un campo di un modulo nella nuova pagina
		//p2 = nome modulo; p3 = nome campo;
		p2=arguments[2];
		p3=arguments[3];
	} else {
		p1=false;
		p2=false;
	}
	if (arguments.length == 5) contenuto_p = arguments[4]; else contenuto_p = "contenuto";
	elemento_p=$("#"+contenuto_p);
	$.post(url, valori_post_extra(nomeform), function(dati){
		elemento_p.html(dati);
		if (p2 && p3) {
			field=eval("document."+p2+"."+p3);
			field.focus();
		}
	});
	return false;
}

function caricaPopupPOST(url,nomeform){ // da testare
	elemento=$("#popupContenuto");
	$.post(url,valori_post_extra(nomeform), function (dati){
		elemento.html(dati);
		mostraPopup('popup');
	});
	return false;
}

function caricaPopupGET(url,contenuto,titolo){
	//come prima azione provvediamo a mostrare il loader
	mostraLoader();
	if (arguments.length > 4) {
		//Elementi per fare il focus su un campo di un modulo nella nuova pagina
		//p1 = nome modulo; p2 = nome campo;
		p1=arguments[3];
		p2=arguments[4];
	} else {
		p1=false;
		p2=false;
	}
	if (arguments.length > 5) {
		s1=arguments[5];
		//s2=arguments[6];
	} else {
		s1=false;
		//s2=false;
	}
	$.post(url,function (dati){
		var celemento = $("#"+contenuto+"Contenuto");
		var telemento = $("#"+contenuto+"Titolo");
		celemento.html(dati);
		if (titolo!="") {
			telemento.html(titolo);
			mostraPopup(contenuto);
		}
		if (p1 && p2) {
			field=eval("document."+p1+"."+p2);
			field.focus();
		}
		if (s1) {
			jQuery("#suggest").suggest(s1,{});
		}
		//come ultima azione provvediamo a rimuovere il loader
		chiudiLoader();
	});
	return false;
}

function spedisciModulo(url,nomeform){
	//come prima azione provvediamo a mostrare il loader
	mostraLoader();
	$.post(url, valori_post_extra(nomeform), function(results){
		// do something useful
		var status=null;
		var status=$(results).find("status").text();
		if (status=="error"){
			var error_field = $(results).find("field").text();
			var messaggio = $(results).find("messaggio").text();
			var titolo = $(results).find("titolo").text();
			var panel_code = "<div class=\"servizio_titolo\">" + titolo + "</div>" +
					"<div class=\"servizio_messaggio\">" + messaggio + "</div>";
			mostraPannello("servizio", panel_code);
			//alert(panel_code);
			if (error_field != " "){
				coloraCampo(error_field);
			}
			chiudiLoader();
		} else if (status=="correct"){
			//redirect su pagina definita
			var destination = $(results).find("destinazione").text();
			if (destination != " " && destination != "-") {
				window.location = destination;
			}
			if (destination == "-") {
				var jscript = $(results).find("jscript").text();
				eval(jscript);
			}
			//chiudo il loader soltanto se non mi muovo da questa pagina
			if (destination == " " || destination == "-") chiudiLoader();
		}
	},"xml");
	return false;
}

/* La funzione effettua una chiamata AJAX per prelevare i valori e popolare la SELECT di DESTINAZIONE
 * La sorgente viane passata come oggetto, la destinazione come ID dell'oggetto.
 */
function aggiornaLista(url,sorgente,destinazione){
	alert(sorgente);
	//prelevo valore della sorgente.
	if (sorgente){
		sourceVal = sorgente.options[sorgente.options.selectedIndex].value;
	}
	
	// inizializzaizone AJAX
	var ajax = assegnaXMLHttpRequest(); // assegnazione oggetto XMLHttpRequest
	if(ajax) {// se l'oggetto XMLHttpRequest non è nullo
		if (sorgente){
			ajax.open("get", url+"?elem="+sourceVal, true); // impostazione richiesta asincrona in POST,del file specificato
		} else ajax.open("get", url, true); // impostazione richiesta asincrona in POST,del file specificato
		ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded"); // imposto il giusto header
		ajax.setRequestHeader("connection", "close"); // rimozione dell'header "connection" come "keep alive"
		// impostazione controllo e stato della richiesta
		ajax.onreadystatechange = function() {
			// verifica dello stato
			if(ajax.readyState === 4 ) { //se l'oggetto ajax mi segnala che ha finito
				if (ajax.status === 200) {// verifica della risposta da parte del server
					if (false) { /*DEBUG*/
						mostraPannello("servizio", ajax.responseText);
						//alert(ajax.responseText+"\n"+ajax.responseXML);
						return;
					}
					var results = ajax.responseXML;
					//cancelliamo l'intera lista
					listaDest=document.getElementById(destinazione);
					for (i = listaDest.options.length; i >= 0; i--) { 
						listaDest.options[i] = null;
					}
					var elementi = null;
					var chiavi = results.getElementsByTagName("chiave");
					var valori = results.getElementsByTagName("valore");
	
					//scorro tutti gli elementi
					for (i=0;i<chiavi.length;i++) {
						if (chiavi[i].firstChild) chiave = chiavi[i].firstChild.data;
							else chiave = "";
						if (valori[i].firstChild) valore = valori[i].firstChild.data;
							else valore = "";
						listaDest.options[i] = new Option(chiave, valore, false, false);
					}
				} else alert(ajax.status)//status 200
			}
		}
		ajax.send(null);
	} else alert("Questo browser non supporta alcune funzioni indispensabili per il corretto funzionamento dell'applicativo!");
}

function valori_post_extra(nomeform) {
	var dati = {};
	curform = eval("document."+nomeform+".elements");
	elementi = curform.length;
	for (i=0; i<elementi; i++) {
		//alert("Tipo del campo processato: "+curform[i].type+"-"+curform[i].value);
		if ((curform[i].type == "text") || (curform[i].type=="textarea") || (curform[i].type=="password") || (curform[i].type=="hidden") || (curform[i].type=="file")){
			/*str=curform[i].value.replace("\n","\\n");
			str=curform[i].value.replace("\r","\\r");*/
			str=curform[i].value;
			//console.log(URLEncode(str));
			eval("dati."+curform[i].name+"=\""+(URLEncode(str))+"\"");
		}
		if ((curform[i].type == "radio") && (curform[i].checked == true))
			eval("dati."+curform[i].name+"=\""+(curform[i].value)+"\"");
		if (curform[i].type == "checkbox") {
			if (curform[i].name.charAt(0)=="o") {
				if (curform[i].checked) eval("dati."+curform[i].name+"=\"on\"");
				else eval("dati."+curform[i].name+"=\"\"");
			} else {
				if (curform[i].checked) eval("dati."+curform[i].name+"=\"on\"");
			}
		}
		if (curform[i].type == "select-one") {
			eval("dati."+curform[i].name+"=\""+(curform[i].options[curform[i].options.selectedIndex].value)+"\"");
		}
		if (curform[i].type == "select-multiple") {
			var dati_multiple="";
			for (j=0;j<curform[i].options.length;j++){
				//alert("Form :"+curform[i].name+"\n Valore: "+curform[i].options[j].value);
				dati_multiple+="<"+curform[i].options[j].value+">";
			}
			eval("dati."+curform[i].name+"=\""+dati_multiple+"\"");
		}
	}
	return dati;
}

function URLEncode(testo){
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +// Numeric
	"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +// Alphabetic
	"abcdefghijklmnopqrstuvwxyz" +
	"-_.!~*'()";// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";
	
	var plaintext = testo;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
		if (ch == " ") {
			encoded += "+";// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
			encoded += ch;
		} else {
			var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
				alert( "Unicode Character '" + ch + "' cannot be encoded using standard URL encoding.\n" + 
					"(URL encoding only supports 8-bit characters.)\n" +
					"A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for
	return encoded;
}

function aggiornaLista(url,sorgente,destinazione){
	//prelevo valore della sorgente
	val_sel=0;
	if (arguments.length > 3)
		val_sel=arguments[3];
	sourceVal=$(sorgente).val();
	$.get(url+"?elem="+sourceVal, function(results){
		//cancelliamo l'intera lista
		listaDest=$("#"+destinazione).empty();
		var elementi = $(results).find("elemento");
		elementi.each(function (ele_dati){
			chiave=$(this).find("chiave").text();
			valore=$(this).find("valore").text();
			if (val_sel==valore)
				listaDest.append('<option value="'+valore+'" selected="selected">'+chiave+'</option>');
			else
				listaDest.append('<option value="'+valore+'">'+chiave+'</option>');
		});
	},"xml");
}

function mostraPannello(nr, inner) {
	var pageData = getPageData();
	var top = Math.round(((pageData[5]/2)-110)+pageData[1]);
	var left = Math.round(((pageData[4]/2)-170)+pageData[0]);
	$("#"+nr).html(inner+'<div class="servizio_tasti"><a href="#" onclick="return chiudiPannello();">chiudi</a></div>');
	$("#"+nr).css({left:left+"px",top:top+"px",display:"block"});
}

function mostraPopup(nr) {
	var pageData = getPageData();
	var top = Math.round(((pageData[5]/2)-250)+pageData[1]);
	if (top < 110) top = 110;
	//var left = Math.round(((pageData[4]/2)-343)+pageData[0]);
	var left = Math.round(((pageData[4]/2)-290)+pageData[0]);
	$("#"+nr).css({left:left+"px",top:top+"px",display:"block"});
	//$("#"+nr).css({left:left+"px",top:top+"px"});
	//$("#"+nr).fadeIn("fast");
}

// recupero il riferimento al tasto del popup
function chiudiPopup(){
	$("#popup").css({display:"none"});
	//$("#popup").fadeOut("fast");
	return false;
}

function chiudiPannello(){
	// recupero il riferimento al tasto del pannello
	$("div")
	.filter(".servizio_tasti").click(
		function(){
		$("div").filter(".servizio").css({display:"none"});
		return false;
		}
	);
}

function mostraConferma(nr,titolo,messaggio,ok,ko){
	var panel_code = '<div class="servizio_titolo">' + titolo + '</div>' +
	'<div class="servizio_messaggio">'+messaggio+'</div>';
	var pageData = getPageData();
	var top = Math.round(((pageData[5]/2)-110)+pageData[1]);
	var left = Math.round(((pageData[4]/2)-170)+pageData[0]);
	document.getElementById(nr).innerHTML = panel_code + "<div class=\"servizio_tasti\"><a href=\"#\" onclick=\""+ok+"\">SI</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"#\" onclick=\""+ko+"\">NO</a></div>";
	document.getElementById(nr).style.left = left+"px";
	document.getElementById(nr).style.top = top+"px";
	document.getElementById(nr).style.display = 'block';
}

function mostraLoader() {
	var pageData = getPageData();
	var top = Math.round(((pageData[5]/2)-36)+pageData[1]);
	var left = Math.round(((pageData[4]/2)-154)+pageData[0]);
	$("#loader").css({left:left+"px",top:top+"px",display:"block"});
}
function chiudiLoader() {
	$("#loader").css({display:"none"});
}

function coloraCampo(campo){
	var num_campi = document.forms[0].elements.length;
	for (i=0; i < num_campi; i++){
		if (document.forms[0].elements[i].className != "off")
			document.forms[0].elements[i].style.backgroundColor='#FDFDFF';
	}
	document.getElementsByName(campo)[0].style.backgroundColor="#FFD4BB";
}

// -----------------------------------------------------------------------------------

//
// getPageData()
// Returns array with:
//  - x,y page scroll
//  - page width, height
//  - window width, height
// Core code from - quirksmode.com
//
function getPageData(){

	var x_Scroll, y_Scroll;

	if (self.pageYOffset) {
		y_Scroll = self.pageYOffset;
		x_Scroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		y_Scroll = document.documentElement.scrollTop;
		x_Scroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		y_Scroll = document.body.scrollTop;
		x_Scroll = document.body.scrollLeft;	
	}

	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
//	console.log(self.innerWidth);
//	console.log(document.documentElement.clientWidth);

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

//	console.log("xScroll " + xScroll)
//	console.log("windowWidth " + windowWidth)

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = xScroll;
	} else {
		pageWidth = windowWidth;
	}
//	console.log("pageWidth " + pageWidth)

	arrayPageData = new Array(x_Scroll,y_Scroll,pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageData;
}