var memidimg;

function Trim(StrToTrim)
	{
   // CONTROLLA CHE IL VALORE IN INPUT SIA DI TIPO STRING
    if (typeof StrToTrim != "string")
    {
        return StrToTrim;
    }

    // CATTURA IL PRIMO CARATTERE DELLA STRINGA PER CONTROLLARE CHE NON SIA UNO SPAZIO VUOTO
    var StrBlank = StrToTrim.substring(0, 1);

    // ELIMINA LO SPAZIO VUOTO DALLA PRIMA POSIZIONE DELLA STRINGA
    while (StrBlank == " ")
    {
        StrToTrim = StrToTrim.substring(1, StrToTrim.length);
        StrBlank = StrToTrim.substring(0, 1);
    }

    // CATTURA L'ULTIMO CARATTERE DELLA STRINGA PER CONTROLLARE CHE NON SIA UNO SPAZIO VUOTO
    StrBlank = StrToTrim.substring(StrToTrim.length - 1, StrToTrim.length);

    // ELIMINA LO SPAZIO VUOTO DALL'ULTIMA POSIZIONE DELLA STRINGA
    while (StrBlank == " ")
    {
        StrToTrim = StrToTrim.substring(0, StrToTrim.length-1);
        StrBlank = StrToTrim.substring(StrToTrim.length-1, StrToTrim.length);
    }

    // ELIMINA POTENZIALI SPAZI VUOTI MULTIPLI ALL'INIZIO ED ALLA FINE DI UNA STRINGA
    while (StrToTrim.indexOf("  ") != -1)
    {
        StrToTrim = StrToTrim.substring(0, StrToTrim.indexOf("  "));
        StrToTrim += StrToTrim.substring(StrToTrim.indexOf("  ") + 1, StrToTrim.length);
    }

    // RESTITUISCE IL VALORE FINALE SENZA SPAZI VUOTI DI CONTORNO
    return StrToTrim;

 }

//Verifico se nella stringa c'è il carattere ["]
function ControlDpApici(StrVerif) {

     var strt = true;
     var getcar = -1;

         getcar = StrVerif.indexOf('"',0);


         var ap = "";
         ap = String.fromCharCode(39);

     if (getcar > -1) {
        alert ('Attenzione avete inserito il carattere ["] che non può essere utilizzato!!\n        Eventualmente potete usare il carattere[' + ap + ']');
        strt = false;
     }

  return strt;
}

//Passandogli una stringa e un puntatore riferito alla stringa
//mi restituisce l'unicode del carattere.
function getCharCode(str,i)
{
	var code=str.charCodeAt(i)
	if(code>256)
	{
		code=gaUToC[code];
	}
	return code;
}

//Verifico che la stringa passata alla funzione contenga solo numeri
function ControlInputOnlyNumber(Stringa){

    var i = 0;
    var rescontrol = false;

     while (i < Stringa.length) {

       var unicode = Stringa.charCodeAt(i);
       if ((unicode < 48) || (unicode > 57))
          rescontrol = true;

         i++;
     }

  return rescontrol;

}

//Verifico che la stringa passata alla funzione contenga solo caratteri e non numeri
function ControlInputOnlyChar(Stringa){

    var i = 0;
    var rescontrol = false;

     while (i < Stringa.length) {

       var unicode = Stringa.charCodeAt(i);
       if ((unicode > 47) && (unicode < 58))
          rescontrol = true;

         i++;
     }

  return rescontrol;

}


/*
===================  Sezione utility controllo eventi =======================
*/


//==== Questa funzione permette di disattivare l'evento [Tasto Enter]
//==== su elementi quali INPUT - TEXTAREA
//==== questo è utile per esempio per evitare il submit
//==== Esempio: <input type="text" name="mytext" onkeypress="return NoKeyEnter(this, event)">

function NoKeyEnter (field, event) {
     var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

      if (keyCode == 13)
                 return false;
	  else
                 return true;
}

/*
=================== Sezione Liste =======================
*/

//funzione per ordinare la lista in ordine alfabetico
function Order_List(ObjList,ColBgr){

        var idx = ObjList.length;
        var ListArray = new Array();

        for (i = 0; i < idx; i++) {
            ListArray[i] = ObjList.options[i].text + ";" + ObjList.options[i].value;
         }

        i = 0;
        for (i = 0; i < idx; i++) {
            ObjList.options[i] = null;
         }

        ListArray.sort();
        i = 0;

      //ritrasferisco i dati dell'array ordinato nella lista corrispondente
        for (i = 0; i < idx; i++) {
             var rec = ListArray[i].split(";");
             ObjList.options[i] = new Option(rec[0],rec[1]);
             ObjList.options[i].style.backgroundColor=ColBgr
         }
}

