//================= controllo cookie per funzioni ajax ===========
function testCookie(){
	if(document.cookie.indexOf("UTID") == -1){
		return false;	
		
	}else{
		return true;
		}
}

function charCalc(){
	currLen = document.getElementById('testo').value.length;
	rim = 160 - currLen;
	document.getElementById('rChar').innerHTML = rim;
}

//========================= FUNZIONI FORM REGISTRAZIONE UTENTE ============================//
//==================  verifica form registrazione utente =========================
function verRegUsr(){
	if(ver_form(9,'pwd,pwd2,nome,cognome,indirizzo,cap,citta,tel,mailVer','F_reg'))
	{
		if (chkEmail(document.getElementById("mail").value))
		{
			if(document.getElementById("acc_privacy").checked == true){
				if(document.getElementById("pwd").value != document.getElementById("pwd2").value)
				{
					
					alert("le password non corrispondono");
					return false;
				}		
			
			}
			else
			{
				
				alert("E' necessario dichiarare di aver letto l'informativa sulla privacy.");
				return false;
			}
		}
		else
		{
			return false;
		}
		
	}	
	else
	{
		return false;	
	}
}
function verModUsr(){
	if(ver_form(7,'nome,cognome,indirizzo,cap,citta,tel,mailVer','F_reg'))
	{
		if (chkEmail(document.getElementById("mail").value))
		{
			if(document.getElementById("pwd").value != document.getElementById("pwd2").value)
			{
				alert("le password non corrispondono");
				return false;
			}
		}
		else
		{
			return false;
		}
		
	}	
	else
	{
		return false;	
	}
}
function selNaz(){
	var a = document.getElementById("F_reg").nazione.selectedIndex;
	if (a==0)
	{
		myDiv = "box_prov";
		//italia
		sendLink('_sel_prov','GET','',myDiv);
		var txtNaz = "<input name=\"nazE\" type=\"hidden\" value=\"Italia\"/>";
		document.getElementById("box_city").innerHTML = "<input name=\"citta\" type=\"hidden\" value=\"\"/>";
		document.getElementById("box_nazE").innerHTML = txtNaz;
	}
	else
	{
		//altro
		var txt = "<input name=\"citta\" type=\"text\" size=\"40\" />";
		var txtProv = "<input name=\"prov\" type=\"hidden\" value=\"\" />";
		
		sendLink('_sel_Naz','GET','','box_nazE');
		document.getElementById("box_prov").innerHTML = txtProv;
		document.getElementById("box_city").innerHTML = txt;
	}
}
function sel_prov(){
	var obj = document.getElementById("prov");
	var ind = obj.selectedIndex;
	var val = obj.options[ind].value;
	myDiv = "box_city";
	sendLink('_sel_city','GET',"provID="+val,myDiv);
}
function selNaz_sped(){
	var a = document.getElementById("F_reg").nazione_sped.selectedIndex;
	if (a==0)
	{
		myDiv = "box_prov_sped";
		//italia
		sendLink('_sel_prov','GET','sped=1',myDiv);
		var txtNaz = "<input name=\"nazE_sped\" type=\"hidden\" value=\"Italia\"/>";
		document.getElementById("box_city_sped").innerHTML = "<input name=\"citta_sped\" type=\"hidden\" value=\"\"/>";
		document.getElementById("box_nazE_sped").innerHTML = txtNaz;
	}
	else
	{
		//altro
		var txt = "<input name=\"citta_sped\" type=\"tex\" size=\"40\" />";
		var txtProv = "<input name=\"prov_sped\" type=\"hidden\" value=\"\" />";
		
		sendLink('_sel_Naz','GET','sped=1','box_nazE_sped');
		document.getElementById("box_prov_sped").innerHTML = txtProv;
		document.getElementById("box_city_sped").innerHTML = txt;
	}
}
function sel_prov_sped(){
	var obj = document.getElementById("prov_sped");
	var ind = obj.selectedIndex;
	var val = obj.options[ind].value;
	myDiv = "box_city_sped";
	sendLink('_sel_city','GET',"provIDSped="+val+"&sped=1",myDiv);
}
function verMailEx(){
	var myEmail =document.getElementById("mail").value;
	var myDiv = "verMailBox";
	if(chkEmail(myEmail)){
		sendLink('verMailEx','GET',"em="+myEmail,myDiv);
	}
}





//========================  Inserimento prodotti nel carrello ==============================
function insCarr(a,b){
	fieldId = 'n'+a;
	myFieldVal = document.getElementById(fieldId).value;
	tSpanId = 'insP'+a;
	
	if(myFieldVal==""){
		alert("compilare i campi obbligatori");
		return false;
	}
	
	filtro = /^[1-9]/;
	if(validateIt(filtro,myFieldVal))
	{
		//clacolo n campi form
		for(i=1; i<document.F_insProd.getElementsByTagName('INPUT').length/2+1; i++)
		{
				fieldTemp = 'pulsante'+i;
				document.getElementById(fieldTemp).disabled = true;
		}
		sendLink('insProdCarr','GET',"nP="+b+"&qt="+myFieldVal+'&IdP='+a,tSpanId);
	}
	else
	{
		alert("Inserire un numero nel campo Q.ta'");
	}
}

//========================================================
//VAlidazione stringhe
//========================================================

function validateIt(a,b){
	regExpress = a;
	stringa = b;
	if(!regExpress.test(stringa)){
		return false;  
	}else{
		return true;
	}
}

//=================== controllo email =================================
function chkEmail(a){		
	EmailAddr = a;
	Filtro = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
	if (!Filtro.test(EmailAddr)){
		alert("Controlla l'indirizzo e-mail inserito");
		return false;
	}else{
		return true;
	}
}

