// ver. 1.2

// inserire l'include nel tag head:
// <script language="JavaScript" src="/lib/js/e3Utility.js" type="text/javascript"></script>
// <script language="JavaScript" src="/lib/js/e3Validate.js" type="text/javascript"></script>
// Nel tag form mettere: validate="validate"
// 
// accetta gli attributi min e max
// 
// ________________________________________ validazione campi form

var _e3Validate = function(){}

_e3Validate.prototype.validate_findobj = function(n, d) { //v4.0
       
  var p,i,x;  
  
  if(!d) d=document; 
  if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; 
    n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; 
  for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=validate_findobj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); 
  return x;
}


_e3Validate.prototype.validate_getFieldName = function(field) {
  var name;
	
  name=field.getAttribute("title");
  if ((name=="") || (name==null))
    name=field.getAttribute("id");
  if ((name=="") || (name==null))
    name=field.getAttribute("name");
  if ((name=="") || (name==null))
    name="";
  return name;
}


_e3Validate.prototype.validate_validateField = function(field) { //v4.0
	
	var i, btn, errors='';
	var subtype;
	var required;
	var type;
	var minValue;
	var maxValue;
	var equalsToName;
	var equalsTo;
	var name;
	var minLength;
	var maxLength;

  	name=_e3Validate.prototype.validate_getFieldName(field);  
 
	
	required=((field.getAttribute('required')=='required')||(field.getAttribute('required')=='1'))?true:false;
	 
  	equalsToName=field.getAttribute('equalsTo');

	
	  //Se il campo non e' obbligatorio, non e' vuoto e non deve essere confrontato, esce
	  if ((!required) && (field.value=="") && (equalsToName==null)) 
		  return true;
	  
	  if (equalsToName!=null) {
		
		equalsTo=_e3Validate.prototype.validate_findobj(equalsToName);
		
		
		 if (equalsTo.value!=field.value) {
		   errors += "- " + name + " diverso da " + _e3Validate.prototype.validate_getFieldName(equalsTo) + ".\n";
		 }
	  }

  //Controlla campo obbligatorio

  if ((required) && (field.value=="")) {
   errors += "- " + name + " obbligatorio.\n";
  }
	
  //Controlla checkbox/radio button obbligatori
	if ((required) && 
			((field.type.toUpperCase()=="CHECKBOX") || (field.type.toUpperCase()=="RADIO"))
		 ) {
		if (!field.checked) {
			errors += "- " + name + " obbligatorio.\n";
		}
	}

  type=field.getAttribute('subtype');
  minValue=parseInt(field.getAttribute('min'));
  maxValue=parseInt(field.getAttribute('max'));

	//Controllo lunghezza minima e massima
	minLength=parseInt(field.getAttribute('minLength'));
	if (minLength==0)
	  minLength=parseInt(field.getAttribute('minlength'));
	maxLength=parseInt(field.getAttribute('maxLength'));
	if (maxLength==0)
	  maxLength=parseInt(field.getAttribute('maxlength'));
	
  
 	if ((!isNaN(minLength)) && (minLength!=0) && (field.value.length<minLength)) {
	  errors+="- " + name + " troppo corto, min " + minLength + " caratteri.\n";
	}
 	if ((!isNaN(maxLength)) && (maxLength!=0) && (field.value.length>maxLength)) {
	  errors+="- " + name + " troppo lungo, max " + maxLength + " caratteri.\n";
	}
	
  switch (type) {
    //eMail
    case 'email': {
			var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9])+$/;
			if (!filter.test(field.value)) errors+="- " + name + " non e\' indirizzo e-mail.\n";
    	break;}
    //Numero Intero
    case 'int': {
		
			//N.B. parseInt("1.2abc")   Returns 1.2
			var filter  = /^([0-9])+$/;
			
			if (!filter.test(field.value)) errors+="- " + name + " non e\' un numero.\n";
			
			if ((isNaN(minValue)) || (isNaN(maxValue))) break;
    		if ((field.value<minValue) || (field.value>maxValue)) errors+="- " + name + " deve essere compreso tra " + minValue + " e " + maxValue + ".\n";

			break;
	}
			/*
			//  Dava problemi con lo 0 davanti
      var valueAux=parseInt(field.value);
	  alert(valueAux)
      if (isNaN(valueAux) || (valueAux+""!=field.value)) errors+="- " + name + " non e\' un numero.\n";
    	if ((isNaN(minValue)) || (isNaN(maxValue))) break;
    	if ((field.value<minValue) || (field.value>maxValue)) errors+="- " + name + " deve essere compreso tra " + minValue + " e " + maxValue + ".\n";
    	break;}
		*/
  //Numero Reale
  
      case 'piva': {
			var filter  = /\d{11}/;
			if (!filter.test(field.value)) errors+="- " + name + " non e\' una partita iva.\n";
    	break;}

    case 'real': {
			//N.B. parseFloat("1.2abc")   Returns 1.2
      //var valueAux=parseFloat(field.value);
      //if (isNaN(valueAux) || (valueAux+""!=field.value))
			var filter  = /(^-?\d\d*\,\d*$)|(^-?\d\d*$)|(^-?\,\d\d*$)/;
			if (!filter.test(field.value)) 
			  errors+="- " + name + " non e\' un numero.\n";
			else
//				field.value=parseFloat(field.value); //parseFloat("1.2abc")   // Returns 1.2.
    	if ((isNaN(minValue)) || (isNaN(maxValue))) break;
    	if ((field.value<minValue) || (field.value>maxValue)) errors+="- " + name + " deve essere compreso tra " + minValue + " e " + maxValue + ".\n";
    	break;}
  //Data/Ora
    /*case 'datetime': {
		
		
		
    	if (isNaN(Date.parse(field.value))) errors+="- " + name + " non e\' una data.\n"; 
    	break;
	}
	case 'date': {
		
		
		
    	if (isNaN(Date.parse(field.value))) errors+="- " + name + " non e\' una data.\n"; 
    	break;
	}*/
  }


	//Mostra errori
  if (errors) 
	  alert(errors);

	//Ritorna true se tutto ok
  return (errors == '');
}


