// da utilizzarsi avendo incluso ajax.js
// implemento la funzione trim() nelle stringhe
String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g,"");
}

/** Tutto cio' che riguarda la registrazione e la modifica dei dati di un utente */
function Registrazione() {

  /** Controlla se il nick e' gia' occupato */
  this.controllaNick = function() {
    var nick = document.getElementById("regNick").value;
    if(!isAlfanumerica(nick)) {
      document.getElementById("nickControl").innerHTML = "non &egrave; alfanumerico!";
      document.getElementById("regNick").focus();
    }
    else Ajax.update("nickControl", "scripts/ajaxComponents.php", "service=nickControl&nick="+nick);
  }

  /** Rigenera un nuovo codice captcha */
  this.refreshCaptcha = function() {
    document.getElementById("captchaCodeImg").src = "captcha.php?par="+Math.floor(Math.random()*7398476);
    document.getElementById("regCaptcha").value = "";
    document.getElementById("regCaptcha").focus();
  }

  /** Spedisce la pagina in registrazione */
  this.registra = function() {
    var nome = document.getElementById("regNome").value;
    var cognome = document.getElementById("regCognome").value;
    var mail = document.getElementById("regMail").value;
    var newsMail = document.getElementById("regNewsMail").value;
    var nick = document.getElementById("regNick").value;
    var password = document.getElementById("regPassw").value;
    var data =
      document.getElementById("giorno").value+"-"+
      document.getElementById("mese").value+"-"+
      document.getElementById("anno").value;
    var captchaCode = document.getElementById("regCaptcha").value;
    if(nome == "" || cognome == "") alert("Hai lasciato in bianco alcuni campi!");
    else if(!controlloData(data)) alert("La data non ha un formato corretto! (" + data+")");
    else if(!isAlfanumerica(nick)) alert("Il nick non è alfanumerico!");
    else if(!controlloMail(mail)) alert("La e-mail ha un formato scorretto!");
    else if(!isAlfanumerica(password)) alert("La password specificata non è alfanumerica!");
    else if(password != document.getElementById("regPassw2").value) alert("Le password non coincidono");
    else {
      var post =
        "service="+escape("processRegistration") +
        "&regNome="+escape(nome)+
        "&regCognome="+escape(cognome)+
        "&regMail="+escape(mail)+
        "&regNewsMail="+escape(newsMail)+
        "&regNick="+escape(nick)+
        "&regPassw="+escape(password)+
        "&regData="+escape(data)+
        "&regCaptcha="+escape(captchaCode);
      Ajax.update("thickboxContent", "scripts/ajaxComponents.php", post);
    }
  }

  /** Controlla i campi per la modifica dei dati dell'utente */
  this.editProfile = function() {
    document.getElementById("editLog").innerHTML =
      "<img src=\"immagini/layout/loading_small.gif\" alt=\"Caricamento\"/>\n"+
      "<span class=\"small\">caricamento... aspetta il segnale verde</span><br/>\n";

    var nome = document.getElementById("edNome").value;
    var cognome = document.getElementById("edCognome").value;
    var mail = document.getElementById("edMail").value;
    var newsMail = document.getElementById("edNewsMail").value;
    var password = document.getElementById("edPassw").value;
    var data =
      document.getElementById("giorno").value+"-"+
      document.getElementById("mese").value+"-"+
      document.getElementById("anno").value;
    if(nome == "" || cognome == "") alert("Hai lasciato in bianco nome o cognome!");
    else if(!controlloData(data)) alert("La data non ha un formato corretto! (" + data+")");
    else if(!controlloMail(mail)) alert("La e-mail ha un formato scorretto!");
    else if(password != "" && !isAlfanumerica(password)) alert("La password specificata non è alfanumerica!");
    else if(password != "" && password != document.getElementById("edPassw2").value) alert("Le password non coincidono");
    else {
      var post =
        "service="+escape("editProfile") +
        "&edNome="+escape(nome)+
        "&edCognome="+escape(cognome)+
        "&edMail="+escape(mail)+
        "&edNewsMail="+escape(newsMail)+
        "&edPassw="+escape(password)+
        "&edData="+escape(data);
      Ajax.update("editLog", "scripts/ajaxComponents.php", post);
    }
  }

  /** Testa se l'espressione e' alfanumerica (ma con underscore), senza spazi */
  function isAlfanumerica(str) {
    var espressione = /^[_A-Za-z0-9]+$/; // solo alfanumerico
    return espressione.test(str);
  }

  /** Torna true se effettivamente la sintassi e' quella di una e-mail, false altrimenti */
  function controlloMail(mail) {
    var espressione = /^[_a-z0-9+-]+(\.[_a-z0-9+-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)+$/;
    return espressione.test(mail);
  }

  /** Controlla se la data ha un formato corretto (gg-mm-aaaa) e se esiste effettivamente */
  function controlloData(data) {
    var espressione = /^[0-9]{2}-[0-9]{2}-[0-9]{4}$/;
    if(!espressione.test(data)) {
      return false;
    }
    else {
      var anno = parseInt(data.substr(6),10);
      var mese = parseInt(data.substr(3, 2),10);
      var giorno = parseInt(data.substr(0, 2),10);

      var datac = new Date(anno, mese-1, giorno);
      if(datac.getFullYear() == anno && datac.getMonth()+1 == mese && datac.getDate() == giorno)
        return true;
      else
        return false;
    }
  }
}



/** Tutto cio' che riguarda la homepage */
function Muro() {}
/** Controlla se e' stato scritto il mittente e fa il submit */
Muro.spedisci = function(formId, nickId, messId) {
  if(document.getElementById(nickId).value == "") alert("Non hai inserito il NOME");
  var mess = ied.getText();
  mess = mess.replace(/<br>/g, "").replace(/<BR>/g, "").replace(/\n/g, "").replace(/\r/g, "").replace(/[&]/g, "").replace(/nbsp;/g, "").trim();
  if(mess == "")
    alert("Non hai scritto il messaggio. Devi compilare il nome e poi scrivere il messaggio sul rettangolo con la sabbia.");
  else ied.inviaDati(formId, messId);
}
/** Crea un iframe e lo appende nell'oggetto con id indicato (idWhere) */
Muro.setIframe = function(src, id, idWhere) {
	var iframe = document.createElement("iframe");
	iframe.setAttribute("id", id);
	iframe.setAttribute("src", src);
	iframe.setAttribute("frameBorder", 0); // frameborder non funziona!! La B va maiuscola!!!!! Fottuto Explorer!
	document.getElementById(idWhere).appendChild(iframe);
}


function visualizzaFoto(url) {
	open(url, "profilo", "width=850,height=650,top=0,left=0,scrollbars=1,resizable=1");
}

function galleryIngrandita(url, foto, fotoId, tot) {
	open(url+"?foto=" + foto + "&fotoId=" + fotoId + "&totFoto=" + tot, "finestraFoto", "width="+(screen.width-10)+",height=650,top=0,left=0,scrollbars=1,resizable=1");
}

/** Inserisce l'UploadApplet nel posto giusto settando i parametri giusti */
function getFTPTransferApplet() {
	var up = new Applet("applets/FTPTransferApplet", "FTPTransferApplet.jar", "ftptransferapplet.FTPTransferApplet.class", 400, 300);

	// recupero i parametri
  var startDir = document.getElementById("sezione").value;
  var prefixFileName = document.getElementById("userId").value;
  if(startDir == "") return;
	// li inserisco nell'applet
	up.addParameter("startDir", startDir);
	up.addParameter("prefixFileName", prefixFileName);
	up.addParameter("endUploadJavascriptCode", "try{Ajax.update('notifiche', 'scripts/ajaxComponents.php', 'service=processUpload&upSezione="+startDir+"');}catch(e){}");
	// inserisco l'applet nel testo
	up.getApplet("ftpTransferApplet", "caricamento");
}

/** Cambia il valore di newsmail nel database in modo asincrono senza nessuna stringa di ritorno */
function newsMailOnOff(checkbox) {
  var post = "service=newsMailOnOff&newsMail=";
  post += (checkbox.checked) ? "SI" : "NO";
  Ajax.update(null, "scripts/ajaxComponents.php", post);
}



var reg = new Registrazione();

