// JavaScript Document
function trim(stringa){
	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 isValidDate(dd,mm,yyyy) {
  if(dd.length > 2 || mm.length > 2 || yyyy.length > 4) return false;
  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) {
    return false;
  } else {
    return true;
  }
}

function isDateTextField(el, dropfield) {
  //tries to split by "/";
  var par = el.value;
  el.value = par.replace("\\","/");
  var dmy = el.value.split("/");
  if (dmy.length != 3) {
    //alert("data non valida (bad splitting!)");
    dropfield.value = "";
    //el.value = "";
    return false;
  } 
  var dd = dmy[0];
  var mm = dmy[1];
  var yyyy = dmy[2];
  var thedate = new Date(yyyy, 1*mm-1, dd);
  if (isValidDate(dd,mm,yyyy)) {
    
    el.value = dd+"/"+mm+"/"+yyyy;
    dropfield.value = yyyy+"-"+(mm.length < 2 ? "0"+mm : mm)+"-"+(dd.length < 2 ? "0"+dd : dd);
    return true;
  }  else {
    dropfield.value = "";
    //el.value = "";
    return false;
  } 
  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;
  
  if (isValidDate(dd,mm,yyyy) && yyyy.length == 4) {
    elem.value = yyyy+"-"+(mm.length < 2 ? "0"+mm : mm)+"-"+(dd.length < 2 ? "0"+dd : dd);
    return true;
  } else {
    elem.value = "";
    return false;
  }
}

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;
  }
}

function isPositiveInt(par) {
	var f = par;
	var pattern = /^[0-9]*$/;
	if(f == pattern.exec(f)) {
		par = f;
	} else {
		return false;
	}
	return true;
}

function isInt(par) {
	var f = par;
	var pattern = /^[\-]?[0-9]*$/;
	if(f == pattern.exec(f)) {
		par = f;
	}
	else {
		return false;
	}
	return true;
}

function onlyPositiveInts(elem) {
	var par = elem.value;
	if (isPositiveInt(par))
		return;
	//while (!isPositiveInt(par))
		//par = par.substring(0,par.length-1);
	elem.value = par;
}