_e3Validate.prototype.validate_form = function(form)
{

  var i;
  var elem;
 
	var Operazione;
	var isValid;

//Esegue la validazione solo durante Avanti,Indietro e Salva
	elem=form.elements["Operazione"];
	if (typeof(elem)!="undefined") {
		Operazione=parseInt(elem.value);
		if (!isNaN(Operazione)) {
			if ((Operazione!=10) && (Operazione!=20) && (Operazione!=30)) 
				return true;
		}
	}
	
  //Se uguale a Avanti,Indietro o Salva valida campi			
  for (i=0;i<form.elements.length;++i) {
  	elem=form.elements[i];
		
    //Ignora campi hidden
    //    if (elem.type=="hidden") continue;
    //Valida campo
		
    isValid=_e3Validate.prototype.validate_validateField(elem);
		
    //Se il campo non e' valido imposta il focus ed esce
	
		if (!isValid) {
			if (elem.type!="hidden"){
				if (typeof(elem.focus)=="object") {
			  	try {
					elem.focus();
				}catch(e){}
				}
			}
			return false;
		}
  }
  

  return true;
}

_e3Validate.prototype.verifyForm = function(){
	var elencoForm = document.getElementsByTagName("form");
        var elencoInput = document.getElementsByTagName("input");
        
        // aggiunge l'evento ai form con l'attributo validate
	for (var i=0;i<elencoForm.length;i++){
		var frm=elencoForm[i];

		if (frm.getAttribute('validate')=="validate") {
			frm.onsubmit = function(){return _e3Validate.prototype.validate_form(this)}
                }
	}
        
        // aggiunge il calendario ai campi con l'attributo subtype="datetime"
        for (var i=0;i<elencoInput.length;i++){
                var input = elencoInput[i];
               switch(input.getAttribute("subtype")){
                case "datetime":
                         _e3Validate.prototype.isDate(input.id,true);
                break;
                
                case "date":
                        _e3Validate.prototype.isDate(input.id,false);
                break;
                
               }
               
        }
}

// Collega il calendario al campo
_e3Validate.prototype.isDate = function(id,activeTime){
	
	var elemento = document.getElementById(id);
	
	elemento.setAttribute("readonly","readonly");
	
	elemento.readOnly = true;
	
	var contenitoreCal = document.createElement("DIV");
	contenitoreCal.id=id+"[cal]";	
	contenitoreCal.setAttribute("isCalendar","true");
        
	
    elemento.className = "immagineCalendario";
        
	
	var args = new Array()
	args[0] = id;
	args[1] = contenitoreCal.id;
	args[2] = null; // mese
	args[3] = null; // anno
	args[4] = null; // giorno
	args[5] = true; // 
	args[6] = activeTime; // ora minuti

	elemento.onclick = e3Utility.Bind(e3Calendar.apriCalendario,args);
	
	elemento.parentNode.appendChild(contenitoreCal);
      
	}

var e3Validate = new _e3Validate();


