function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}
 
function getCookie(c_name)
{
	if (document.cookie.length>0)
	{
		  var c_start=document.cookie.indexOf(c_name + "=");
		  if (c_start!=-1)
		  {
		  		c_start=c_start + c_name.length+1;
				var c_end=document.cookie.indexOf(";",c_start);
				if (c_end==-1) c_end=document.cookie.length;
				return unescape(document.cookie.substring(c_start,c_end));
		  }
	}
	return null;
}
 
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function checkCookie()
{
	var numPagineVisualizzate = getCookie('numPagineVisualizzateNessos');
	if (jQuery.trim(numPagineVisualizzate) != null && jQuery.trim(numPagineVisualizzate) != "")
  		return jQuery.trim(numPagineVisualizzate);
  	else
		return null;
}

function resetInput(id, defaultValue, hasDefaultValue)
{
	var el = document.getElementById(id);
	if(el.value == '')
	{
		if(hasDefaultValue)
			el.value = defaultValue;
		else
			el.value = '';
		jQuery("#"+id).css('color', '#ACAEAF');
	}else if(el.value == defaultValue || el.value == 'Valore richiesto' || el.value == 'Valore errato' || el.value == 'Formato errato')
	{
		el.value = '';
		jQuery("#"+id).css('color', '#ACAEAF');
	}
}

function resetPassword(id, defaultValue, hasDefaultValue)
{
	var el = document.getElementById(id);
	if(el.value == '')
	{	
		jQuery("#label_"+id).css('color', '#ACAEAF');
		if(jQuery("#label_"+id).css('display') == 'none')
			jQuery("#label_"+id).css('display', 'inline');
		else
			jQuery("#label_"+id).css('display', 'none');
	}else 
	{
		jQuery("#label_"+id).css('color', '#ACAEAF');
		jQuery("#label_"+id).css('display', 'none');
	}
}

function controllaCorrettezza(id)
{
	var value = document.getElementById(id).value;
	if((value.indexOf("/") != -1)&&
			(value.indexOf("\\") != -1)&&
			(value.indexOf(":") != -1)&&
			(value.indexOf("?") != -1)&&
			(value.indexOf("*") != -1)&&
			(value.indexOf("<") != -1)&&
			(value.indexOf(">") != -1)&&
			(value.indexOf(" ") != -1)&&
			(value.indexOf("|") != -1))
	{
		return false;
	}else
	{
		return true;
	}
}

function MaxCaratteri(id, MaxLen)
{
	value = document.getElementById(id).value;
	if(value.length <= MaxLen)
	{
		return true;
	}else
	{
		document.getElementById(id).value = value.substring(0, value.length-1);
		return false;
	}
}

function checkSearch(defaultValue)
{
	var value = document.getElementById('word').value;
	document.getElementById('word').style.color = '#ACAEAF';
	if(jQuery.trim(value) != '' && jQuery.trim(value) != defaultValue)
	{
		jQuery("#searchForm").submit();
	}else
	{
		document.getElementById('word').style.color = '#FF0000';
		document.getElementById('word').value = defaultValue;
	}		
}

var count_error = 0;
function checkLogin()
{
	count_error = 0;
	checkEmail('user', 'email');
	checkPassword('pwd', 'password');
	if(count_error == 0)
	{
		jQuery.ajax({
		   type: "POST",
		   url: url_site + "templates/nessos/checkLogin.php",
		   data: "u=" + jQuery.base64Encode(jQuery("#user").val()) + "&p=" + jQuery.base64Encode(jQuery("#pwd").val()),
		   cache: false,
		   async: false,
		   success: function(html)
		   {
		       if(parseInt(html) == 1)
				{
					jQuery("#loginForm").submit();
				}else
				{
					openDinamicAlert('dinamic_alert', 'Attenzione!!', 'I dati inseriti non consentono di eseguire il login');	
				}
		   }
		 });
	}
}

function checkUpdatePassword()
{
	count_error = 0;
	checkField('updatepwd');
	if(lastPassword == jQuery("#updatepwd").val()) return;
	lastPassword = jQuery("#updatepwd").val();
	if(count_error == 0)
	{
		jQuery.ajax({
		   type: "POST",
		   url: url_site + "templates/nessos/updatePassword.php",
		   data: "idu=" + idUtente + "&p=" + jQuery.base64Encode(jQuery("#updatepwd").val()),
		   cache: false,
		   async: false,
		   success: function(html)
		   {
			    closeAlert('change_password');
		        if(parseInt(html) == 1)
				{
					jQuery("#change_password").attr('firstlogin', 1);
					openDinamicAlert('dinamic_alert', 'Complimenti!!', 'L\'aggiornamento della password &egrave; andato a buon fine');
				}else
				{
					openDinamicAlert('dinamic_alert', 'Attenzione!!', 'Errore nell\'aggiornamento dei dati');	
				}
		   }
		 });
	}
}