function trace(alertdiv,phrase) {
  if (alertdiv) {
    alertdiv.innerHTML = "Alcuni dati inseriti non risultano corretti. Ti preghiamo di verificare i campi evidenziati"+phrase;
    alertdiv.style.display = "block";
  } else {
    phrase = phrase.replace(/<\/?ul>/gi,"");
    phrase = phrase.replace(/<li>/gi,"- ");
    phrase = phrase.replace(/<\/li>/gi,"\n");
    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 check(theform, btn, dobeforesubmit) {
  
  if (btn != null && btn.disabled == true) {
    return false;
  } else if (btn != null && btn.disabled != true) {
    btn.disabled = true;  
  }
  
  var f = document.forms[theform];
  
  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 = new Array();
  if(f["validate"]) {
    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]];
      if(!elem) continue;
      //normal fields
      var tnescheck = null;
      var avoidwhenempty = false;
      if (elem && elem.getAttribute("tnes:check")) {
        tnescheck = elem.getAttribute("tnes:check");
      } else if (elem && elem.getAttribute("tnes:checkwhenfilled")) {
        tnescheck = elem.getAttribute("tnes:checkwhenfilled");
        //alert("esiste tnes check when filled sul campo"+getLabelForElement(f,elem));
        avoidwhenempty = true;
      } else if (elem && elem[0] && elem[0].getAttribute("tnes:check")) {
        tnescheck = elem[0].getAttribute("tnes:check");
      } else if (elem && elem[0] && elem[0].getAttribute("tnes:checkwhenfilled")) {
        tnescheck = elem[0].getAttribute("tnes:checkwhenfilled");
        avoidwhenempty = true;
      }
      
      
      if (tnescheck == null && isNullOrEmpty(elem.value)) {
        //checks if the element's value is ""
        wrong += "<li>Non hai compilato il campo '"+getLabelForElement(f,elem)+"'</li>";
        wronglabels.push(elem);
      } else if (tnescheck && isNullOrEmpty(elem.value) && avoidwhenempty == true) {
        //if the field has a tnes:checkwhenfilled attribute instead of a tnes:check attribute, it will not be verified when empty.
        continue;
      } else if (tnescheck && isNullOrEmpty(elem.value) && avoidwhenempty == false) {
        wrong += "<li>Non hai compilato il campo '"+getLabelForElement(f,elem)+"'</li>";
        wronglabels.push(elem);
      } else if (tnescheck && tnescheck.indexOf("text") == 0 && !textMode(elem,tnescheck.substring(4))) {
        //check if element's value complies with some regexps...
        wrong += "<li>Il campo '"+getLabelForElement(f,elem)+"' conteneva caratteri non validi che sono stati eliminati per ragioni di sicurezza.</li>";
        wronglabels.push(elem); 
      } else if (tnescheck && tnescheck == "email") {
        //checks if is email
        if(isNullOrEmpty(elem.value)) {
          wrong += "<li>Non hai compilato il campo '"+getLabelForElement(f,elem)+"'</li>";
          wronglabels.push(elem);
        } else if (!isNullOrEmpty(elem.value) && !isEmail(elem.value)) {
          wrong += "<li>L'indirizzo e-mail inserito non è corretto</li>";
          wronglabels.push(elem);
        }      
      } else if(tnescheck && tnescheck.indexOf("datetextfield") == 0 && !isDateTextField(elem, f[tnescheck.substring(13)])) {
        //checks if a date is valid. a textfield with tnes:check='datetextfield...' will accept only gg/mm/aaaa or gg\mm\aaaa dates. If the date is correctly written by the user, it will be dropped in f[...] hiddenfield. This hiddenfield will contain yyyy-mm-dd formatted date. 
        wrong += "<li>La data corrispondente al campo '"+getLabelForElement(f,elem)+"'</em> non e' valida</li>";
        wronglabels.push(elem);
      } else if(tnescheck && tnescheck.indexOf("date") == 0 && tnescheck.indexOf("datetextfield") != 0 && !isDate(f, tnescheck.substring(4).split(","), elem)) {
        //checks if a date is valid. espects an hiddenfield with tnes:check='date...,...,...' and espects 3 input fields ( ...,... and ... ). If the date is correctly written through the 3 input fields, the date will be dropped into the hiddenfield, formatted as yyyy-mm-dd.
        wrong += "<li>La data corrispondente al campo '"+getLabelForElement(f,elem)+"'</em> non e' valida</li>";
        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, es: tnes:check="filejpg,gif"
        wrong += "<li>Campo '"+getLabelForElement(f,elem)+"'</em>: il file non è stato inserito o è del tipo sbagliato (vengono accettati solo i file di tipo "+tnescheck.substring(4)+")</li>";
        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" ? "<li>E' necessario selezionare una voce del campo '" : "<li>Non hai compilato il campo '") + getLabelForElement(f,elem) + "'</em></li>";
          wronglabels.push(elem);
      } else if (tnescheck && tnescheck == "privacy" && !isChecked(elem)) {
        //checks if a privacy checkbox is checked
          wrong += "<li>E' necessario dare il proprio consenso al trattamento dei dati</li>";
          wronglabels.push(elem);
      } else if (tnescheck && tnescheck == "checked" && !isChecked(elem)) {
        //checks if a checkbox is checked
        wrong += "<li>Manca il segno di spunta nel campo '"+getLabelForElement(f,elem)+"'</em></li>";
        wronglabels.push(elem);
      } else if (tnescheck && tnescheck.indexOf("password") == 0 && isNullOrEmpty(elem.value)) {
        //checks if the password is compiled
        wrong += "<li>Non hai compilato il campo '"+getLabelForElement(f,elem)+"'</li>";
        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 += "<li>La password non ha il numero corretto di caratteri "+pwphrase+"</li>";
        wronglabels.push(elem);
      } else if(tnescheck && tnescheck.indexOf("exactlength") == 0 && !isExactLength(elem, tnescheck.split("exactlength")[1])) {
        wrong += "<li>Il campo '"+getLabelForElement(f,elem)+"' non ha il numero corretto di caratteri ("+tnescheck.split("exactlength")[1]+")</li>";
        wronglabels.push(elem);
      } else if (tnescheck && tnescheck.indexOf("geminiof") == 0 && isNullOrEmpty(elem.value)) {
        //checks if the gemini password is compiled
        wrong += "<li>Non hai compilato il campo '"+getLabelForElement(f,elem)+"'</li>";
        wronglabels.push(elem);
      } else if (tnescheck && tnescheck.indexOf("geminiof") == 0 && !isGeminiOf(elem, f[tnescheck.split("geminiof")[1]]) ) {
        wrong += "<li>La voce inserita nel campo '"+getLabelForElement(f,elem)+"' non corrisponde alla password scelta</li>";
        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 += "<li>La password non ha il numero corretto di caratteri "+pwphrase+"</li>";
            wronglabels.push(elem);
      } else if (tnescheck && tnescheck.indexOf("ignoregemof") == 0 && !isGeminiOf(elem, f[tnescheck.split("ignoregemof")[1]])) {
        wrong += "<li>La voce inserita nel campo '"+getLabelForElement(f,elem)+"' non corrisponde alla password scelta</li>";
        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=="newsletterspecialcheck") {
          var newsletter = null;
          var count = 0;
          for (var k = 0; k < f["newsletter"].length && count < 6; k++) {
          	if (f["newsletter"][k].value == "true" && f["newsletter"][k].checked == true) {
          		newsletter = true;
          		break;
          	} else if (f["newsletter"][k].value == "false" && f["newsletter"][k].checked == true) {
          		newsletter = false;
          	}
          }		
          if (newsletter == null) {
          	wrong += "<li>Non e' stato specificato se ci si vuole iscrivere o meno alla newsletter!</li>";
          	wronglabels.push(elem);
          	//return false;
          } else if (newsletter == true) {
          	var chb_funzioni = document.getElementsByName("funzioni");
          	var chb_settori = document.getElementsByName("settori");
          	var chb_iniziative_speciali = document.getElementsByName("iniziative_speciali");
          	var atleastonechecked = false;
          	for (var k = 0; k < chb_funzioni.length; k++) {
          		if(chb_funzioni[k].checked == true) {
          			atleastonechecked = true;
          			break;
          		}
          	}
          	for (var k = 0; k < chb_settori.length; k++) {
          		if(chb_settori[k].checked == true) {
          			atleastonechecked = true;
          			break;
          		}
          	}
          	for (var k = 0; k < chb_iniziative_speciali.length; k++) {
          		if(chb_iniziative_speciali[k].checked == true) {
          			atleastonechecked = true;
          			break;
          		}
          	}
          	if(atleastonechecked == false) {
          		wrong += "<li>Si e' scelto di ricevere la newsletter ma non sono state indicate le aree di interesse!</li>";
          		wronglabels.push(elem);
          	}
          }
      }
  }     
  if (wrong != "") {
    trace(alertdiv,"<ul>"+wrong+"</ul>");
    litLabelForElement(f,wronglabels);
    if (btn != null) btn.disabled = false;
  } else if (wrong == "") {
    if(dobeforesubmit && dobeforesubmit() != true) {
      if (btn != null) btn.disabled = false;
      return;
    } 
    //alert("[SORRY - submit disabled]:\nthere is some work in progress!");
    f.submit();
  }
}//check_form