// ------------ Calendario -------------------


var _e3Calendar = function(){
	this.apriCalendario = function(args){
	
		var id = args[0];
		var idCal = args[1];
		var mese_in = args[2];        
		var year_in = args[3];
		var day_in = args[4];
		var getDateField = args[5];
		var visHourMin = args[6];
		var ora_in = "";
		var minuti_in = "";
		var now = new Date();
		var field = document.getElementById(id);
		var contenitoreCal = document.getElementById(idCal);
		
		var minDate = field.getAttribute("min");
		var maxDate = field.getAttribute("max");
		
		
		if (getDateField){
			
			e3Calendar.closeAllCalendar();			
			var dateField = field.value.split("/");	
			
			if (dateField.length==3){
						   
				var yearOraMinuti = dateField[2].split(" ");
				if (mese_in==null) mese_in = dateField[1]-1;
				if (year_in==null) year_in = yearOraMinuti[0];
				if (day_in==null) day_in = dateField[0];
							
				if (yearOraMinuti.length>1){
					var oraMinuti = yearOraMinuti[1].split(".");
					ora_in = oraMinuti[0];
					minuti_in = oraMinuti[1];
					}
				
			}else{
				if (mese_in==null) mese_in = now.getMonth();
				if (year_in==null) year_in = now.getFullYear();
				if (day_in==null) day_in = now.getDate();
			}
			
			
		}else{
			if (mese_in==null) mese_in = now.getMonth();
			if (year_in==null) year_in = now.getFullYear();
			if (day_in==null) day_in = now.getDate();
		}
		
		if (getDateField && contenitoreCal.innerHTML.length>0) {
			contenitoreCal.style.display="none";
			contenitoreCal.innerHTML = "";
			return true;
			
		}else{
	   
					var x = e3Utility.getDim(field).x + field.offsetWidth;
					var y = e3Utility.getDim(field).y + field.offsetHeight - 17;
	
					
					
					contenitoreCal.style.position="absolute";
					contenitoreCal.style.left = x + "px";
					contenitoreCal.style.top = y + "px";
					
					
			contenitoreCal.style.display="block";
		}
		var day_of_week = new Array('Dom','Lun','Mar','Mer','Gio','Ven','Sab');
		var month_of_year = new Array('Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre');
		var Calendar = new Date();
		
		
		var year = year_in;	    // Returns year
		var month = mese_in;    // Returns month (0-11)
		var today = day_in;    // Returns day (1-31)
		
	
		
		var weekday = Calendar.getDay();    // Returns day (1-31)
		
		
		
		
		var DAYS_OF_WEEK = 7;    // "constant" for number of days in a week
		var DAYS_OF_MONTH = 31;    // "constant" for number of days in a month
		var cal;    // Used for printing
		
		Calendar.setYear(year)
		Calendar.setDate(1);    // Start the calendar day at '1'
		Calendar.setMonth(month);    // Start the calendar month at now
		
		var TR_start = '<TR>\n';
		var TR_end = '</TR>\n';
		var highlight_start = "<TH onClick=\"e3Calendar.setValue('"+id+"',this.innerHTML+'/"+parseInt(parseInt( month)+1)+"/"+year+"','"+contenitoreCal.id+"','"+minDate+"','"+maxDate+"')\" WIDTH=\"30\">";
		var highlight_end   = '</TH>\n';
		
		var TD_start = "<TD onClick=\"e3Calendar.setValue('"+id+"',this.innerHTML+'/"+parseInt(parseInt( month)+1)+"/"+year+"','"+contenitoreCal.id+"','"+minDate+"','"+maxDate+"')\" WIDTH=\"30\">";
		var TD_start_days = "<TD class='days'>";
		var TD_start_normal = "<TD>\n";
		var TD_end = '</TD>\n';
		
		cal =  '<div class="calendario"><iframe  src=\"about:blank\" scrolling=\"no\" frameborder=\"0\" class="\ieFix\" ></iframe><TABLE>';
		cal += '<thead><tr>';
		cal += '<th colspan="'+ DAYS_OF_WEEK +'">';
		//-10 anni <span class=\"annoDecr10\"  onclick=\"e3Calendar.goTo('anno',"+month+","+year+","+today+",'"+contenitoreCal.id+"','"+id+"',-10,"+visHourMin+")\">&laquo; -10&nbsp;&nbsp;</span>
		//+10 anni </span><span class=\"annoIncr10\" onclick=\"e3Calendar.goTo('anno',"+month+","+year+","+today+",'"+contenitoreCal.id+"','"+id+"',+10,"+visHourMin+")\">&nbsp;&nbsp;+10 &raquo;</span>
		cal += "<div class=\"nav_anno\"><span class=\"annoDecr1\"  onclick=\"e3Calendar.goTo('anno',"+month+","+year+","+today+",'"+contenitoreCal.id+"','"+id+"',-1,"+visHourMin+")\">< -1</span><strong>" + year + "</strong><span class=\"annoIncr1\" onclick=\"e3Calendar.goTo('anno',"+month+","+year+","+today+",'"+contenitoreCal.id+"','"+id+"',+1,"+visHourMin+")\">+1 ></div>" ;
		cal += "<div class=\"nav_mese\"><span onclick=\"e3Calendar.goTo('mese',"+month+","+year+","+today+",'"+contenitoreCal.id+"','"+id+"',-1,"+visHourMin+")\"><</span><strong>" + month_of_year[month]  + "</strong><span onclick=\"e3Calendar.goTo('mese',"+month+","+year+","+today+",'"+contenitoreCal.id+"','"+id+"',+1,"+visHourMin+")\">></span></div>"
		cal += '</th>';
		cal += '</tr></thead>';
		cal += '<tbody><tr>'
		
		// LOOPS FOR EACH DAY OF WEEK
		for(index=0; index < DAYS_OF_WEEK; index++)
		{
		
			// BOLD TODAY'S DAY OF WEEK
			cal += TD_start_days + day_of_week[index] + TD_end;
		}
		
		cal += TR_end;
		cal += TR_start;
		
		// FILL IN BLANK GAPS UNTIL TODAY'S DAY
		for(index=0; index < Calendar.getDay(); index++)
	
		cal += TD_start_normal + '  ' + TD_end;
		
		// LOOPS FOR EACH DAY IN CALENDAR
		for(index=0; index < DAYS_OF_MONTH; index++)
		{
			if( Calendar.getDate() > index )
			{
			  // RETURNS THE NEXT DAY TO PRINT
			  week_day =Calendar.getDay();
			
			  // START NEW ROW FOR FIRST DAY OF WEEK
			  if(week_day == 0)
			  cal += TR_start;
			
			  if(week_day != DAYS_OF_WEEK)
			  {
			
			  // SET VARIABLE INSIDE LOOP FOR INCREMENTING PURPOSES
			  var day  = Calendar.getDate();
			
			  // HIGHLIGHT TODAY'S DATE
			  if( today==Calendar.getDate() )
			  cal += highlight_start + day + highlight_end ;
			
			  // PRINTS DAY
			  else
				
				  cal += TD_start + day + TD_end;
				
			  }
			
			  // END ROW FOR LAST DAY OF WEEK
			  if(week_day == (DAYS_OF_WEEK-1))
			  cal += TR_end;
		  }
		
		  // INCREMENTS UNTIL END OF THE MONTH
		  Calendar.setDate(Calendar.getDate()+1);
		
		}// end for loop
	
	// ----------------- inserimento ora / minuti --------------------
	if (visHourMin){
		 cal += TR_end;
		cal += TR_start
		cal += "<td colspan=\""+DAYS_OF_WEEK+"\">ora: "+e3Calendar.getHour(id+"_ora",ora_in)+":"+e3Calendar.getMinute(id+"_minuti",minuti_in)+" <span onClick=\"e3Calendar.setValue('"+id+"','"+day+"/"+(parseInt( month)+1)+"/"+year+"','"+contenitoreCal.id+"','"+minDate+"','"+maxDate+"')\">INSERISCI</span></td>"
		cal += TR_end
	}
	
	// --------------------------------------------------------------
		
	
		cal += '</tbody>';
		cal +=	"<tfoot><tr><td colspan=\""+DAYS_OF_WEEK+"\"><span onClick=\"e3Calendar.setValue('"+id+"','','"+contenitoreCal.id+"')\">Nessun valore</span></td></tr></tfoot>"
		cal += '</TABLE></div>';
		
		
		contenitoreCal.innerHTML = cal;
		//var test = window.open();
		//test.document.write(cal);
		
		
	};
	this.getHour = function(id,value){
		value = value.toInt();
		var contentObj = document.createElement("div");	
		var selectObj = document.createElement("select");
		selectObj.id=id;
		
		var optionObj = document.createElement("option");
		optionObj.innerHTML = "";
		optionObj.value = "";
		selectObj.appendChild(optionObj);
		
		for (var i=0;i<24;i++){
			var optionObj = document.createElement("option");
			var valueTmp = i.toString();
			if (valueTmp.length<2) valueTmp="0"+valueTmp;
			if (i==value) optionObj.setAttribute("selected","selected");
			optionObj.innerHTML = valueTmp;
			optionObj.value = valueTmp;
			selectObj.appendChild(optionObj);
		}
		contentObj.appendChild(selectObj);
		return contentObj.innerHTML;
	};
	
	this.getMinute = function(id,value){
		value = value.toInt();
		var contentObj = document.createElement("div");	
		var selectObj = document.createElement("select");
		selectObj.id=id;
		
		var optionObj = document.createElement("option");
		optionObj.innerHTML = "";
		optionObj.value = "";
		selectObj.appendChild(optionObj);
		
		for (var i=0;i<60;i++){
			var optionObj = document.createElement("option");
			var valueTmp = i.toString();
			if (valueTmp.length<2) valueTmp="0"+valueTmp;
			if (i==value) optionObj.setAttribute("selected","selected");
			optionObj.innerHTML = valueTmp;
			optionObj.value = valueTmp;
			selectObj.appendChild(optionObj);
		}
		contentObj.appendChild(selectObj);
		return contentObj.innerHTML;
	};
	
	this.setValue = function(id,value,idCal,minDate,maxDate){
		var valueUTC = 0;
		if (value.length>0){
			var ora = document.getElementById(id+"_ora");
			var minuti = document.getElementById(id+"_minuti");
			var oraMinuti = "";
			
			if (ora&&minuti){
				if (ora.value.length>0){
					if (ora.value.isNumeric() && minuti.value.isNumeric()){
	
						if (minuti.value.length==0) minuti.value="00";
						if (minuti.value.length==1) minuti.value="0"+minuti.value;
						if (ora.value.length==1) ora.value="0"+ora.value;
						
						if (parseInt(ora.value)>=24) ora.value = "00";
						if (parseInt(minuti.value)>59) minuti.value = "00";
						
						oraMinuti = " " + ora.value + "." + minuti.value;
					}
					
				}
			}
			
			var VerValue = value.split("/");
			
			
			if (VerValue[0].length<2) VerValue[0]="0"+VerValue[0];
			if (VerValue[1].length<2) VerValue[1]="0"+VerValue[1];
			
			value = VerValue[0] + "/" + VerValue[1] + "/" + VerValue[2] + oraMinuti;
			valueUTC = Date.UTC(VerValue[2],VerValue[1],VerValue[0]);
		}
		
		var minDateUTC = null;
		var maxDateUTC = null;
		if (minDate&&maxDate){
			var minDateArray = minDate.split("/");
			var maxDateArray = maxDate.split("/");
		
			minDateUTC = Date.UTC(minDateArray[2],minDateArray[1],minDateArray[0]);
			maxDateUTC = Date.UTC(maxDateArray[2],maxDateArray[1],maxDateArray[0]);
		}
		
		var isValid = true
		
		if (valueUTC<minDateUTC){
			alert("Attenzione\nNon è possibile inerire date inferiori al "+minDate)	;
			isValid = false;
		}
		if (valueUTC>maxDateUTC){
			alert("Attenzione\nNon è possibile inerire date superiori al "+maxDate)	;
			isValid = false;
		}
		
		if (isValid){
			var field = document.getElementById(id);
			field.value = value;
			var cal = document.getElementById(idCal);
			cal.innerHTML = "";
			cal.style.display="none";
			if (field.onchange) field.onchange();
			
		}

	

	};
	this.goTo = function(tipo,month,year,day,idCal,id,dir,visOraMinuti){
		var args = new Array();
		args[0] = id;
		args[1] = idCal;
	
		if (tipo=="mese"){
			args[2] = month + dir;
			
			args[3] = year;
		}else{
			
			args[2] = month;	
			args[3] = year + dir;
		}
		
		if (args[2]>11) {
			args[2]=0;
			args[3]++;
		}
		if (args[2]<0) {
			args[2]=11;
			args[3]--;
		}
		
		args[4] = day;
		args[5] = false;
		args[6] = visOraMinuti;
		e3Calendar.apriCalendario(args);
	};
	
	this.closeAllCalendar = function(){
		var elencoCalendari = document.getElementsByTagName("DIV");
	
		for (var i=0;i<elencoCalendari.length;i++){
			var calendario=elencoCalendari[i];
			if (calendario.getAttribute("isCalendar")=="true") {
				calendario.style.display = "none";
				}
	
		};
		
	};
};
var e3Calendar = new _e3Calendar();




e3Utility.addEvent(window,"load",e3Validate.verifyForm);




// ________________________________________ validazione campi form fine

