// form validation function //

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 verifica_form(form,obbligatori,campo_mail,array_figli) {

    var controllo=true
    var nameRegex = /^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*$/;
    var emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
    var messageRegex = new RegExp(/<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/gim);
    
    
    
    
  /*  if (document.getElementById('Possesso_certificato').value=='S') {
     if (!isDate(document.getElementById('Data_notifica_decreto').value,"Data_notifica_decreto")){
        controllo=false;
     }
     if (!isDate(document.getElementById('Data_pronuncia_decreto').value,"Data_pronuncia_decreto")){
        controllo=false;
     }
     if (controllo==true) {
     vaiajax("/ajax-calcola-data.php?Data="+document.getElementById('Data_corso').value+"&Data_decreto="+document.getElementById('Data_notifica_decreto').value);
     }
    }*/
   
if (controllo==true) {
  for (i=0;i<obbligatori.length;i++){
    if(document.getElementById(obbligatori[i]).value == "") {
      inlineMsg(obbligatori[i],'<strong>Errore</strong><br />Campo obbligatorio.',2);
      rosso(obbligatori[i]);
      controllo=false;
      break;
    } else {
      //norm(obbligatori[i])
    }
  }
}
   
   
  /*  if (document.getElementById('Possesso_certificato').value=='S' && controllo==true) {
     
        vaiajax("/ajax-calcola-data.php?Data="+document.getElementById('Data_corso').value+"&Data_decreto="+document.getElementById('Data_notifica_decreto').value);
    }*/
    
mail_form=document.getElementById(campo_mail).value
   if(!mail_form.match(emailRegex) && controllo==true ) {
    inlineMsg(campo_mail,'<strong>Errore</strong><br />Email non valida.',2);
    controllo=false
    
    
  } else 
  
if (document.getElementById('figli_si').checked==false && document.getElementById('figli_no').checked==false && controllo==true) {
  inlineMsg('figli_no','<strong>Errore</strong><br />Campo obbligatorio.',2);
  controllo=false;
}
//alert(123); 
  if (document.getElementById('Consenso').checked!=true && controllo==true){
    inlineMsg('Consenso','<strong>Errore</strong><br />E\' necessario dare il consenso.',2);
    controllo=false    
  }
  if (array_figli.length>0) {
   
    
    for (i=1;i<2;i++){
        if (document.getElementById('Tipo_figlio_bio'+i).checked==false && document.getElementById('Tipo_figlio_ado'+i).checked==false) {
           inlineMsg('Tipo_figlio_ado'+i,'<strong>Errore</strong><br />Selezionare se biologico o adottivo.',2);
           controllo=false;
        }
        if (document.getElementById('Data_nascita_figlio'+i).value=='') {
           inlineMsg('Data_nascita_figlio'+i,'<strong>Errore</strong><br />Inserire data di nascita.',2);
           controllo=false;
        }	
    }
  }
      if (document.getElementById('Possesso_certificato').value=='S') {
  /*    if (!isDate(document.getElementById('Data_notifica_decreto').value,"Data_notifica_decreto")){
      controllo=false;
      }*/
      if (!isDate(document.getElementById('Data_pronuncia_decreto').value,"Data_pronuncia_decreto")){
      controllo=false;
      }
      if (controllo==true) {
      
      vaiajax("/ajax-calcola-data.php?Data="+document.getElementById('Data_corso').value+"&Data_decreto="+document.getElementById('Data_pronuncia_decreto').value);
      }
      } else {
	if (controllo==true) document.getElementById('form').submit();
      }
//
}
function rosso(campo) {
  var nomi_ar=new Array("Nome_coniuge1","Cognome_coniuge1","Nome_coniuge2","Cognome_coniuge2");
  var prof_ar=new Array("Professione_coniuge1","Professione_coniuge2","Indirizzo","E_mail");
  chk=true;
  for (i=0;i<4;i++){
    if (campo==nomi_ar[i]) {
      document.getElementById(campo).style.backgroundImage='url("/images/com/iscrizioni_step3_formcoppiecondecreto/campoditesto_nome_bg_red.png")';
      chk=false
    }
  }
  if (chk==true) {
  for (i=0;i<4;i++){
    if (campo==prof_ar[i]) {
      document.getElementById(campo).style.backgroundImage='url("/images/com/iscrizioni_step3_formcoppiecondecreto/campoditesto_professione_bg_red.png")';
      chk=false
    }
  }
  }
  if (chk==true){
  document.getElementById(campo).style.backgroundImage='url("/images/com/iscrizioni_step3_formcoppiecondecreto/campoditesto_datadinascita_bg_red.png")';
 // return true;
  }

}
function norm(campo){
 /*var nomi_ar2=new Array("Nome_coniuge1","Cognome_coniuge1","Nome_coniuge2","Cognome_coniuge2");
  var prof_ar2=new Array("Professione_coniuge1","Professione_coniuge2","Indirizzo","E_mail");
  chk=true;
  for (i=0;i<4;i++){
    if (campo==nomi_ar2[i]) {
      document.getElementById(campo).style.backgroundImage='url("/images/com/iscrizioni_step3_formcoppiecondecreto/campoditesto_nome_bg.png")';
      chk=false
    }
  }
  if (chk==true) {
  for (i=0;i<4;i++){
    if (campo==prof_ar2[i]) {
      document.getElementById(campo).style.backgroundImage='url("/images/com/iscrizioni_step3_formcoppiecondecreto/campoditesto_professione_bg.png")';
      chk=false
    }
  }
  }
/*  if (chk==true){
  //document.getElementById(campo).style.backgroundImage='url("/images/com/iscrizioni_step3_formcoppiecondecreto/campoditesto_datadinascita_bg.png")';  }
 */
}
function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr,quale){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
           
		inlineMsg(quale,'<strong>Errore</strong><br />La data deve essere in formato dd/mm/YYYY.',2);
                //alert(3333);
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		inlineMsg(quale,'<strong>Errore</strong><br />Inserire un mese valido.',2);
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		inlineMsg(quale,'<strong>Errore</strong><br />Inserire un giorno valido.',2);
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		inlineMsg(quale,'<strong>Errore</strong><br />Anno non valido.',2);
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		inlineMsg(quale,'<strong>Errore</strong><br />Inserire una data valida.',2);
		return false
	}