//Conta le parole in una textarea
//ObjTxt = è l'oggetto TextArea
//maxchars = è il numero massimo di caratteri che si può scrivere
//IdElementCount = è l'elemnto che visualizza il numero delle parole
function Pcount1(ObjTxt,maxchars,IdElementCount){
  
  var cnt = document.getElementById(IdElementCount);
  cnt.innerHTML = maxchars; 
   
    chars=ObjTxt.value;
	inischeda.memmydesc.value= ObjTxt.value;
    if (chars.length > maxchars){
      ObjTxt.value=chars.substr(0,maxchars);
      ObjTxt.blur();
     }
    
    cnt.innerHTML = maxchars-ObjTxt.value.length;	 
	 
    ObjTxt.focus();
}

function memdescr(ObjTxt){
   
}

function Pcount2(ObjTxt,maxchars,IdElementCount){
  
  var cnt = document.getElementById(IdElementCount);
  cnt.innerHTML = maxchars; 
   
    chars=ObjTxt.value;
	inischeda.memyoudesc.value= chars;
	
    if (chars.length > maxchars){
      ObjTxt.value=chars.substr(0,maxchars);
      ObjTxt.blur();
     }
    
    cnt.innerHTML = maxchars-ObjTxt.value.length;	 
	 
    ObjTxt.focus();
}

//funzione per il primo passo per la registrazione
function Step_1(){

  if (inischeda.checkcme.checked == false){
     alert ("Per continuare devi dichiarare di essere maggiorenne!");
	 return;
  }	 
  
  if (inischeda.checkpry.checked == false){
     alert ("Per continuare devi aver accettato l'informatica sulla privacy!");
	 return;
  }	   

  inischeda.fase.value = 2;
 
  inischeda.submit();
   
 }



// funzione per salvare le foto della registrazione dell'utente 
function SalvaPhotos_Reg(){
	
	 			 
     inischeda.fase.value=5;
	
	 inischeda.submit();
		
 }

// Gestione anteprima immagini caricate dall'utente in fase di registrazione
function anteprima(varImg,n,mitt){
 	
	if(varImg!="" && varImg!="NULL"){
	        var nomefile = varImg;
   	        estensione = nomefile.substr(nomefile.lastIndexOf(".")+1);
	        estensione=estensione.toLowerCase();

	if(estensione=="jpg" || estensione=="jpeg"){
	imgA=new Image();
	imgTemp=varImg;
	brow=navigator.userAgent.toLowerCase();


	if(brow.search("firefox")=="-1"){

		imgA.src="file:///"+imgTemp;
		if(imgA.width>2){
		larghezzaReale=imgA.width;
		altezzaReale=imgA.height;
		nuovaAltezza="73";
		nuovaLarghezza="73";

	if(larghezzaReale-altezzaReale>0){

		rapporto=(larghezzaReale/nuovaLarghezza);
		imWidth=nuovaLarghezza;
		imHeight=(altezzaReale / rapporto);

		}else{

		rapporto=(altezzaReale/nuovaAltezza);
		imWidth=(larghezzaReale/rapporto);
		imHeight=nuovaAltezza;
		}

	}

		}

	}else{
    	alert("Devi inserire un\'immagine jpg!");
        return;
	}
	}else{
	    alert("Devi inserire un immagine!");
  	    return;
	}

    //verifico la dimensione del file
  if (mitt == "L"){	
	if (DimFile(nomefile) > 40000){
		alert("Attenzione l'immagine è troppo grande! Max 40Kb");
  	    return;
	}
  }

 
   var newImage = document.createElement('img');
     if (mitt == "L"){
      newImage.setAttribute('src', "file:///"+varImg);
	 }
     if (mitt == "S"){
      newImage.setAttribute('src', varImg);
	 }	  
      newImage.setAttribute('alt', "NUOVA IMMAGINE");
	  newImage.setAttribute('width',"150");
	  newImage.setAttribute('height',"150");
      
	  //alert("ft"+n+"="+newImage);
	  
	  document.getElementById("ft"+n).innerHTML = "";
      document.getElementById("ft"+n).appendChild(newImage); 
	  
	  if (n == '1')
	    inischeda.foto2.disabled = false;

	  if (n == '2')
	    inischeda.foto3.disabled = false;
   
	  if (n == '3')
	    inischeda.foto4.disabled = false;   
}


//==  verifico la correttezza dell'email ===
function verifemail(email){

   var ret = false;

  if ((email.length) < 8 || email.indexOf('.') < 1 || email.indexOf('@') < 1){
      alert ("Attenzione hai scritto un'email non corretta! Verifica...");
	  ret = true;
   }   

   return ret;

}

