// JavaScript Document

// controlla email
function controllaEmail(str) {
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);var res=1;if (str.indexOf(at)==-1){
		res=0;
	}
	else if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		res=0;
	}
	else if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		res=0;
	}
	else if (str.indexOf(at,(lat+1))!=-1){
		res=0;
	}
	else if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		res=0;
	}
	else if (str.indexOf(dot,(lat+2))==-1){
		res=0;
	}
	else if (str.indexOf(" ")!=-1){
		res=0;
	}
	if(res==1) {
		return true;
	}
	else {
		return false;
	}					
}

function addSeparatorsNF(nStr, inD, outD, sep)
{
	nStr += '';
	var dpos = nStr.indexOf(inD);
	var nStrEnd = '';
	if (dpos != -1) {
		nStrEnd = outD + nStr.substring(dpos + 1, nStr.length);
		nStr = nStr.substring(0, dpos);
	}
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(nStr)) {
		nStr = nStr.replace(rgx, '$1' + sep + '$2');
	}
	return nStr + nStrEnd;
}

function quoteReplace(fields) {

	var elenco=fields.split(",");

	var tmp;

	for(i in elenco) {

		var tmp=document.getElementById(elenco[i]).value;

		document.getElementById(elenco[i]).value=tmp.replace(/\'/g, "&#39;");

		document.getElementById(elenco[i]).value=tmp.replace(/\"/g, "&#34;");

		/*

		document.getElementById(elenco[i]).value=tmp.replace(/à/g, "&agrave;");

		document.getElementById(elenco[i]).value=tmp.replace(/è/g, "&egrave;");

		document.getElementById(elenco[i]).value=tmp.replace(/ì/g, "&igrave;");

		document.getElementById(elenco[i]).value=tmp.replace(/ò/g, "&ograve;");

		document.getElementById(elenco[i]).value=tmp.replace(/ù/g, "&ugrave;");

		*/

	}

}



// cookie functions

function setCookie(name,value,days) {

	if (days) {

		var date = new Date();

		date.setTime(date.getTime()+(days*24*60*60*1000));

		var expires = "; expires="+date.toGMTString();

	}

	else var expires = "";

	document.cookie = name+"="+value+expires+"; path=/;";

}



function getCookie(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 deleteCookie(name) {

	setCookie(name,"",-1);

}


function getcwd() {
  var myloc = window.location.href;
  var locarray = myloc.split("/");
  delete locarray[(locarray.length-1)];
  var arraytext = locarray.join("/");
  return arraytext;
}


function showHide(elemento) {
  var stato = document.getElementById(elemento).style.display;
  var newstato = 'none';
  if(stato == 'none') newstato = '';
  document.getElementById(elemento).style.display=newstato;
}

function hidemessage(elemento) {
  var stato = document.getElementById(elemento).style.display;
  if(stato != 'none') document.getElementById(elemento).style.display='none';
}

// prende in ingresso un link, un nome di parametro ed un valore di parametro
// se il parametro viene trovato nel link allora imposto il nuovo valore
// altrimenti accodo il nuovo parametro al link esistente
// restituisce il nuovo link 
function changeLinkParameter(theLink,theParameter,theValue) {

  var theLinkArray = theLink.split('&');
  var found = 0;
  for(i=0;i<theLinkArray.length;i++) {
    if(theLinkArray[i].substring(0,theParameter.length) == theParameter) {
      theLinkArray[i] = theParameter + '=' + theValue;
      found = 1;
      break;
    }
  }
  if(found == 1) {
    return theLinkArray.join('&');
  }
  else {
    return theLink + '&' + theParameter + '=' + theValue;
  }

}


function calcolaSpese() {

  var area = document.getElementById('areadispedizione').value;
  var costo = document.getElementById('costo_'+area).value;
  var costo_num = parseFloat(costo.substring(0,costo.length-2).replace('.','').replace(',','.'));
  var totale_p = parseFloat(document.getElementById('totale_p').value);
  
  var totale_finale = costo_num+totale_p;
  totale_finale=addSeparatorsNF(totale_finale.toFixed(2), '.', ',', '.') + " &euro;";
    
  document.getElementById('speseeuro').innerHTML = costo;
  document.getElementById('totalespeseeuro').innerHTML = totale_finale;

  var cnt = 0;
  var mylink;
  while(mylinkpiu = document.getElementById('linkpiu' + cnt)) {
    mylinkmen = document.getElementById('linkmen' + cnt)
    
    mylinkpiu = changeLinkParameter(mylinkpiu,'areadispedizione',area);
    mylinkmen = changeLinkParameter(mylinkmen,'areadispedizione',area);
    
    mylinkpiu.href = mylinkpiu;  
    mylinkmen.href = mylinkmen;
    
    cnt++;
  }

  var procedi = document.getElementById('fromlink').value;
  procedi = changeLinkParameter(procedi,'areadispedizione',area);
  document.getElementById('fromlink').value = procedi;

  return true;
}


// submit via link

function salvaSpese() {

  var area = document.getElementById('areadispedizione').value;
  var primolink = document.getElementById('fromlink').value;
  var ID_reg = document.getElementById('ID_reg').value;

  var newlink = getcwd() + primolink + '&areadispedizione=' + area + '&mode2=';

  if(ID_reg != '' && ID_reg != 'undefined') {
    newlink += 'carrello_paypal&ID_reg=' + ID_reg;
  }
  else {
    newlink += 'login'
  }
	alert(newlink);
  location.href = newlink;
}


// controlla bontà dell'accesso
function checkLogin() {

  var accediusername = document.getElementById('accediusername').value;
  var accedipassword = document.getElementById('accedipassword').value;
  var theLink = document.getElementById('fromlink').value;
  
  var criptata = Javacrypt.displayPassword();
  criptata=criptata[0];
  theLink = theLink + '';
  var risposta = new Ajax.Request('ajax_checklogin.php',
    {
      parameters: {
        email: accediusername,
        password: criptata
      },
      onSuccess: function(transport){
        var response = transport.responseText || "no response text";
        if(response > 0) {
          theLink = changeLinkParameter(theLink,'action','register');
          theLink = changeLinkParameter(theLink,'ID_reg',response);
          theLink = changeLinkParameter(theLink,'mode2','login');
          location.href = theLink;
          return false;
        }
        else if(response == 0) {
          document.getElementById('messaggioerrore').innerHTML='accesso non effettuato';
          document.getElementById('messaggioerrore').style.display='';
          return false;
        }
        else {
          document.getElementById('messaggioerrore').innerHTML='indirizzo email in attesa di verifica<br>controllare la propria casella di posta elettronica';
          document.getElementById('messaggioerrore').style.display='';
          return false;
        }
      },
      onFailure: function(){ alert('Something went wrong...') }
    }
  );
}


// invia la mail di nuova password
function forgottenPassword() {
	
	var dimenticatoemail = document.getElementById('dimenticatoemail').value;
	if(controllaEmail(dimenticatoemail)) {
		var risposta = new Ajax.Request('ajax_dimenticata.php',
			{
				parameters: {
					email: dimenticatoemail
				},
				onSuccess: function(transport) {
					var response = transport.responseText || "no response text";
	        if(response > 0) {
	          document.getElementById('messaggioerroredimentica').innerHTML='email spedita con successo, controlla la tua casella di posta';
	          document.getElementById('messaggioerroredimentica').style.display='';
	          return false;
	        }
	        else {
	          document.getElementById('messaggioerroredimentica').innerHTML='indirizzo email non riconosciuto';
	          document.getElementById('messaggioerroredimentica').style.display='';
	          return false;
	        }
				},
				onFailure: function(){ alert('Something went wrong...') }
			}
		)
	}
	else {
    document.getElementById('messaggioerroredimentica').innerHTML='Indirizzo email non valido.';
    document.getElementById('messaggioerroredimentica').style.display='';
	}
}


function coloraCampo(idCampo) {
  
  document.getElementById(idCampo).focus();
  document.getElementById(idCampo).style.backgroundColor='#ffcccc';
  document.getElementById('messaggioerrore').style.display='';
  return true;
}

function decoloraCampo(idCampo) {
    idCampo.style.backgroundColor='';
    document.getElementById('messaggioerrore').style.display='none';
}


// controlla i campi inseriti in sede di registrazione
function checkFields() {
  var theLink = document.getElementById('fromlink').value;
  
  var profilo_nome = document.getElementById('profilo_nome').value;
  var profilo_cognome = document.getElementById('profilo_cognome').value;
  var profilo_indirizzo1 = document.getElementById('profilo_indirizzo1').value;
  var profilo_indirizzo2 = document.getElementById('profilo_indirizzo2').value;
  var profilo_cap = document.getElementById('profilo_cap').value;
  var profilo_citta = document.getElementById('profilo_citta').value;
  var profilo_provincia = document.getElementById('profilo_provincia').value;
  var profilo_stato = document.getElementById('profilo_stato').value;
  var profilo_telefono = document.getElementById('profilo_telefono').value;
  var profilo_email = document.getElementById('profilo_email').value;
  var profilo_password = document.getElementById('profilo_password').value;
  var profilo_passwordconf = document.getElementById('profilo_passwordconf').value;

  var ID_reg = document.getElementById('ID_reg').value;
  if(ID_reg>0) {
    var profilo_passwordold = document.getElementById('profilo_passwordold').value;
  }
  
  if(profilo_nome == '' || profilo_nome == null || profilo_nome == undefined) {
    coloraCampo('profilo_nome');
    return false;
  }
  else if(profilo_cognome == '' || profilo_cognome == null || profilo_cognome == undefined) {
    coloraCampo('profilo_cognome');
    return false;
  }
  else if(profilo_indirizzo1 == '' || profilo_indirizzo1 == null || profilo_indirizzo1 == undefined) {
    coloraCampo('profilo_indirizzo1');
    return false;
  }
  else if(profilo_cap == '' || profilo_cap == null || profilo_cap == undefined) {
    coloraCampo('profilo_cap');
    return false;
  }
  else if(profilo_citta == '' || profilo_citta == null || profilo_citta == undefined) {
    coloraCampo('profilo_citta');
    return false;
  }
  else if(profilo_provincia == '' || profilo_provincia == null || profilo_provincia == undefined) {
    coloraCampo('profilo_provincia');
    return false;
  }
  else if(profilo_stato == '' || profilo_stato == null || profilo_stato == undefined) {
    coloraCampo('profilo_stato');
    return false;
  }
  else if(profilo_telefono == '' || profilo_telefono == null || profilo_telefono == undefined) {
    coloraCampo('profilo_telefono');
    return false;
  }
  else if(!controllaEmail(profilo_email)) {
    coloraCampo('profilo_email');
    return false;
  }
  else if( (profilo_password == '' || profilo_password == null || profilo_password == undefined || profilo_password.length<5) 
            && (ID_reg == 0 || (ID_reg>0 && profilo_passwordold.length>0))) {
    coloraCampo('profilo_password');
    return false;
  }
  else if( (profilo_passwordconf == '' || profilo_passwordconf == null || profilo_passwordconf == undefined || profilo_passwordconf.length<5) 
            && (ID_reg == 0 || (ID_reg>0 && profilo_passwordold.length>0)) ) {
    coloraCampo('profilo_passwordconf');
    return false;
  }
  else if(profilo_passwordconf != profilo_password) {
    coloraCampo('profilo_passwordconf');
    return false;
  }
  else {
    var criptata = Javacrypt.displayPassword(profilo_password);
    criptata=criptata[0];
    
    if(ID_reg>0 && profilo_passwordold.length>0) {
      var criptataold = Javacrypt2.displayPassword(profilo_passwordold);
      criptataold=criptataold[0];
    }

    var risposta = new Ajax.Request('ajax_register.php',
      {
        parameters: {
          profilo_nome: profilo_nome,
          profilo_cognome: profilo_cognome,
          profilo_indirizzo1: profilo_indirizzo1,
          profilo_indirizzo2: profilo_indirizzo2,
          profilo_cap: profilo_cap,
          profilo_citta: profilo_citta,
          profilo_provincia: profilo_provincia,
          profilo_stato: profilo_stato,
          profilo_telefono: profilo_telefono,
          profilo_email: profilo_email,
          profilo_password: criptata,
          profilo_passwordold: criptataold,
          ID_reg: ID_reg
        },
        onSuccess: function(transport){
          var response = transport.responseText || "no response text";
          if (response == 'err01') {
            document.getElementById('messaggioerrore').innerHTML='email gi&agrave; utilizzata da un\'altro utente';
            document.getElementById('messaggioerrore').style.color='red';
            document.getElementById('messaggioerrore').style.display='';
            return false;
          }
          if (response == 'err02') {
            document.getElementById('messaggioerrore').innerHTML='la vecchia password non &egrave; corretta';
            document.getElementById('messaggioerrore').style.color='red';
            document.getElementById('messaggioerrore').style.display='';
            return false;
          }
          else if (response == 'ok') {
            document.getElementById('messaggioerrore').innerHTML='dati modificati con successo';
            document.getElementById('messaggioerrore').style.color='green';
            document.getElementById('messaggioerrore').style.display='';
            return false;
          }
          else if(response > 0) {
            theLink = changeLinkParameter(theLink,'action','firstregister');
            theLink = changeLinkParameter(theLink,'ID_ver',response);
            location.href = theLink;
            return false;
          }
        },
        onFailure: function(){ alert('Something went wrong...') }
      }
    );
  }
}

function fixPng(img) {
  var sstring = "width:" + img.width + "px; height:" + img.height + "px;" + "filter:progid_DXImageTransform.Microsoft.Alpha(opacity=0);filter:progid_DXImageTransform.Microsoft.AlphaImageLoader"
   + "(src=\'" + img.src.replace(getcwd(),'') + "\', sizingMethod='scale');"; 
  img.style.cssText=sstring;
  return true;
}

function showToppa(lingua) {
  var nascondi = "it";
  var mostra = "en";
  if(lingua=="it") {
    nascondi = "en";
    mostra = "it";
  }
  document.getElementById('toppa_'+mostra).style.display='';
  document.getElementById('toppa_'+nascondi).style.display='none';
}

// controlla i campi inseriti in sede di registrazione
function checkAddressFields() {
  
  var indirizzo_nome = document.getElementById('indirizzo_nome').value;
  var indirizzo_cognome = document.getElementById('indirizzo_cognome').value;
  var indirizzo_indirizzo1 = document.getElementById('indirizzo_indirizzo1').value;
  var indirizzo_indirizzo2 = document.getElementById('indirizzo_indirizzo2').value;
  var indirizzo_cap = document.getElementById('indirizzo_cap').value;
  var indirizzo_citta = document.getElementById('indirizzo_citta').value;
  var indirizzo_provincia = document.getElementById('indirizzo_provincia').value;
  var indirizzo_stato = document.getElementById('indirizzo_stato').value;

  var ID_reg = document.getElementById('ID_reg').value;
  var ID_ind = document.getElementById('ID_ind').value;

  if(indirizzo_nome == '' || indirizzo_nome == null || indirizzo_nome == undefined) {
    coloraCampo('indirizzo_nome');
    return false;
  }
  else if(indirizzo_cognome == '' || indirizzo_cognome == null || indirizzo_cognome == undefined) {
    coloraCampo('indirizzo_cognome');
    return false;
  }
  else if(indirizzo_indirizzo1 == '' || indirizzo_indirizzo1 == null || indirizzo_indirizzo1 == undefined) {
    coloraCampo('indirizzo_indirizzo1');
    return false;
  }
  else if(indirizzo_cap == '' || indirizzo_cap == null || indirizzo_cap == undefined) {
    coloraCampo('indirizzo_cap');
    return false;
  }
  else if(indirizzo_citta == '' || indirizzo_citta == null || indirizzo_citta == undefined) {
    coloraCampo('indirizzo_citta');
    return false;
  }
  else if(indirizzo_provincia == '' || indirizzo_provincia == null || indirizzo_provincia == undefined) {
    coloraCampo('indirizzo_provincia');
    return false;
  }
  else if(indirizzo_stato == '' || indirizzo_stato == null || indirizzo_stato == undefined) {
    coloraCampo('indirizzo_stato');
    return false;
  }
  else {
    var risposta = new Ajax.Request('ajax_registeraddress.php',
      {
        parameters: {
          indirizzo_nome: indirizzo_nome,
          indirizzo_cognome: indirizzo_cognome,
          indirizzo_indirizzo1: indirizzo_indirizzo1,
          indirizzo_indirizzo2: indirizzo_indirizzo2,
          indirizzo_cap: indirizzo_cap,
          indirizzo_citta: indirizzo_citta,
          indirizzo_provincia: indirizzo_provincia,
          indirizzo_stato: indirizzo_stato,
          ID_reg: ID_reg,
          ID_ind: ID_ind
        },
        onSuccess: function(transport){
          var response = transport.responseText || "no response text";
          if (response == 'ok') {
            document.getElementById('messaggioerrore').innerHTML='dati modificati con successo';
            document.getElementById('messaggioerrore').style.color='green';
            document.getElementById('messaggioerrore').style.display='';
            return false;
          }
          else if(response > 0) {
            document.getElementById('messaggioerrore').innerHTML='nuovo indirizzo inserito con successo';
            document.getElementById('messaggioerrore').style.color='green';
            document.getElementById('messaggioerrore').style.display='';
            return false;
          }
        }
      }
    );
  }
}

function galleryFoto(link,width) {
	document.getElementById('gallery_foto').src='imageresample.php?src='+link+'&typ=w&siz='+width+'pars=';
}