return true
}

// START OF MESSAGE SCRIPT //

var MSGTIMER = 20;
var MSGSPEED = 5;
var MSGOFFSET = 3;
var MSGHIDE = 3;

// build out the divs, set attributes and call the fade function //
function inlineMsg(target,string,autohide) {
  var msg;
  var msgcontent;
  if(!document.getElementById('msg')) {
    msg = document.createElement('div');
    msg.id = 'msg';
    msgcontent = document.createElement('div');
    msgcontent.id = 'msgcontent';
    document.body.appendChild(msg);
    msg.appendChild(msgcontent);
    msg.style.filter = 'alpha(opacity=0)';
    msg.style.opacity = 0;
    msg.alpha = 0;
  } else {
    msg = document.getElementById('msg');
    msgcontent = document.getElementById('msgcontent');
  }
  msgcontent.innerHTML = string;
  msg.style.display = 'block';
  var msgheight = msg.offsetHeight;
  var targetdiv = document.getElementById(target);
  targetdiv.focus();
  var targetheight = targetdiv.offsetHeight;
  var targetwidth = targetdiv.offsetWidth;
  var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
  var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
  msg.style.top = topposition + 'px';
  msg.style.left = leftposition + 'px';
  clearInterval(msg.timer);
  msg.timer = setInterval("fadeMsg(1)", MSGTIMER);
  if(!autohide) {
    autohide = MSGHIDE;  
  }
  window.setTimeout("hideMsg()", (autohide * 1000));
}

// hide the form alert //
function hideMsg(msg) {
  var msg = document.getElementById('msg');
  if(!msg.timer) {
    msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
  }
}

// face the message box //
function fadeMsg(flag) {
  if(flag == null) {
    flag = 1;
  }
  var msg = document.getElementById('msg');
  var value;
  if(flag == 1) {
    value = msg.alpha + MSGSPEED;
  } else {
    value = msg.alpha - MSGSPEED;
  }
  msg.alpha = value;
  msg.style.opacity = (value / 100);
  msg.style.filter = 'alpha(opacity=' + value + ')';
  if(value >= 99) {
    clearInterval(msg.timer);
    msg.timer = null;
  } else if(value <= 1) {
    msg.style.display = "none";
    clearInterval(msg.timer);
  }
}

// calculate the position of the element in relation to the left of the browser //
function leftPosition(target) {
  var left = 0;
  if(target.offsetParent) {
    while(1) {
      left += target.offsetLeft;
      if(!target.offsetParent) {
        break;
      }
      target = target.offsetParent;
    }
  } else if(target.x) {
    left += target.x;
  }
  return left;
}

// calculate the position of the element in relation to the top of the browser window //
function topPosition(target) {
  var top = 0;
  if(target.offsetParent) {
    while(1) {
      top += target.offsetTop;
      if(!target.offsetParent) {
        break;
      }
      target = target.offsetParent;
    }
  } else if(target.y) {
    top += target.y;
  }
  return top;
}

// preload the arrow //
if(document.images) {
  arrow = new Image(7,80); 
  arrow.src = "/images/msg_arrow.gif"; 
}



