/*Funzioni Per Jquery*/
$(document).ready(
	function () {
		applicaAlLoad();
	}
);

idCrescenteRisposte=1;idCrescenteDomande=1;
//Funzioni richiamate direttamente al loading
function applicaAlLoad(idElemento){
	if(idElemento!=null&&idElemento!=undefined){
		if(idElemento.substr(0,1)!="#") idElemento="#"+ idElemento;
		idElemento+=" ";
	}
	else
		idElemento="";

	//Verifico le form
	$(idElemento +"form.verificaForm").submit(function(){
		/*if(this.id=='moduloCaricaContenuti')
			$("#moduloCaricaContenuti img.hidden").show();*/
		return verificaForm(this.id);
	});
	$("#frm_edit_questionari select.compilaData").change(function(){
		$("#frm_edit_questionari input#dataCompilata").val($("#frm_edit_questionari select#dataCompilataD").val()+"-"+$("#frm_edit_questionari select#dataCompilataM").val()+"-"+$("#frm_edit_questionari select#dataCompilataY").val())
	});
	
	setTimeout(function() {fading();}, 3000);
	setTimeout(function() {fadingEle();}, 3300);
	setTimeout(function() {fadingEly();}, 3100);
	setTimeout(function() {fadingElyp();}, 3400);
	
}

function fading(){
	posCurr++;
	if(posCurr>=arrSfondi.length)
		posCurr=0;
	
	
	currImg=arrSfondi[posCurr];
	$("<div class=\"tmpDiv\">&nbsp;</div>").css("background-image","url(../images/home/fascia_isotec/"+ currImg +")").appendTo("#fasciaIsotec").fadeIn("slow",function(){
		$("#fasciaIsotec img").attr("src","../images/home/fascia_isotec/"+ currImg);
		$(this).remove();
	});
	
	setTimeout(function() {fading();}, 3000);
}
function fadingEle(){
	posCurrEle++;
	if(posCurrEle>=arrSfondiEle.length)
		posCurrEle=0;
	
	currImgEle=arrSfondiEle[posCurrEle];
	$("<div class=\"tmpDiv\">&nbsp;</div>").css("background-image","url(../images/home/fascia_elettrotegola/"+ currImgEle +")").appendTo("#fasciaIsotec2").fadeIn("slow",function(){
		$("#fasciaIsotec2 img").attr("src","../images/home/fascia_elettrotegola/"+ currImgEle);
		$(this).remove();
	});
	
	setTimeout(function() {fadingEle();}, 3300);
}
function fadingEly(){
	posCurrEly++;
	if(posCurrEly>=arrSfondiEly.length)
		posCurrEly=0;
	
	currImgEly=arrSfondiEly[posCurrEly];
	$("<div class=\"tmpDiv\">&nbsp;</div>").css("background-image","url(../images/home/fascia_elycold/"+ currImgEly +")").appendTo("#fasciaElycold").fadeIn("slow",function(){
		$("#fasciaElycold img").attr("src","../images/home/fascia_elycold/"+ currImgEly);
		$(this).remove();
	});
	
	setTimeout(function() {fadingEly();}, 3100);
}
function fadingElyp(){
	posCurrElyp++;
	if(posCurrElyp>=arrSfondiElyp.length)
		posCurrElyp=0;
	
	currImgElyp=arrSfondiElyp[posCurrElyp];
	$("<div class=\"tmpDiv\">&nbsp;</div>").css("background-image","url(../images/home/fascia_elycop/"+ currImgElyp +")").appendTo("#fasciaElyplast").fadeIn("slow",function(){
		$("#fasciaElyplast img").attr("src","../images/home/fascia_elycop/"+ currImgElyp);
		$(this).remove();
	});
	
	setTimeout(function() {fadingElyp();}, 3400);
}


//Funzioni standard
function chiediConferma(anchor){
	if (confirm("Sei sicuro? L'operazione non potra' essere annullata")){
		anchor.href += '&conferma=1';
		return true;
	}
	return false;
}

function in_array(thaArray, elem) {
	for (var i=0; i<thaArray.length && thaArray[i]!=elem; i++);
	return thaArray[i]==elem;
}
function find_in_array(thaArray, elem) {
    for (var i = 0; i < thaArray.length ; i++) {
        if (thaArray[i] == elem) return i;
    }
}

//Stringhe dei messaggi di errore dei form
var erroriF = new Array();
erroriF['obblText']="non puņ essere vuoto";
erroriF['obblOption']="deve essere selezionato";
erroriF['obblMail']="non contiene un indirizzo mail valido";
erroriF['obblData']="non contiene una data valida";
erroriF['obblCheck']="deve essere selezionato";

