// 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 isNullOrEmpty(str) {
  var s = trim(str);
  if (s.replace(/\s+/gi,"") == "" || s.lastIndexOf("*") == s.length-1) {
    return true;
  }
  return false;
}

function isDate(f,dmy,elem) {
  var dd = f[dmy[0]].value;
  var mm = f[dmy[1]].value;
  var yyyy = f[dmy[2]].value;
  
  var thedate = new Date(yyyy, 1*mm-1, dd);
  
  if (thedate.getDate() != dd || isNullOrEmpty(dd) || isNullOrEmpty(mm) || isNullOrEmpty(yyyy) || 1*dd == 0 || 1*mm == 0 || 1*yyyy == 0 || 1*mm >12) {
    elem.value = "";
    return false;
  }
  
  elem.value = yyyy+"-"+(mm < 10 ? "0"+mm : mm)+"-"+(dd < 10 ? "0"+dd : dd);
  return true;
}
function isAcceptedFile(extensions,elem) {
  if (elem.value.indexOf(".") == -1) return true;
  var currentextension = elem.value.substring(elem.value.lastIndexOf(".")+1);
  var accepted = false;
  for (var i = 0; i < extensions.length; i++) {
    if (trim(currentextension) == trim(extensions[i])) {
      accepted = true;
      break;
    }
  }
  if (!accepted) {
    return false;
  }
  return true;
}
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 == "" && elem.tagName == "select" && elem.options[0].selected == true) {
    return true;
  } else if (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 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 check(theform) {
  var f = document.forms[theform];
  if(!f["validate"] || f["validate"].value == "") {
    f.submit();
    return;
  }
  
 
  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 = f["validate"].value.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)+"'\n";
        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)+"'\n";
          wronglabels.push(elem);
        } else if (!isNullOrEmpty(elem.value) && !isEmail(elem.value)) {
          wrong += "- L'indirizzo e-mail inserito non è corretto\n";
          wronglabels.push(elem);
        }      
      } else if(tnescheck && tnescheck.indexOf("date") == 0 && !isDate(f, tnescheck.substring(4).split(","), elem)) {
        //checks if a date is valid
          wrong += "- Il campo '"+getLabelForElement(f,elem)+"' non e' compilato o la data inserita non e' valida\n";
          wronglabels.push(elem);
      } else if( tnescheck && tnescheck.indexOf("file") == 0 && (!isAcceptedFile(tnescheck.substring(4).split(","), elem) || isNullOrEmpty(elem.value)) ) {
        //checks if a filetype is accepted in an input type file field
        wrong += "- Campo '"+getLabelForElement(f,elem)+"': vengono accettati solo i file di tipo "+tnescheck.substring(4)+"\n";
        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) + "'\n";
          wronglabels.push(elem);
      } else if (tnescheck && tnescheck == "privacy" && !isChecked(elem)) {
        //checks if a privacy checkbox is checked
          wrong += "- E' necessario dare il proprio consenso al trattamento dei dati\n";
          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)+"\n";
        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)+"'\n";
        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+"\n";
        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]+")\n";
        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)+"'\n";
        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\n";
        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+"\n";
            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\n";
        wronglabels.push(elem);
      } else if (tnescheck && tnescheck.indexOf("copyfrom") == 0 && tnescheck.split("copyfrom")[1] != "") {
        copyFrom(elem,f[tnescheck.split("copyfrom")[1]]);
      } 
       //alert(tnescheck+" |"+elem.value+"|");
  }     
  
  
  if (wrong != "") {
    alert("CAMPI NON COMPILATI O DA CORREGGERE:\n"+wrong);
    litLabelForElement(f,wronglabels);
  } else if (wrong == "") {
    //alert("[SORRY - submit disabled]:\nthere is some work in progress!");
    f.submit();
  }
}