var opt = "<option value=\"0\">Selezionare</option>";

/*
 * Se risponde apache creare una regola che proxa le chiamate dalla porta 80
 * alla 8080, altrimenti firefox non funziona (cross site scripting)
 * su Fondazione:
 * var host = "http://" + window.location.hostname + "/ApiFPS/";
 */
var port = "";
var host = "http://" + window.location.hostname + port + "/ApiFPS/";

function getIstitutoDatiT(id) {
  $('datiIstitutoT').getElement('.institute-data')._control.load(id);
}

function getIstitutiT(id) {
  var myRequest = new Request({url: host + 'getInstitutesFromInstituteKindAndMunicipality.jsp',
      onComplete: function(r){
        $("selectIstitutiT").innerHTML = "<select id=\"istitutoSelectT\" name=\"istituto\">" + opt + r + "</select>";
        $("istitutoSelectT").addEvent('change', function() {
          $('istitutoId').value = this.value;
          getIstitutoDatiT(this.value);
        });
      }
    }).send("idik=" + id + "&idMun=" + $("comune").value);
}

function getTipoIstitutoT(id) {
  var myRequest = new Request({url: host + 'getInstituteKinds2.jsp',
      onComplete: function(r){
        $("selectTipoT").innerHTML = "<select id=\"tipoist\" name=\"tipoist\">" + opt + r + "</select>";
        $("tipoist").addEvent('change', function() {
          getSottotipoIstitutoT(this.value);
          getIstitutiT(this.value);
        });
      }
    }).send();
}

function getSottotipoIstitutoT(id) {
  var myRequest = new Request({url: host + 'getInstituteKinds2.jsp',
      data: { parentId: id },
      onComplete: function(r){
        if (r.match(/^\s*$/)) $('selectSottotipoT').getParent().setStyle('display', 'none');
        else {
          $('selectSottotipoT').innerHTML = '<select id="sottotipoist" name="sottotipoist">' + opt + r + '</select>';
          $('sottotipoist').addEvent('change', function() {
            getIstitutiT(this.value);
          });
          $('selectSottotipoT').getParent().setStyle('display', '');
        }
      }
    }).send();
}

function getComuniT(id) {
  var myRequest = new Request({url: host + 'getMunicipalitiesFromProvince.jsp',
      onComplete: function(r){
        $("selectComuniT").innerHTML = "<select id=\"comune\" name=\"comune\">" + opt + r + "</select>";
        $("comune").addEvent('change', function() {
          getTipoIstitutoT();
        });
      }
    }).send("idProv=" + id);
}

function getProvinceT(id) {

  var myRequest = new Request({url: host + 'getProvincesFromRegion.jsp',
      onComplete: function(r){
        $("selectProvinciaT").innerHTML = "<select id=\"provincia\" name=\"provincia\">" + opt + r + "</select>";
        $('provincia').addEvent('change', function() {
          getComuniT(this.value);
        });
      }
    }).send("idReg=" + id);
}

function myShow(check, divId) {

  if (check.checked)
    $(divId).setStyle("display", "block");
  else
    $(divId).setStyle("display", "none");

}

function showAltro(id) {

  if (id == 'altro')
    $(id).setStyle("display", "block");
  else
    $('altro').setStyle("display", "none");

}

function showSelect(select, id) {

  if (select.value == 1)
    $(id).setStyle('display','block');
  else
    $(id).setStyle('display','none');

}

