// JavaScript Document
function trim(stringa){
  if(!stringa) return "";
	while (stringa.substring(0,1) == ' '){
		stringa = stringa.substring(1, stringa.length);
	}
	while (stringa.substring(stringa.length-1, stringa.length) == ' '){
		stringa = stringa.substring(0,stringa.length-1);
	}
	return stringa;
}
function getElementsByAttribute(aName, aValue, specifictag) {
  if (!specifictag) {
	   var allTags = document.getElementsByTagName('*') || document.all;
	} else {
    var allTags = document.getElementsByTagName(specifictag) || document.all;
  }
	var results = new Array();
	for(var i=0; i < allTags.length; i++) {
		if(allTags[i].tagName != "TABLE" && allTags[i].getAttribute(aName) &&  aValue == allTags[i].getAttribute(aName)) {
			results.push(allTags[i]);
		}
	}
	return results;
}
function isEmail(par) {
	var e = par;
	e = e.replace(/^\s*(\S*)\s*$/, "$1");
	var pattern = /^[A-Za-z0-9_.-]+@[A-Za-z0-9_.-]+\.[A-Za-z]{2,}$/;
	return (e == e.match(pattern));
}
function isSelected(elem,par) {
  if ((par == null || par == "") && elem.tagName.toLowerCase() == "select" && elem.options[0].selected == true) {
    return true;
  } else if (par != null && par != "" && elem.value == par) {
    return true;
  } 
  return false;
}
function isChecked(elem) {
  if (elem.checked == true) {
    return true;
  } 
	return false;
}
function isPasswordRange(elem,range) {
  var limits = range.split("-");
  if (range == "" || !parseInt(limits[0])) {
    return true;  
  } 
  if (elem.value.length < limits[0]) {
    return false;
  }
  if ( parseInt(limits[1]) && elem.value.length > limits[1] ) {
    return false;
  }
  return true; 
}
function isExactLength(elem,len) {
  if (1*elem.value.length != 1*len) {
    return false;
  }
  return true;
}
function isGeminiOf(elem,matchelem) {
  if(elem.value != matchelem.value) {
    return false;
  } 
  return true;  
}
function copyFrom(elem,sourceelem) {

  if (sourceelem) {
    elem.value = sourceelem.value;
  }
  	//alert(elem.name+":"+elem.value + " --- " +sourceelem.name+":"+sourceelem.value);
}
function trace(alertdiv,phrase) {
  if (alertdiv) {
    alertdiv.innerHTML = "Alcuni dati inseriti non risultano corretti. Ti preghiamo di verificare i campi segnalati in <span>arancione</span>.<br/><br/>"+phrase;
    alertdiv.style.display = "block";
  } else {
    alert("CAMPI NON COMPILATI O DA CORREGGERE:\n"+phrase);
  }
}
function litLabelForElement(f,elsarray) {
  var labels = f.getElementsByTagName("label");
  for (var i = 0; i < labels.length; i++) {
    if(labels[i].className.indexOf("wrong") != -1) {
      labels[i].className = labels[i].className.replace("wrong","");
    }
    for (var j = 0; j < elsarray.length; j++) {
      if (labels[i].htmlFor == elsarray[j].name) {
        labels[i].className += " wrong";
      }
    }
  }
}
function getLabelForElement(f,elem) {
   var labels = f.getElementsByTagName("label");
   for (var i = 0; i < labels.length; i++) {
        if(labels[i].htmlFor == elem.name) {
          if(labels[i].innerText == null || labels[i].innerText == "") {
            return labels[i].textContent;
          } else {
            return labels[i].innerText;
          }
          break;
        }
   }
   return elem.name;
}
function isNullOrEmpty(str) {
  var s = trim(str);
  if (s.replace(/\s+/gi,"") == "" || s.lastIndexOf("*") == s.length-1) {
    return true;
  }
  return false;
}
function check(theform) {
  var f = document.forms[theform];
  if(!f["validate"] || f["validate"].value == "") {
    f.submit();
    return;
  }
  
  
  var validatevalue = f["validate"].value;
 
  //PM specific check
  var abbtype = f["leggendo_abb_type"];
  if (abbtype) {
      for (var i = 0; i < abbtype.length; i++) {
        if (abbtype[i].checked == true && abbtype[i].value == "scuola" && f["addschoolvalidate"] && f["addschoolvalidate"].value != "") {
          validatevalue += ","+f["addschoolvalidate"].value;
          break;
        } 
      } 
  }
  //end of PM specific check
  

  var divs = f.getElementsByTagName("div");
  for (var i = 0; i < divs.length; i++) {
    if(divs[i].className.indexOf("alert") != -1) {
      var alertdiv = divs[i];
      break;
    }
  }
  
  var fields = validatevalue.split(",");
  var wrong = "";
  var wronglabels = new Array();
  //var empty = "";
  for (var i = 0; i < fields.length; i++) {
      var elem = f[fields[i]];
      
        //normal fields
      var tnescheck = null;
      try {
        tnescheck = elem.getAttribute("tnes:check") ? elem.getAttribute("tnes:check") : null;
      } catch(x) {
        tnescheck = elem[0].getAttribute("tnes:check") ? elem[0].getAttribute("tnes:check") : null;
      }

      if (tnescheck == null && isNullOrEmpty(elem.value)) {
        //checks if the element's value is ""
        wrong += "---- Non hai compilato il campo '"+getLabelForElement(f,elem)+"' ---- <br/>";
        wronglabels.push(elem);
      } else if(tnescheck && tnescheck == "email") {
        //checks if is email
        if(isNullOrEmpty(elem.value)) {
          wrong += "---- Non hai compilato il campo '"+getLabelForElement(f,elem)+"' ---- <br/>";
          wronglabels.push(elem);
        } else if (!isNullOrEmpty(elem.value) && !isEmail(elem.value)) {
          wrong += "---- L'indirizzo e-mail inserito non è corretto ---- <br/>";
          wronglabels.push(elem);
        }      
      } else if (tnescheck && tnescheck.indexOf("select") == 0 && isSelected(elem, tnescheck.split("select")[1])) {
        //checks if, in a select, a certain value is selected [example... tnes:check("select") checks for first value selected, tnes:check("select-") checks for "-" selected, tnes:check("selectfoo") checks for "foo" selected]
          wrong += (elem.tagName.toLowerCase() == "select" ? "---- E' necessario selezionare una voce del campo '" : "---- Non hai compilato il campo '") + getLabelForElement(f,elem) + "' ---- <br/>";
          wronglabels.push(elem);
      } else if (tnescheck && tnescheck == "privacy" && !isChecked(elem)) {
        //checks if a privacy checkbox is checked
          wrong += "---- E' necessario accettare i termini della legge sulla privacy ---- <br/>";
          wronglabels.push(elem);
      } else if (tnescheck && tnescheck == "checked" && !isChecked(elem)) {
        //checks if a checkbox is checked
        wrong += "---- Manca il segno di spunta nel campo "+getLabelForElement(f,elem)+" ---- <br/>";
        wronglabels.push(elem);
      } else if (tnescheck && tnescheck.indexOf("password") == 0 && isNullOrEmpty(elem.value)) {
        //checks if the password is compiled
        wrong += "---- Non hai compilato il campo '"+getLabelForElement(f,elem)+"' ---- <br/>";
        wronglabels.push(elem);
      } else if (tnescheck && tnescheck.indexOf("password") == 0 && !isPasswordRange(elem, tnescheck.split("password")[1]) ) {
        //checks if a compiled field respects the right number of characters
        var pwrange = tnescheck.split("password")[1].split("-");
        var pwphrase = "";
        if  (pwrange[0] && pwrange[0] != "" && pwrange[1] && pwrange[1] != "") {
          pwphrase = "(da "+pwrange[0]+" a "+pwrange[1]+")";
        } else if (pwrange[0] && pwrange[0] != "" && (pwrange[1] == "" || pwrange[1] == null)) {
          pwphrase = "(minimo "+pwrange[0]+")";
        } 
        wrong += "---- La password non ha il numero corretto di caratteri "+pwphrase+" ---- <br/>";
        wronglabels.push(elem);
      } else if(tnescheck && tnescheck.indexOf("exactlength") == 0 && !isExactLength(elem, tnescheck.split("exactlength")[1])) {
        wrong += "---- Il campo '"+getLabelForElement(f,elem)+"' non ha il numero corretto di caratteri ("+tnescheck.split("exactlength")[1]+") ---- <br/>";
        wronglabels.push(elem);
      } else if (tnescheck && tnescheck.indexOf("geminiof") == 0 && isNullOrEmpty(elem.value)) {
        //checks if the gemini password is compiled
        wrong += "---- Non hai compilato il campo '"+getLabelForElement(f,elem)+"' ---- <br/>";
        wronglabels.push(elem);
      } else if (tnescheck && tnescheck.indexOf("geminiof") == 0 && !isGeminiOf(elem, f[tnescheck.split("geminiof")[1]]) ) {
        wrong += "---- La voce inserita nel campo '"+getLabelForElement(f,elem)+"' non corrisponde alla password scelta ---- <br/>";
        wronglabels.push(elem);
      } else if (tnescheck && tnescheck.indexOf("ignorepasswd") == 0 && !isNullOrEmpty(elem.value) && !isPasswordRange(elem, tnescheck.split("ignorepasswd")[1]) ) {
            //checks if a compiled field respects the right number of characters
            var pwrange = tnescheck.split("ignorepasswd")[1].split("-");
            var pwphrase = "";
            if  (pwrange[0] && pwrange[0] != "" && pwrange[1] && pwrange[1] != "") {
              pwphrase = "(da "+pwrange[0]+" a "+pwrange[1]+")";
            } else if (pwrange[0] && pwrange[0] != "" && (pwrange[1] == "" || pwrange[1] == null)) {
              pwphrase = "(minimo "+pwrange[0]+")";
            } 
            wrong += "---- La password non ha il numero corretto di caratteri "+pwphrase+" ---- <br/>";
            wronglabels.push(elem);
      } else if (tnescheck && tnescheck.indexOf("ignoregemof") == 0 && !isGeminiOf(elem, f[tnescheck.split("ignoregemof")[1]])) {
        wrong += "---- La voce inserita nel campo '"+getLabelForElement(f,elem)+"' non corrisponde alla password scelta ---- <br/>";
        wronglabels.push(elem);
      } else if (tnescheck && tnescheck.indexOf("copyfrom") == 0 && tnescheck.split("copyfrom")[1] != "") {
        copyFrom(elem,f[tnescheck.split("copyfrom")[1]]);
      } else if (tnescheck && tnescheck.indexOf("pmaltro") == 0) {
        //PM specific check
        if (elem.options[0].selected == true) {
          wrong += ("---- E' necessario selezionare una voce del campo '") + getLabelForElement(f,elem) + "' ---- <br/>";
          wronglabels.push(elem);
        } else if ( elem.value.indexOf("altro") == 0 && isNullOrEmpty(f[elem.name+"_altro"].value) ) {
          wrong += "---- Non è stato specificato alcunchè nel campo 'Altro' ---- <br/>";
          wronglabels.push(f[elem.name+"_altro"]);
        } else {
          f[tnescheck.split("pmaltro")[1]].value = (elem.value.indexOf("altro") == 0 ? "altro: "+f[elem.name+"_altro"].value : elem.value);
        }
        //end of PM specific check
      }
       //alert(tnescheck+" |"+elem.value+"|");
  }     
  
  
  if (wrong != "") {
    trace(alertdiv,wrong);
    litLabelForElement(f,wronglabels);
  } else if (wrong == "") {
    //alert("[SORRY - submit disabled]:\nthere is some work in progress!");
    f.submit();
  }
}

