/*Funzioni Per Jquery*/
$(document).ready(
	function () {
		applicaAlLoad();
	}
);

//Funzioni richiamate direttamente al loading
function applicaAlLoad(idElemento){
	if(idElemento!=null&&idElemento!=undefined){
		if(idElemento.substr(0,1)!="#") idElemento="#"+ idElemento;
		idElemento+=" ";
	}
	else
		idElemento="";

	//Conferma
	$(idElemento +".chiediConferma").click(function(){
		return chiediConferma(this);
	});
	
	
	//Mostro o nascondi i div al click su un link con class shd. Parametri: Tipo di link, Tipo di comparsa del div, Id del div
	//shd01biblio
	$("a[class*='shd']").click(function(){
		classe=$(this).attr("class");
		myregexp = new RegExp(/(shd[^ ]*)/);
		mymatch = myregexp.exec(classe);
		if(mymatch!=null){
			valore=mymatch[1].replace("shd","");
			tipologia=valore.substring(0,1);comparsa=valore.substring(1,2);idDiv=valore.substring(2);
			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;
			
			$("#"+ idDiv).css("top",topo);
			
			if($("#"+ idDiv).is(":hidden")){
				if(tipologia=='1') $(this).html(str_dettaglio_giorni);
				if(comparsa=='1') $("#"+ idDiv).slideDown("slow");
				else if(comparsa=='2') $("#"+ idDiv).show();
			}
			else{
				if(tipologia=='2' && comparsa=='1')
					$("#"+ idDiv).slideToggle("slow",function(){
						$("#"+ idDiv.replace("campoEsteso","menoEsteso")).show();
					});
				else{
					if(tipologia=='1') $(this).html(str_dettaglio_giorni);
					if(comparsa=='1') $("#"+ idDiv).slideToggle("slow");
					else if(comparsa=='2') $("#"+ idDiv).hide();
				}
			}
			return false;
		}	
	});
	
	//Verifico Form
	$("form.verificaForm").submit(function(){
		return verificaForm(this.id);
	});
	
	//Centro il div mostraMessaggio
	cssMessaggio("mostraMessaggioPage");
	
	//Cambio il numero di camere minimo in base agli utenti
	$("#frm_n_adulti").change(function(){
		num_option=$("#frm_quantocamere option").length; 
		if($(this).val()>1){
			if(num_option<3)
				$("#frm_quantocamere").append("<option value=\"2\">2</option>");
		}
		else{
			$("#frm_quantocamere option[value='2']").remove();
		}
	});
	$(".linkCal").click(function(){
		id=$(this).attr("id").replace("linkCal","");
	  	msg=$("#calendario"+ id).html();
		mostraMessaggio(1,str_dettaglio_tariffa,msg,"positivo");
	});
	//
	$(".calcolaCamere").change(function(){
		quanti=0;
		$(".calcolaCamere").each(function(){
			quanti+=Number($(this).val());
		});
		$("#totCamere").val(quanti);
	});
	
	$("#frm_ccdatam, #frm_ccdatay").change(function(){
		var month=new Array(12);
		month[0]="31";
		month[1]="28";
		month[2]="30";
		month[3]="30";
		month[4]="31";
		month[5]="30";
		month[6]="31";
		month[7]="31";
		month[8]="30";
		month[9]="31";
		month[10]="30";
		month[11]="31";
		
		mm=$("#frm_ccdatam").val();	aa=$("#frm_ccdatay").val();
		dd=month[mm-1];							
		
		strData=dd +"-"+ mm +"-"+ aa;
		$("#frm_dataValidita").val(strData);
	});
	
	/*$(".boxPrenota .submitLogin").click(function(){
		mostraMessaggio(1,"Attenzione","<strong>La sezione non &egrave; al momento disponibile.</strong><br>Ci scusiamo per il disagio.","negativo");
		return false;
	});*/
	
	$("#policyCancellazione a").click(function(){
		testo=$("#testoPrivacy").html();
		mostraMessaggio(1,str_termini_condizioni,testo,"negativo");
	});
	
	$("#data_arrivo").change(function(){
		dataa=$("#data_arrivo").val();
		datab=$("#data_partenza").val();

		var aDataA = dataValida(dataa);
		var aDataB = dataValida(datab);
		var differenza='';
		if(aDataA && aDataB)
			differenza=dateDiff(aDataA,aDataB);
			
		if(differenza>0){
			var adata = dataa.split('-');
			var gg = parseInt(adata[0],10);
			var mm = parseInt(adata[1],10);
			var aaaa = parseInt(adata[2],10);
			var xdata = new Date(aaaa,mm-1,gg+1);
			ggiorno	= xdata.getDate();
			mmese	= Number(xdata.getMonth()+1);
			aanno	= xdata.getFullYear();

			if(ggiorno<10)	ggiorno="0"+ ggiorno;
			if(mmese<10)	mmese="0"+ mmese;
			
			datab=ggiorno +"-"+ mmese +"-"+ aanno;
			$("#data_partenza").val(datab);
		}
	});
	

}
function dateDiff(dataa,datab){
		var diffMilli = dataa.getTime()-datab.getTime();
		var divisore = 86400000;
		return Math.round(diffMilli/divisore);
	}
	function dataValida(txt){
	var re = /^\d{1,2}\-\d{1,2}\-\d{4}$/
	if(re.test(txt)){
		var adata = txt.split('-');
		var gg = parseInt(adata[0],10);
		var mm = parseInt(adata[1],10);
		var aaaa = parseInt(adata[2],10);
		var xdata = new Date(aaaa,mm-1,gg)
		if((y2k(xdata.getYear())==aaaa) && (xdata.getMonth()==mm-1) && (xdata.getDate()==gg))
			return xdata
		else return false
	}else return false
}