//===========================      collapse DIV       =====================
//=======================================================================================

function collThis(idDiv){
	myDivEl = document.getElementById(idDiv);
	if(myDivEl.style.display=="none"){
		myDivEl.style.display='block';
	}else {
		myDivEl.style.display='none';
	}
}


//======funzione generica di controllo campi obbligatori =======================
//======a=N. campi obbligatori, b=array con nome campi, c= nome form =========================
function ver_form(a,b,c){	
	elementi = b.split(",");
	control = 0;
	for (var i = 0; i < a; i++) {			
		stringa='document.'+c+'.'+elementi[i]+'.value';
		nome='document.'+c+'.'+elementi[i]+'.name';
		if (eval(stringa)==''){
			alert("Attenzione, compilare i campi obbligatori");
			control=1;
			return false;
		}
	}
	return true;
}

//============================ PAGINE E FORM =========================================
var xmlHttp;
function createXMLHttpRequest() {
    if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    } 
    else if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }
}
//a = pagina, b = GET-POST  c=queryString d= div(non obbligatorio)
function startRequest(a,b,c,d) {
	createXMLHttpRequest();
	if(!d){
		myDiv = "pagina";	
	}else{
		myDiv = d;	
	}
	document.getElementById(myDiv).innerHTML ="&nbsp;&nbsp;<img src=\"./images/loader.gif\" alt=\"attendere...\"  style=\"width:14px; height:14px;\">";
	mya = a;
	myQStrn = c;
    xmlHttp.onreadystatechange = handleStateChange;
	var queryStr = null;
	
	//imposto  l'invio del form se la richiesta arriva come post
	if(b == 'POST'){
		var p_name = "./inc/" + a + ".cfm?timeS=" + new Date().getTime();
		xmlHttp.open(b, p_name, true);
		if(c){			
			queryStr = c;
		}
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		xmlHttp.send(queryStr);
	}else{
	//imposto la chiamata alla pagina se arriva come GET
		var p_name = "./inc/" + a + ".cfm?timeS=" + new Date().getTime();
		if(c){			
			var p_name = p_name+"&"+c;
		}
		//alert(c);
		xmlHttp.open(b, p_name, true);
		xmlHttp.send(null);
	}  
}    
function handleStateChange() {
	/*visualizaz div*/ //alert(myDiv);
    if(xmlHttp.readyState == 4) {
		if(xmlHttp.status == 200) {
			document.getElementById(myDiv).innerHTML = xmlHttp.responseText;
			afterResp(mya,myDiv,myQStrn);
		}		
	}
}

//=======================================================================================
//======================Funzioni da chiamare dopo il caricamento della pagina============
//=======================================================================================
function afterResp(myPage,myDiv,myQStrn){
	switch (myPage){
		case "insProdCarr":
			for(i=1; i<document.F_insProd.getElementsByTagName('INPUT').length/2+1; i++)
			{
					fieldTemp = 'pulsante'+i;
					document.getElementById(fieldTemp).disabled = false;
			}
			var str = myQStrn.replace(/([a-z0-9A-Z\W]+IdP=?)/g,'');
			str = "n"+str;
			document.getElementById(str).value = 1;
			//disabilito il pulsante
			var strP = myQStrn.replace(/nP=/g,'');
			strP = strP.replace(/&qt=.+/g,"");
			//alert(strP);
			var nomePuls = 'pulsante'+strP;
			document.getElementById(nomePuls).disabled = true;
			alert("prodotto inserito nel carrello")
		break;
	}
}


//=======================================================================================
//=====================================Invio link =======================================
//=======================================================================================
function sendLink(a,b,c,d){	
	//elimino un'eventuale istanza di mceTiny
	try{
		tinyMCE.execCommand('mceRemoveControl',false,'testoID');
		tinyMCE.execCommand('mceRemoveControl',false,'ImgHome');
	}
	catch(err){
		//alert(err);
		}
	startRequest(a,b,c,d);
}


//=======================================================================================
//invio dati FORM	a=nelementi obbligatori; b= nomi elementi obbligatori; c= div target, d= nome form, e= pagina //=======================================================================================
function sendForm(a,b,c,d,e){
	if(ver_form(a,b,d)){
		//elimino l'istanza mceTiny
		//alert(tinyMCE);
		try{
			tinyMCE.execCommand('mceRemoveControl',false,'testoID');
			tinyMCE.execCommand('mceRemoveControl',false,'ImgHome');
		}
		catch(err){
			//alert(err);
		}
		//alert("vai");
		if(document.getElementById("testoID")){
			mceTesto = document.getElementById("testoID").value;
			//alert(mceTesto);
		}
		formName ='document.'+d+'.elements.length' ;
		Nelementi =eval(formName);
		//alert(Nelementi);
		//alert("ok");
		qryStrn = "";
		for (var i = 0; i < Nelementi; i++) {
			tipo = 'document.'+d+'.elements['+i+'].type';
			nome = 'document.'+d+'.elements['+i+'].name';
			if(eval(tipo)=='radio' || eval(tipo)=='checkbox'){
				chk = 'document.'+d+'.elements['+i+'].checked';
				
				if(eval(chk)){
					valore =  'document.'+d+'.elements['+i+'].value';
					nome = eval(nome);
					valore = encodeURIComponent(eval(valore));	
					qryStrn = qryStrn+nome+"="+valore+"&";
				}
			}else{
				valore =  'document.'+d+'.elements['+i+'].value';
				nome = eval(nome);
				valore = encodeURIComponent(eval(valore));	
				qryStrn = qryStrn+nome+"="+valore+"&";
			}
		}
		//alert(qryStrn);
		startRequest(e,'POST',qryStrn,c);
	}
}