function showOther(theform,elem) {
  
  var f = document.forms[theform];
  var txt = f[elem.name+"_altro"];
  var txtcontainer = txt.parentNode;
  
  for (var c = 0; c <= 10; c++) {
     if(txtcontainer.tagName != null && txtcontainer.tagName.toLowerCase() == "div") {
         break;
     } else {
         txtcontainer = txtcontainer.parentNode;
     }
  }
  if (elem.value.indexOf("altro") == 0) {
    txtcontainer.style.display = "block";  
  } else {
    txtcontainer.style.display = "none";
  }
}

function showAddSchoolDivs(theform) {
  //PM specific check
  var f = document.forms[theform];
  var abbtype = f["leggendo_abb_type"];
  var schoolischecked = false;
  for (var i = 0; i < abbtype.length; i++) {
    var addschooldivs = getElementsByAttribute("name","addschool","div");
    if (abbtype[i].checked == true && abbtype[i].value == "scuola") {
      schoolischecked = true;
      break;
    } 
  }
  for (var i = 0; i < addschooldivs.length; i++) {
    addschooldivs[i].style.display = (schoolischecked ? "block" : "none");
  }
  //end of PM specific check
}


window.onload = function() {
  //registration form: shows "altro" field if "altro" is selected in "js_scuola" , "js_classe" selects.
  if (document.forms["registratiform"]) {
    
    var f = document.forms["registratiform"];
    if (f["js_scuola"]) {
      showOther("registratiform",f["js_scuola"]);
    } 
    if (f["js_classe"]) {
      showOther("registratiform",f["js_classe"]);
    }
    if (f["leggendo_abb_type"]) {
      showAddSchoolDivs("registratiform");
      for (var i = 0; i < f["leggendo_abb_type"].length; i++) {
        f["leggendo_abb_type"][i].onclick = function() {
          showAddSchoolDivs("registratiform");
        }
      }
    }
    
  } //if document.forms["registratiform"]
}