function y2k(number) { 
	return (number < 1000) ? number + 1900 : number; 
}

function ___getPageSize() {
	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;
	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;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
};
function ___getPageScroll() {
	var xScroll, yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}
	arrayPageScroll = new Array(xScroll,yScroll);
	return arrayPageScroll;
};


function in_array(thaArray, elem) {
	for (var i=0; i<thaArray.length && thaArray[i]!=elem; i++);
	return thaArray[i]==elem;
}

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){
		// Hime some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
		$('embed, object, select').css({ 'visibility' : 'hidden' });
		$("body").append("<div id=\"velinaMessaggio\">&nbsp;</div><div id=\"mostraMessaggio\"><div class=\"dim2 "+ classe +"\">"+ titoloMsg +"</div><span class=\"dim3\">"+ msg +"<br /><br /><a href=\"javascript:void(0)\" class=\"chiudiDivMessaggio\">"+ str_chiudi +"</a></span></div>");
		cssMessaggio("mostraMessaggio");
	}
	else if(tipologia==2)
		alert(titoloMsg.replace("<br />","\n") +"\n"+ msg.replace("<br />","\n"));
	else if(tipologia==3)
		$("#"+ idDiv).html(titoloMsg +"<br />"+ msg);
}
function cssMessaggio(id){
	var arrPageSizes = ___getPageSize();
	var arrPageScroll= ___getPageScroll();
	$("#"+id).hide();
	altoPage=arrPageSizes[3];					largoPage=arrPageSizes[2];
	alto=$("#"+id).height();					largo=$("#"+id).width();
	topo=((altoPage-alto)/2)+arrPageScroll[1];	
	lefto=((largoPage-largo)/2)+arrPageScroll[0];
	$("#velinaMessaggio").hide().css({ 
			backgroundColor: '#000', opacity:'0.8', width: arrPageSizes[0], height: arrPageSizes[1]
		}).fadeIn(
		function(){$("#"+id).hide().css({top:topo,left:lefto}).show();}
	);
	$(".chiudiDivMessaggio,#velinaMessaggio").click(function(){ killMessaggio();});

	$(window).resize(function() {
		// Get page sizes
		var arrPageSizes = ___getPageSize();
		var arrPageScroll= ___getPageScroll();
		altoPage=arrPageSizes[3];					largoPage=arrPageSizes[2];
		alto=$("#"+id).height();					largo=$("#"+id).width();
		topo=((altoPage-alto)/2)+arrPageScroll[1];	
		lefto=((largoPage-largo)/2)+arrPageScroll[0];
		// Style overlay and show it
		$('#velinaMessaggio').css({
			width:		arrPageSizes[0],
			height:		arrPageSizes[1]
		});
		// Get page scroll
		var arrPageScroll = ___getPageScroll();
		// Calculate top and left offset for the jquery-lightbox div object and show it
		$("#"+id).css({
			top:	topo,
			left:	lefto
		});
	});
}
function killMessaggio(){
	$(".campoErrore:first").focus();
	$('embed, object, select').css({ 'visibility' : 'visible' });
	$("#mostraMessaggio").remove();
	$("#mostraMessaggioPage").remove();
	$("#velinaMessaggio").fadeOut(function() { $("#velinaMessaggio").remove(); });
}

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");	inId=$(this).attr("id");
		inLabel=$("label[for='"+ inId +"']").html();	inTitle=$(this).attr("title");
		if(inLabel!=null){
			inLabel=inLabel.replace(/(<[^>]*>).*(<[^>]*>)?/g, "").replace(/(\n)*(\t)*/g, "").replace("*","").replace(" {2,*}"," "); //Prendo la label e tolgo tutti i tag html
			if(!inLabel.length)		inLabel= (inTitle!=null&&inTitle!='')? inTitle : inName;
		}
		else						inLabel= (inTitle!=null&&inTitle!='')? inTitle : 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)){
						inStrErr+=inStrErr!='' ? " "+ str_e +" " : str_il_campo +" <strong>"+ inLabel;
						inStrErr+="</strong> "+ erroriF[n];
						$("form#"+ idForm +" [name='"+ inName +"']").addClass("campoErrore");
					}
				}
				else if(n=='minimoCamere'){
					if($("#frm_quantocamere").val()<$("#"+inId).val()){
						inStrErr+=inStrErr!='' ? " e " : + str_numero_camere +" ";
						inStrErr+=" "+ str_maggiore_di +" "+ $("#frm_quantocamere").val();
						$("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(1,str_errori_modulo,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 "obblDataSucc":
			datab=$("#frm_dataCorrenteValidita").val();
			dataa=$("#frm_dataValidita").val();
			var aDataA = dataValida(dataa);
			var aDataB = dataValida(datab);
			var differenza='';
			if(aDataA && aDataB)
				differenza=dateDiff(aDataA,aDataB);
			
			if(differenza<0) return true;
			break
		case "obblCheck":
			if(!$("#"+ idForm+" [name='"+ inName +"']:checked").length)	return true;
			break;
		case "obblCC":
			var aRulerz = new Array(); 
			var aCNames = new Array(); 
			var myReturn = false;
			var daField='numero'; //campo numero carta credito
			aCNames = ["MASTERCARD","VISA","AMERICAN EXPRESS","DINERS","JCB","DICOVER","ENROUTE"];
			aRulerz[aCNames[0]] = new Array("16"  ,"51:52:53:54:55");
			aRulerz[aCNames[1]] = new Array("13:16"  ,"4");
			aRulerz[aCNames[2]] = new Array("15"  ,"34:37");
			aRulerz[aCNames[3]] = new Array("14"  ,"300:301:302:303:304:305:36:38");
			aRulerz[aCNames[4]] = new Array("16"  ,"3088:3096:3112:3158:3337:3528:2131:1800");
			aRulerz[aCNames[5]] = new Array("16"  ,"6011");
			aRulerz[aCNames[6]] = new Array("15"  ,"2014:2149");
			//combo tipo carta credito
			var count=aCNames.length;
			if($("#"+ idForm+" [name='"+ inName +"']:checked").length)
				var daType = $("#"+ idForm+" [name='"+ inName +"']:checked").val();
			else
				var daType="MASTERCARD";
			//recupero numero carta
			var CardNumber=$("#"+ idForm+" [name='ccnumero']").val();
			//verifico numero
			var cType = daType;
			var no_digit = CardNumber.length;
			var oddoeven = no_digit & 1;
			var sum = 0; 
			var pat = false;
			var cln=false; 
			var ldn=false;
			
			for (var count = 0; count < no_digit; count++){
				var digit = parseInt(CardNumber.charAt(count));
				if (!((count & 1) ^ oddoeven)){
					digit *= 2;
					if (digit > 9)digit -= 9;
				}
				sum += digit;
			}
			
			if (sum % 10 == 0){
				var aCln = aRulerz[ cType][0].split(":");
				var aLdn = aRulerz[ cType][1].split(":");
		
				for(var i=0; i<aCln.length; i++){
					if(aCln[i]==no_digit){
						cln=true; 
						break
					}
				}
		
				for(var i=0; i<aLdn.length; i++){
					if(CardNumber.indexOf(aLdn[i])==0){
						ldn=true; 
						break
					}
				}
			}
		  
			if (sum % 10 == 0 && cln == true && ldn==true)
				return false;
			else
				return true;
			break;
	}
	return false;
}