function openRegistrazioneAlert()
{
	document.getElementById('box_login').style.display = 'none';
	document.getElementById('privacy').checked = "checked";
	jQuery("#privacy_error").css('display', 'none');
	jQuery("#emailreg").attr('disabled', '');
	resetField('nome', 'nome', false);
	resetField('cognome', 'cognome', false);
	resetField('telefonoreg', 'telefono', false);
	resetField('emailreg', 'email', false);
	resetField('passwordreg', 'password', true);
	openAlert('registrazione_alert');
}

var idProdottoAmico = 0;
function openInviaAmico(idProdotto)
{
	if(jQuery("#dinamic_alert").css('display') != "none") jQuery("#dinamic_alert").hide();
	idProdottoAmico = idProdotto;
	resetField('tuonome', 'tuo nome', false);
	resetField('suonome', 'suo nome', false);
	resetField('tuaemail', 'tua email', false);
	resetField('suaemail', 'sua email', false);
	openAlert('invia_amico_alert');
}

function checkInviaAmico()
{
	count_error = 0;
	jQuery(".btn_invia_amico").attr('href', 'javascript:void(0)');
	checkField('tuonome', 'tuo nome');
	checkField('suonome', 'suo nome');
	checkEmail('tuaemail', 'tua email');
	checkEmail('suaemail', 'sua email');
	if(count_error == 0)
	{
		jQuery.ajax({
		   type: "POST",
		   url: url_site + "templates/nessos/inviaAmico.php",
		   data: "te=" + jQuery.base64Encode(jQuery("#tuaemail").val()) + "&se=" + jQuery.base64Encode(jQuery("#suaemail").val()) + "&tn=" + jQuery.base64Encode(jQuery("#tuonome").val()) + "&sn=" + jQuery.base64Encode(jQuery("#suonome").val()) + "&idp="+idProdottoAmico,
		   cache: false,
		   async: false,
		   success: function(html)
		   {
			    jQuery(".btn_invia_amico").attr('href', 'javascript:checkInviaAmico()');
		   		closeAlert('invia_amico_alert');
		        if(parseInt(html) == 1)
				{
					openDinamicAlert('dinamic_alert', 'Complimenti!!', 'Il prodotto &egrave; stato consigliato a '+jQuery("#suonome").val() + '.<br><br>Per eseguire di nuovo l\'operazione <a href="javascript:openInviaAmico('+idProdottoAmico+')">clicca qui</a>.' );	
				}else 
				{
					openDinamicAlert('dinamic_alert', 'Attenzione!!', 'Errore');	
				}
		   }
		 });
	}else jQuery(".btn_invia_amico").attr('href', 'javascript:checkInviaAmico()');
}

function checkRegistrazione()
{
	count_error = 0;
	jQuery(".btn_registrazione").attr('href', 'javascript:void(0)');
	checkField('nome', 'nome');
	checkField('cognome', 'cognome');
	checkNumber('telefonoreg', 'telefono');
	checkEmail('emailreg', 'email');
	checkPassword('passwordreg', 'password');
	checkCheckbox('privacy');
	if(count_error == 0)
	{
		jQuery.ajax({
		   type: "POST",
		   url: url_site + "templates/nessos/richiediRegistrazione.php",
		   data: "e=" + jQuery.base64Encode(jQuery("#emailreg").val()) + "&p=" + jQuery.base64Encode(jQuery("#passwordreg").val()) + "&n=" + jQuery.base64Encode(jQuery("#nome").val()) + "&c=" + jQuery.base64Encode(jQuery("#cognome").val()) + "&t=" + jQuery.base64Encode(jQuery("#telefonoreg").val()),
		   cache: false,
		   async: false,
		   success: function(html)
		   {
			    jQuery(".btn_registrazione").attr('href', 'javascript:checkRegistrazione()');
		   		closeAlert('registrazione_alert');
		        if(parseInt(html) == 1)
				{
					if(idUtente > 0)  openDinamicAlert('dinamic_alert', 'Complimenti!!', 'L\'aggiornamento dei dati &egrave; andato a buon fine');
					else openDinamicAlert('dinamic_alert', 'Complimenti!!', 'La registrazione &egrave; andata a buon fine');	
				}else if(parseInt(html) == 2)
				{
					openDinamicAlert('dinamic_alert', 'Attenzione!!', 'L\'email inserita &egrave; gi&agrave; stata utilizzata per un altro account');
				}else
				{
					openDinamicAlert('dinamic_alert', 'Attenzione!!', 'Errore nella registrazione');	
				}
		   }
		 });
	}else jQuery(".btn_registrazione").attr('href', 'javascript:checkRegistrazione()');
}