//verifico la password come lunghezza
function v_pwd(objscheda){

  var mypwd  = objscheda.pwd1.value;
  
    if ((mypwd.length) < 6){
        alert("Attenzione la password dev'essere lunga almeno 6 caratteri!");
		objscheda.pwd1.focus();
		return;
     }		
}

//controllo la password se i due campi sono uguali
function c_pwd(objscheda){

 var ret = false

    if (objscheda.pwd1.value != objscheda.pwd2.value){
        alert("Attenzione la password ripetuta non è uguale!");
		objscheda.pwd2.focus();
		ret= true;
     }
	 
	return ret; 
	 		
}

//spedisco il messaggio
function Send_msg(){

   //Prima di mandare il msg verifico che il campo non sia vuoto

     var msg = Trim(frmsg.textmsg.value);

      if (msg.length == 0){
	      alert('Attenzione!! Non hai scritto nessun messaggio.');
		  frmsg.textmsg.value='';
		  document.getElementById('contap').innerHTML = "250";
		  return;
      }		  

     //frmsg.textmsg.value=msg;

     frmsg.fase.value='1';
	 frmsg.submit();
}

//richiamata da result_incontri.php
function schedadett(id,idm) {

   if (idm == -1) {
    var sc = window.confirm("Per visualizzare il dettaglio degli utenti dovete prima registrarvi!\n                    Volete registrarvi adesso?");
        if (sc == true){
	        window.location.href = "Scheda1.php";
        }		
   } else {

     searchWin = window.open('dett_incontri.php?ID='+id+'&IDM='+idm,'finestraindipendente','scrollbars=no,resizable=no,width=550,height=630,status=no,location=no,toolbar=no');
     searchWin.focus();
  }
  
}

function ApriW(filehtm){

  
  htmWin = window.open(filehtm,+'finestraindipendente','scrollbars=no,resizable=no,width=800,height=600,status=no,location=no,toolbar=no');
  htmWin.focus();

}

//richiamata da scheda2.php
function ReadMsg(idmsg,id){
 
 RmsgWin = window.open('LRmsg.php?idm='+idmsg,'msg','scrollbars=no,resizable=no,width=560,height=310,status=no,location=no,toolbar=no');

 RmsgWin.focus();

}

//richiamata da scheda2.php
function ViewUser(id){

  searchWin = window.open('dett_incontri.php?ID='+id,'finestraindipendente','scrollbars=no,resizable=no,width=550,height=640,status=yes,location=no,toolbar=no');
  searchWin.focus(); 

}
//richiamata da home_incontri.php
//richiama la scheda personale per le modifiche dei dati
function scheda3(miascheda){
  miascheda.action="upd_incontri.php";
  miascheda.submit();
}

function update_miefoto(miascheda){
  miascheda.action="upd_myfoto.php";
  miascheda.submit();
}
//richiamata da home_incontri.php
//richiama la scheda del cambio password
function scheda4(miascheda){
  miascheda.action="cambiopwd.php";
  miascheda.submit();
}
//richiamata da home_incontri.php
//richiama la visualizzazione della lista  degli amici
function lamici(miascheda){
  miascheda._codesearch.value = 2;
  miascheda.submit();
}


function gohome(){

  window.location.href = "home.php";
}

function ret_start(){

  window.location.href = "index.php";
}

function gopanel(){

  window.location.href = "access_user.php";
}


//richiamata da cambiopwd.php
function Salva_Pwd(){

//verifico che il campo password 1 non sia vuoto
    var pwd1 = Trim(pwdscheda.pwd1.value);     
    if (pwd1 == '') {
		  pwdscheda.pwd1.focus();
          alert ("Attenzione devi definire una password di accesso!");
          return;
	}	 
	 
   //verifico che il campo password 1 non sia vuoto
    var pwd2 = Trim(pwdscheda.pwd2.value);     
    if (pwd2 == '') {
		  pwdscheda.pwd2.focus();
          alert ("Attenzione devi ridigitare la password per verificare la sua correttezza!");
          return;
	}	 
	 
	 
    if (c_pwd(pwdscheda) == true){
	        return;
	 }		 
		 
   //verifico che il campo domanda segreta non sia vuota
    if (Trim(pwdscheda.domseg.value) == '') {
		  pwdscheda.domseg.focus();
          alert ("Attenzione devi impostare la domanda segreta!");
          return;
	}	 		

   //verifico che il campo risposta segreta non sia vuoto
    if (Trim(pwdscheda.risseg.value) == '') {
		  pwdscheda.risseg.focus();
          alert ("Attenzione devi impostare la risposta segreta!");
          return;
	}

     pwdscheda.fase.value='2';
	 pwdscheda.submit();

 }