function submitProfile(thisForm) {
  var strSend = "";

  strSend += "nome=" + thisForm.nome.value;
  strSend += "&cognome=" + thisForm.cognome.value;
  strSend += "&email=" + thisForm.email.value;
  strSend += "&passwd1=" + thisForm.passwd1.value;
  strSend += "&passwd2=" + thisForm.passwd2.value;

  strSend += "&giornoNascita=" + thisForm.giornoNascita.value;
  strSend += "&meseNascita=" + thisForm.meseNascita.value;
  strSend += "&annoNascita=" + thisForm.annoNascita.value;
  strSend += "&indirizzo=" + thisForm.indirizzo.value;
  strSend += "&cap=" + thisForm.cap.value;
  strSend += "&city=" + thisForm.city.value;
  strSend += "&province=" + thisForm.province.value;
  strSend += "&nation=" + thisForm.nation.value;
  strSend += "&tel=" + thisForm.tel.value;
  strSend += "&cell=" + thisForm.cell.value;

  strSend += "&professione=" + thisForm.professione.value;

  if (thisForm.professione.value == 0) {
    alert("Seleziona la professione");
    return false;
  } // if

  if ( thisForm.professione.value == 1 ) {
    var qrystr = $(thisForm).getElements('input[name=materie]')
      .filter(function(el) { return el.checked; })
      .map(function(el) { return el.name + '=' + encodeURIComponent(el.value); })
      .join('&');
    if (qrystr) strSend += '&' + qrystr;
  } // if

  // Controllo errori
  if (thisForm.giornoNascita.value == "0" ||
      thisForm.meseNascita.value == "0" ||
      thisForm.annoNascita.value == "" ||
      thisForm.indirizzo.value == "" ||
      thisForm.cap.value == "" ||
      thisForm.city.value == "" ||
      thisForm.province.value == "0" ||
      thisForm.tel.value  == "") {
    alert("Errore. Controllare i dati inseriti.");
    return false;
  } // if

  if ( thisForm.professione.value == 1 || thisForm.professione.value == 8 || thisForm.professione.value == 2) {

    if (thisForm.formProfile.value != "") {

      try {
        if (thisForm.cambiaistituto.checked) {
          if (thisForm.regione.value == "0" ||
              thisForm.provincia.value == "0" ||
              thisForm.comune.value == "0" ||
              thisForm.tipoist.value == "0") {

            alert("Controllare la selezione dell'istituto");
            return false;
          }

          try {
            if (thisForm.showistituto.checked &&
              thisForm.newInstitute.value == "") {
              alert("Errore. Controllare la selezione dell'istituto");
              return false;
            } // if
          } catch (e) {
            if (thisForm.istitutoId.value == "0") {
              alert("Istituto non selezionato");
              return false;
            }
          }

          strSend += "&istituto=" + thisForm.istitutoId.value;
          strSend += "&regione=" + thisForm.regione.value;
          strSend += "&provincia=" + thisForm.provincia.value;
          strSend += "&comune=" + thisForm.comune.value;
          strSend += "&tipoist=" + thisForm.tipoist.value;
          //strSend += "&sottotipoist=" + thisForm.sottotipoist.value;
          strSend += "&sottotipoist=" + (thisForm.sottotipoist.value != '0' ? thisForm.sottotipoist.value : '');
          strSend += "&newInstitute=" + thisForm.newInstitute.value;
          strSend += "&newInstAddress=" + thisForm.instDataAddress.value;
          strSend += "&newInstTel=" + thisForm.instDataTel.value;
          strSend += "&newInstEmail=" + thisForm.instDataEmail.value;
          strSend += "&newInstDir=" + thisForm.instDataDirector.value;
          strSend += "&newInstDirTitle=" + thisForm.instDataDirectorTitle.value;
          strSend += "&newInstDirEmail=" + thisForm.instDataDirectorEmail.value;
        }
      } catch (e) {
        if (thisForm.regione.value == "0" ||
            thisForm.provincia.value == "0" ||
            thisForm.comune.value == "0" ||
            thisForm.tipoist.value == "0") {

          alert("Controllare la selezione dell'istituto");
          return false;
        }

        try {
          if (thisForm.showistituto.checked &&
              thisForm.newInstitute.value == "") {
            alert("Errore. Controllare la selezione dell'istituto");
            return false;
          } // if
        } catch (e) {
          if (thisForm.istitutoId.value == "0") {
            alert("Istituto non selezionato");
            return false;
          }
        }

        strSend += "&istituto=" + thisForm.istitutoId.value;
        strSend += "&regione=" + thisForm.regione.value;
        strSend += "&provincia=" + thisForm.provincia.value;
        strSend += "&comune=" + thisForm.comune.value;
        strSend += "&tipoist=" + thisForm.tipoist.value;
        // strSend += "&sottotipoist=" + thisForm.sottotipoist.value;
        strSend += "&sottotipoist=" + (thisForm.sottotipoist.value != '0' ? thisForm.sottotipoist.value : '');
        strSend += "&newInstitute=" + thisForm.newInstitute.value;
        strSend += "&newInstAddress=" + thisForm.instDataAddress.value;
        strSend += "&newInstTel=" + thisForm.instDataTel.value;
        strSend += "&newInstEmail=" + thisForm.instDataEmail.value;
        strSend += "&newInstDir=" + thisForm.instDataDirector.value;
        strSend += "&newInstDirTitle=" + thisForm.instDataDirectorTitle.value;
        strSend += "&newInstDirEmail=" + thisForm.instDataDirectorEmail.value;
      }
    } else {

      if (thisForm.regione.value == "0" ||
          thisForm.provincia.value == "0" ||
          thisForm.comune.value == "0" ||
          thisForm.tipoist.value == "0") {

        alert("Controllare la selezione dell'istituto");
        return false;
      }

      try {
        if (thisForm.showistituto.checked &&
            thisForm.newInstitute.value == "") {
          alert("Errore. Controllare la selezione dell'istituto");
          return false;
        } // if
      }
      catch (e) {
        if (thisForm.istitutoId.value == "0") {
          alert("Istituto non selezionato");
          return false;
        }
      }

      strSend += "&istituto=" + thisForm.istitutoId.value;
      strSend += "&regione=" + thisForm.regione.value;
      strSend += "&provincia=" + thisForm.provincia.value;
      strSend += "&comune=" + thisForm.comune.value;
      strSend += "&tipoist=" + thisForm.tipoist.value;
      // strSend += "&sottotipoist=" + thisForm.sottotipoist.value;
      strSend += "&sottotipoist=" + (thisForm.sottotipoist.value != '0' ? thisForm.sottotipoist.value : '');
      strSend += "&newInstitute=" + thisForm.newInstitute.value;
      strSend += "&newInstAddress=" + thisForm.instDataAddress.value;
      strSend += "&newInstTel=" + thisForm.instDataTel.value;
      strSend += "&newInstEmail=" + thisForm.instDataEmail.value;
      strSend += "&newInstDir=" + thisForm.instDataDirector.value;
      strSend += "&newInstDirTitle=" + thisForm.instDataDirectorTitle.value;
      strSend += "&newInstDirEmail=" + thisForm.instDataDirectorEmail.value;
    } // if
  } // if

  if ( thisForm.professione.value == 6 ) {

    if (thisForm.orgIdFps.value == 'altro') {
      var invFNames = [ 'oDescription', 'oAddress', 'oCap', 'oProvince', 'oTel' ].filter(function(fName) {
        var f = $(thisForm[fName]);
        var inv = f.get('value') == (f.tagName.toLowerCase() == 'select' ? '0' : '');
        f.getParent('div')[inv ? 'addClass' : 'removeClass']('wrong');
        return inv;
      });
      if (invFNames.length > 0) {
        alert('Compilare i campi richiesti');
        return false;
      }
    } // if

    //alert(thisForm.orgIdFps);

    if (thisForm.orgIdFps.value == "0" && thisForm.formProfile.value == "") {
        alert("Errore. Controllare la selezione dell'organizzazione");
        return false;
    }

    // Organization data
    strSend += "&orgIdFps=" + thisForm.orgIdFps.value;
    strSend += "&oDescription=" + thisForm.oDescription.value;
    strSend += "&oAddress=" + thisForm.oAddress.value;
    strSend += "&oCap=" + thisForm.oCap.value;
    strSend += "&oCity=" + thisForm.oCity.value;
    strSend += "&oProvince=" + thisForm.oProvince.value;
    strSend += "&oTel=" + thisForm.oTel.value;
    strSend += "&oEmail=" + thisForm.oEmail.value;

    strSend += "&professioneOther=" + thisForm.professioneOther.value;
    
    if (thisForm.orgId) {
      strSend += "&orgId=" + thisForm.orgId.value;
    }

  } // if

  strSend += "&classe=" + thisForm.classe.value;

  strSend += "&formProfile=" + thisForm.formProfile.value;

//  alert(strSend);
  var redirect = thisForm.redirect.value;

  var myRequest = new Request({async: false, url: host + 'saveUpdateProfile.jsp',
      onComplete: function(r) {
        var s = r.replace("\n", "");
        if (s.indexOf("+") != -1) {
          alert(s.split("+")[0]);
          if (thisForm.formProfile.value == "") {
            Cookie.write('UserFsp', s.split("+")[1], { duration: 7, path: '/' });
            // alert("http://" + window.location.hostname + port + contextPath + "/ita/homepage/register.html?rp=" + redirect);
            location.href="http://" + window.location.hostname + port + contextPath + "/ita/homepage/register.html?rp=" + redirect;
          } else if (redirect) {
            location.href="http://" + window.location.hostname + port + contextPath + redirect + ".html?fp=" + window.location.pathname.replace(contextPath, '').replace(/\.html$/, '');
          }
        } else {
          alert(s);
        }
      }
    }).send(strSend);

  return false;

}