function checkRecovery()
{
	count_error = 0;
	checkEmail('emailrec', 'email');
	if(count_error == 0)
	{
		jQuery.ajax({
		   type: "POST",
		   url: url_site + "templates/nessos/recoveryPassword.php",
		   data: "e=" + jQuery.base64Encode(jQuery("#emailrec").val()),
		   cache: false,
		   async: false,
		   success: function(html)
		   {
		   		chiudiLogin();
		   		if(parseInt(html) == 1)
				{
					openDinamicAlert('dinamic_alert', 'Complimenti!!', 'La password &egrave; stata inviata all\'indirizzo email ' + jQuery("#emailrec").val());	
				}else if(parseInt(html) == 2)
				{
					openDinamicAlert('dinamic_alert', 'Attenzione!!', 'L\'email inserita non identifica nessun account per accedere al sito.');	
				}else
				{
					openDinamicAlert('dinamic_alert', 'Attenzione!!', 'Errore nell\'invio della richiesta');	
				}
				resetField('user', 'username', false);
				resetField('pwd', 'password', true);
				resetField('emailrec', 'email', false);
		   }
		 });
	}
}

function checkCheckbox(id)
{
	jQuery("#"+id+"_error").css('display', 'none');
	if(!document.getElementById(id).checked)
	{
		count_error = count_error + 1;
		jQuery("#"+id+"_error").css('display', 'inline');
	}
}

function resetField(id, defaultValue, isPassword)
{
	if(!isPassword)
	{
		document.getElementById(id).style.color = '#ACAEAF';
		document.getElementById(id).value = defaultValue;
	}else
	{
		document.getElementById(id).value = '';
		jQuery("#label_"+id).css('visibility', 'visible');
		jQuery("#label_"+id).css('display', 'inline');
		jQuery("#label_"+id).css('color', '#ACAEAF');
		jQuery("#label_"+id).val(defaultValue);
	}
}

function checkField(id, defaultValue)
{
	var value = document.getElementById(id).value;
	document.getElementById(id).style.color = '#ACAEAF';
	if(jQuery.trim(value) == '' || jQuery.trim(value) == defaultValue || jQuery.trim(value) == 'Valore richiesto')
	{
		count_error = count_error + 1;
		document.getElementById(id).style.color = '#FF0000';
		//document.getElementById(id).value = 'Valore richiesto';
	}
}

function checkNumber(id, defaultValue)
{
	var value = document.getElementById(id).value;
	document.getElementById(id).style.color = '#ACAEAF';
	if(jQuery.trim(value) == '' || jQuery.trim(value) == defaultValue || jQuery.trim(value) == 'Valore richiesto' || isNaN(value))
	{
		count_error = count_error + 1;
		document.getElementById(id).style.color = '#FF0000';
		//document.getElementById(id).value = 'Valore richiesto';
	}
}

function checkPassword(id, defaultValue)
{
	var value = document.getElementById(id).value;
	document.getElementById(id).style.color = '#ACAEAF';
	jQuery("#label_"+id).val('');
	jQuery("#label_"+id).css('color', '#ACAEAF');
	if(jQuery.trim(value) == '' || jQuery.trim(value) == defaultValue)
	{
		count_error = count_error + 1;
		jQuery("#label_"+id).val(defaultValue);
		jQuery("#label_"+id).css('color', '#FF0000');
		//document.getElementById(id).style.color = '#FF0000';
		document.getElementById(id).value = '';
	}
}

function checkEmail(id, defaultValue)
{
	var value = document.getElementById(id).value;
	document.getElementById(id).style.color = '#ACAEAF';
	var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
	if(jQuery.trim(value) == '' || jQuery.trim(value) == defaultValue)
	{
		count_error = count_error + 1;
		document.getElementById(id).style.color = '#FF0000';
		document.getElementById(id).value = defaultValue;
	}else if (!filter.test(value))
	{
		count_error = count_error + 1;
		document.getElementById(id).style.color = '#FF0000';
		document.getElementById(id).value = 'Formato errato';
	}
}