//richiamata da scheda5.php,_cancel_user.php
function Rec_dati_email(scheda){

    //verifico che il campo email non sia vuoto
    var email = Trim(scheda.email.value);     
    if (email == '') {
		  scheda.email.focus();
          alert ("Attenzione devi definire la tua email!");
          return;
	}	 
     scheda.fase.value='1';
	 scheda.submit();
}


//richiamata da _cancel_user.php (domanda segreta)
function Rec_dati_drs(scheda){

   //verifico che il campo risposta non sia vuota
    var risp = Trim(scheda.risseg.value);
  	     
    if (risp == '') {
		  scheda.risseg.focus();
          alert ("Attenzione devi digitare la tua risposta segreta!");
          return;
	}
		 
    scheda.fase.value='5';
	scheda.submit();
}





//funzione per selezionare i messaggi della pagina [home]
function Seleziona_msg()
 {
 
   var objcheck = new Array();

   var objcheck = _elimi.elements ['checkmsg[]'];
 
    if (objcheck == null){
       return;
    }
 
   var ResultCount=objcheck.length;

   if (ResultCount == null) {
        objcheck.checked = true;
    }

	for (var i = 0; i < ResultCount; i++){
    objcheck(i).checked = true;
	}
	

}
//funzione per eliminare i msg selezionati
function Elimina_msg()
 {

  var risp = window.confirm("Sei sicuro di eliminare i messaggi selezionati?");

  if (risp == false)  {
     alert ("Eliminazione annullata!!");
     return;
  }
  
 _elimi.submit();
}

//funzione per cambiare pagina nella lettura dei messaggi
function change_pg(pag) {
 
   _elimi.activepag.value = pag;
   _elimi.code_pag.value = pag-1;
   _elimi.action="home_incontri.php";
   _elimi.submit();

 }
 
//funzione per caricare i messaggi ricevuti
function msg_ricev() {
 
   _elimi.TypeMsg.value = "msgr";
   _elimi.action="home_incontri.php";
   _elimi.submit();
}
 
//funzione per caricare i messaggi inviati
function msg_inv() {
 
   _elimi.TypeMsg.value = "msgi";
   _elimi.action="home_incontri.php";
   _elimi.submit();
} 


//Funzione che restituisce la dimensione del file
function DimFile(file){

   file = file.replace(/\\/g,"/");
   
   var dimf = 0;
      
   var fso = new ActiveXObject("Scripting.FileSystemObject");

   fileObj = fso.GetFile(file);  //("f:\\yehuda\\js\\tips\\myapp.txt");
   
   dimf = fileObj.Size;
   
   return dimf;

}

// funzione per cambiare il colore del border
function SelectImg(idimg,iddel){

 var bottobj = document.getElementById(iddel);
  
  
if(memidimg != undefined) {
	
   if(idimg != memidimg) {
        var memimgobj = document.getElementById(memidimg); 
        memimgobj.style.borderColor = '#000000' ; 
     }   
}

      var imgobj = document.getElementById(idimg);  

       if ( imgobj.style.borderColor == '#ff0000') {
            imgobj.style.borderColor = '#000000' ;
            bottobj.disabled = 1;	
        } else {
           imgobj.style.borderColor = '#ff0000' ;
           bottobj.disabled = 0;		
      }		
	
  memidimg = idimg;
  
  //scrivo nella casella idphoto il numero della foto selezionata
  var nph = 0;
  
   switch (idimg) {
   	
          case('f1'):
              nph = 1;
              break ;
          case('f2'):
              nph = 2;
              break ; 
          case('f3'):
              nph = 3;
              break ;              	
          case('f4'):
              nph = 4;
              break ; 
          case('f5'):
              nph = 5;
              break ;
          case('f6'):
              nph = 6;
              break ;
          case('f7'):
              nph = 7;
              break ; 
          case('f8'):
              nph = 8;
              break ; 
          case('f9'):
              nph = 9;
              break ;
          case('f10'):
              nph = 10;
              break ;                                                                                                  	
  } 	
  
   document.getElementById('idphoto').value=nph;  
 
   nomepreload=imgobj.src;
   p=nomepreload.indexOf("preuploads");
  
   document.getElementById('photopreload').value=nomepreload.substr(p);  

   return true;	
	
}	

// funzione che permette di cambiare l'icona del mouse- per esempio al passaggio sopra un'immagine
function changeIM(idobj){
 
   document.getElementById(idobj.id).style.cursor="pointer";  

}
// funzione che permette di abilitare o disabilitare un campo text
function abidisa(idobj,condiz,sv){
  
  if(condiz == 'false') document.getElementById('nriv').disabled=false; 
  if(condiz == 'true') document.getElementById('nriv').disabled=true; 

  if(sv=='reset') document.getElementById('nriv').value='';

}