function doLogin(thisForm) {

  var strSend = "";
  var redirect = thisForm.redirect.value;

  strSend += "username=" + thisForm.username.value;
  strSend += "&password=" + thisForm.password.value;
  var myRequest = new Request({async: false, url: host + 'login.jsp',
      onComplete: function(r){
        var cookieVal = r.replace("\n", "");
        if ( cookieVal != "" ) {
          Cookie.write('UserFsp', cookieVal, { duration: 7, path: '/' });
          //alert("redirect to:" + "http://" + window.location.hostname + port + contextPath + redirect);
          location.href = redirect.match(/^\/iniziative/)
            ? "http://" + window.location.hostname + port + contextPath + '/ita/homepage/profilo.html?rp=' + redirect
            : "http://" + window.location.hostname + port + contextPath + redirect;
        } else {
          alert("Username o password errati");
        } // if
      }
    }).send(strSend);

  return false;

}

function doRegistration(thisForm) {

  var strSend = "";

  var infoAgg = "";
  if ($('infoAgg') != null) {
	  var elem = $('infoAgg');
      if (elem.value == '') {
         elem.setStyle("border", "2px solid #CC1931");
         return false;
      }
      infoAgg = $('infoAgg').value;
  } 
  
  strSend += "idUser=" + thisForm.idUser.value;
  strSend += "&idInitiative=" + thisForm.idInitiative.value;
  strSend += "&infoAgg=" + infoAgg;
  
  // Register user to initiative and send emails
  var myRequest = new Request({async: false, url: host + 'registrationInitiative.jsp',
      onComplete: function(r) {
        //alert(r);
        if ( r.replace("\n", "") == "0" ) {
          $('introRegistration').setStyle('display', 'none');
          $('submitRegistration').setStyle('display', 'none');
          if ($('boxInfoAgg') != null) {
        	  $('boxInfoAgg').setStyle('display', 'none');
          }
          $('resultz').setStyle('display', '');
        } else {
          alert("Errore nell'iscrizione.\nRiprovare più tardi");
        } // if
      }
    }).send(strSend);

  return false;

}

function doRetrievePassword(thisForm) {

  var strSend = "";

  strSend = "emailuser=" + thisForm.emailuser.value;

  var myRequest = new Request({async: false, url: host + 'retrievePassword.jsp',
      onComplete: function(r) {
        // alert(r);
        if ( r.replace("\n", "") == "0" ) {
          alert("Ti è stata inviata una mail con la nuova password.");
        } else {
          alert("Utente non riconosciuto.");
        } // if
      }
    }).send(strSend);

  return false;

}