function mostraMessaggio(tipologia,titoloMsg,msg,classe,idDiv){
	/*	TIPOLOGIA:	1= Creo div centrato
					2= Mostro alert classico
					3= Mostro in un div esistente {serve anche l'idDiv}
		CLASSE:		Parametro per la classe del div in cui mostro il messaggio*/
	if(tipologia==1){
		if (window.innerHeight)
			pos = window.pageYOffset;
		else if (document.documentElement && document.documentElement.scrollTop)
			pos = document.documentElement.scrollTop;
		else if (document.body)
			pos = document.body.scrollTop;
		topo=pos+204;
		html="<div id=\"mostraErrori\" class=\""+ classe +"\" style=\"top:"+ topo +"px;\"><div class=\"intestazione_popup\"><img src=\"images/titoli/"+ titoloMsg +".gif\" title=\""+ titoloMsg +"\" alt=\""+ titoloMsg +"\" /><a href=\"javascript:void(0)\" class=\"chiudiDivErrori\"><img src=\"images/struttura/close_default.gif\" name=\"chiudi\" title=\"CHIUDI\" alt=\"CHIUDI\" onMouseOut=\"MM_swapImgRestore()\" onMouseOver=\"MM_swapImage('chiudi','','images/struttura/close_hover.gif',0)\" /></a><br style=\"clear:both\" /></div><br><span class=\"dim3\">"+ msg +"<br /><br><input type=\"button\" class=\"button buttonChiaro fisso chiudiMessaggio\" value=\"chiudi\"><br></span></div>";
		//$("body").append(html);
		$(html).appendTo("body").hide().slideDown("slow");
		$(".chiudiDivErrori, .chiudiMessaggio").click(function(){$(".campoErrore:first").focus();$("#mostraErrori").remove();});
	}
	else if(tipologia==2)
		alert(titoloMsg.replace("<br>","\n") +"\n"+ msg.replace("<br>","\n"));
	else if(tipologia==3)
		$("#"+ idDiv).html(titoloMsg +"<br>"+ msg);
}

function verificaForm(idForm){
	var campiVerificati= new Array(); //Per evitare di controllare piu' volte lo stesso campo
	formCorretto=true;	strErr="";
	$("form#"+ idForm +" :input").filter("[type!='submit']").filter("[type!='reset']").each(function(){
		//Verifico cosa devo controllare del campo
		inName=$(this).attr("name");		inClass=$(this).attr("class");
		inLabel=$(this).parent().html().replace(/<[^>]*>.?(<[^>]*>)?/g, "").replace(/(\n)*(\t)*/g, ""); //Prendo la label e tolgo tutti i tag html
		if(inLabel=="&nbsp;"||inLabel=="nbsp;") inLabel=inName;
		inArrClass= inClass.split(" ");		inStrErr="";
		//Ogni campo va controllato una sola volta. Quindi verifico che il nome non sia gia' nell'array
		if(!in_array(campiVerificati, inName)){
			//Verifico per ogni campo le classi di controllo
			$.each( inArrClass, function(i, n){
				if(n.substring(0,4)=='obbl'){
					//Per le date utilizzare un campo Hidden che si autocompila al change delle select --> Verificare solo quello
					if(verificaCampo(idForm, inName,n)){
						//Caso speciale
						if(inName=='id_domande' && idForm=='frm_edit_questionari')
							inStrErr+="E' obbligatorio inserire domande nel questionario";
						else{
							inStrErr+=inStrErr!='' ? " e " : "Il campo "+ inLabel;
							inStrErr+=" "+ erroriF[n];
						}
						$("form#"+ idForm +" [name='"+ inName +"']").addClass("campoErrore");
					}
				}
			});
			if (inStrErr.length)
				strErr+=strErr!='' ? "<br>"+ inStrErr : inStrErr;
			campiVerificati.push(inName);
		}
	});
	//Si e' verificato un errore nel form: Mostro il messaggio di errore
	if(strErr.length){
		formCorretto=false;
		mostraMessaggio(2,"avviso",strErr,"negativo");
	}
	return formCorretto;
}

//Verifico il campo
function verificaCampo(idForm, inName,cosaVerifico){
	inpValue	=	$("#"+ idForm+" [name='"+ inName +"']").val();
	switch(cosaVerifico){
		case "obblText":
			if(inpValue=="")	return true;
			break;
		case "obblOption":
			if(inpValue=="--"||inpValue=="0")	return true;
			break;
		case "obblMail":
			if(!inpValue.match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})$/))	return true;
			break;
		case "obblData":
			//Formato della data dd-mm-yyyy. il separatore puo' essere qualsiasi carattere.
			obj=inpValue.replace(/[^\d]/g,"0");
			gg=obj.substr(0,2);	mm=obj.substr(3,2);	aa=obj.substr(6,4);
			strdata=gg+"/"+mm+"/"+aa;
			dteDate=new Date(aa,mm-1,gg);
			daa=dteDate.getFullYear().toString();
			dmm=(dteDate.getMonth()+1).toString();
				dmm=dmm.length==1?"0"+dmm:dmm
			dgg=dteDate.getDate().toString();
				dgg=dgg.length==1?"0"+dgg:dgg
			dddata=dgg+"/"+dmm+"/"+daa
			
			if (dddata!=strdata){
				return true;
			}
			break;
		case "obblCheck":
			if(!$("#"+ idForm+" [name='"+ inName +"']:checked").length)	return true;
			break
	}
	return false;
}