function checkID(id, arr)
{
	var i=0;
	var ok = false;
	while((i < arr.length)&&(!ok))
	{
		if(arr[i] == id)
		{
			ok = true;	
		}else
		{
			i = i + 1;
		}
	}
	return i;
}

function ricreaArray(array, indice)
{
	var newArray = new Array();
	if(indice == 0)
	{
		if(array.length > 1)
			newArray = array.slice(1, array.length);
	}else
	{
		newArray = array.slice(0, indice);
		if(indice < array.length)
		{
			var array1 = array.slice(indice+1, array.length);
			for(var i = 0; i < array1.length; i++)
				newArray.push(array1[i]);
		}
	}
	return newArray;
}

function validateEmail(elementValue) {		
	var emailPattern = /^[a-zA-Z0-9\._-]+@[a-zA-Z0-9\.-]+\.[a-zA-Z]{2,4}$/;
	return emailPattern.test(elementValue);
} 

/**************************************************************************************
	* CONTROLLA ESISTENZA HISTORY
***************************************************************************************/
function existentHistory(historyArray, historyValue)
{
	var indice = -1;
	var ok = false;
	var i = 0;
	var obj;
	while(i < historyArray.length && !ok)
	{
		obj = historyArray[i];
		if(jQuery.trim(historyValue) == jQuery.trim(obj.historyValue))
		{
			indice = i;	
			ok = true;
		}
		i = i + 1;
	}
	return indice;
}

function resetSelect(id)
{
	jQuery("#"+id).css('color', '#ACAEAF');
}

function checkCart()
{
	jQuery.ajax({
	   type: "POST",
	   url: url_site + "templates/nessos/checkCart.php",
	   data: "sesid="+sessionID+"&idu="+idUtente,
	   cache: false,
	   async: false,
	   success: function(html)
	   {
		   if(parseInt(html) == 1) window.location.href = url_site + "cassa";
		   else if(parseInt(html) == 2) openAlert('continua_acquisto');
		   else openDinamicAlert('dinamic_alert', 'Attenzione!', 'Il tuo carrello non contiene nessun prodotto');
	   }
	 });
}

function chiudiContinuaAcquisto(val)
{
	closeAlert('continua_acquisto');
	if(val) window.location.href = url_site + "cassa";
}

function checkSpedizione()
{
	count_error = 0;
	checkField('indirizzo_sped', 'Indirizzo');
	checkField('comune_sped', 'Comune');
	checkNumber('cap_sped', 'Cap');
	if(jQuery("#provincia_sped").val() == -1)
	{
		count_error = count_error + 1;
		document.getElementById('provincia_sped').style.color = '#FF0000';
	}
	//checkField('provincia_sped', 'Provincia');
	if(count_error == 0)
	{
		jQuery.ajax({
		   type: "POST",
		   url: url_site + "templates/nessos/saveSpedizione.php",
		   data: "idU=" + idUtente + "&in=" + jQuery.base64Encode(jQuery("#indirizzo_sped").val()) + "&c=" + jQuery.base64Encode(jQuery("#comune_sped").val()) + "&cp=" + jQuery.base64Encode(jQuery("#cap_sped").val()) + "&p=" + jQuery("#provincia_sped").val() + "&inf="+ jQuery.base64Encode(jQuery("#info_agg").val()),		   
		   cache: false,
		   async: false,
		   success: function(xml)
		   {
			   var error = jQuery(xml).find("errore").text();
			   var indirizzo = jQuery(xml).find("indirizzo").text();
			   var comune = jQuery(xml).find("comune").text();
			   var cap = jQuery(xml).find("cap").text();
			   var provincia = jQuery(xml).find("provincia").text();
			   var altro = jQuery(xml).find("altro").text();
			   if(parseInt(error) == 0)
			   {
				   jQuery(".aggiungi_indirizzo").children("h2").removeClass("aggiungiOpen")
				   jQuery(".aggiungi_indirizzo").children("h2").html("Modifica indirizzo spedizione");
				   jQuery(".aggiungi_indirizzo_overflow").animate({height: "0px"}, 300, "linear", function()
				   {
					   if(jQuery("#indirizzo_sped_txt").css('display') != "none")
					   {
						   jQuery("#changeIndirizzo").css('display', 'inline');
						   jQuery("#indirizzo_sped_txt").html(indirizzo);
						   jQuery("#altro_sped_txt").html(comune + ", " + cap + " " + provincia);
						   if(jQuery.trim(altro) != "" && jQuery.trim(altro) != "Info aggiuntive")
						   {
							   if( jQuery("#info_sped_txt").css('display') != "none")
							   	   jQuery("#info_sped_txt").html(altro);
							   else
							   {
								   jQuery("#info_sped_txt").css('visibility', 'hidden');
								   jQuery("#info_sped_txt").css('display', 'inline');
								   jQuery("#info_sped_txt").html(altro);
								   jQuery("#info_sped_txt").css('visibility', 'visible');
							   }
						   }
					   }else
					   {
						   jQuery("#indirizzo_sped_txt").css('visibility', 'hidden');
						   jQuery("#info_sped_txt").css('visibility', 'hidden');
							
						   jQuery("#indirizzo_sped_txt").css('display', 'inline');
						   jQuery("#altro_sped_txt").css('display', 'inline');
						   
						   jQuery("#indirizzo_sped_txt").html(indirizzo);
						   jQuery("#altro_sped_txt").html(comune + ", " + cap + " " + provincia);
							
						   jQuery("#coincide_fatt").css('display', 'none');
						   jQuery("#indirizzo_sped_txt").css('visibility', 'visible');
						   jQuery("#altro_sped_txt").css('visibility', 'visible');
						   
						   if(jQuery.trim(altro) != "" && jQuery.trim(altro) != "Info aggiuntive")
						   {
							   jQuery("#info_sped_txt").css('visibility', 'hidden');
							   jQuery("#info_sped_txt").css('display', 'inline');
							   jQuery("#info_sped_txt").html(altro);
							   jQuery("#info_sped_txt").css('visibility', 'visible');
						   }
					   }
					   reloadTrasporto();
					   openDinamicAlert('dinamic_alert', 'Complimenti!!', 'Il suo indirizzo di spedizione &egrave; stato aggiornato correttamente.');	
				   });
				}else
				{
					openDinamicAlert('dinamic_alert', 'Attenzione!!', 'Si &egrave; verificato un problema nell\'eseguire l\'operazione richiesta.');	
				}
		   }
		 });
	}
}

function changeIndirizzo()
{
	var val = jQuery("#indirizzoFatturazione").val();	
	if(val == 1)
	{
		jQuery("#indirizzo_sped_txt").show();
		jQuery("#altro_sped_txt").show();
		if(jQuery("#info_sped_txt").html() != "&nbsp;") jQuery("#info_sped_txt").show();
		jQuery(".aggiungi_indirizzo").show();
		
		jQuery("#indirizzoFatturazione").val(0);
		jQuery("#changeIndirizzo").html('&gt; Utilizza per la spedizione l\'indirizzo di fatturazione');	
	}else
	{
		jQuery("#indirizzo_sped_txt").hide();
		jQuery("#altro_sped_txt").hide();
		jQuery("#info_sped_txt").hide();
		jQuery(".aggiungi_indirizzo").hide();
		
		jQuery("#indirizzoFatturazione").val(1);
		jQuery("#changeIndirizzo").html('&gt;Utilizza un diverso indirizzo di spedizione');
	}
	reloadTrasporto();
}

var isOpenGuardaVideo = 0;
function openGuardaVideo(video)
{
	if(isOpenGuardaVideo == 0)
	{
		setTopAlert('guarda_popup_video');
		document.getElementById('opacity_layer').style.display = 'inline';	
		document.getElementById('guarda_popup_video').style.display = 'inline';	
		isOpenGuardaVideo = 1;
		
		$("a#playerVideo").attr('href', url_site+"templates/nessos/images/prodotti/video/"+video);
		flowplayer("playerVideo", url_site+"templates/nessos/flowplayer/flowplayer-3.1.5.swf",
		{ 
			clip: 
			{ 
				autoPlay: false,
				autoBuffering: true 
			},
			play: { 
				label: null, 
				replayLabel: "premi per rivedere il video" 
			}
		});
	}
}

function closeGuardaVideo()
{
	$f(0).stop();
	jQuery(".player_video").html('<a href="" class="myPlayer" id="playerVideo"></a>');
	document.getElementById('opacity_layer').style.display = 'none';	
	document.getElementById('guarda_popup_video').style.display = 'none';
	isOpenGuardaVideo = 0;
}
