// JavaScript Document

function Trim(stringa) {
var stringa = stringa+''; //converto in stringa
return stringa.replace(/\s+$|^\s+/g,"");
}

function verifica_data (gg,mm,aa) {
   var strdata = gg+"/"+mm+"/"+aa;
   data = new Date(aa,mm-1,gg);
   daa=data.getFullYear().toString();
   dmm=(data.getMonth()+1).toString();
      dmm=dmm.length==1?"0"+dmm:dmm
   dgg=data.getDate().toString();
      dgg=dgg.length==1?"0"+dgg:dgg
   dddata=dgg+"/"+dmm+"/"+daa
   if (dddata!=strdata) return false;
	else return true;
}
function verifica_data2 (strdata) {
   var arrdata = strdata.split("/");
   var gg = arrdata[0];
   var mm = arrdata[1];
   var aa = arrdata[2];
   return verifica_data (gg,mm,aa);
}

function checkEmail(email)
{
  var goodEmail = email.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi);
  if (goodEmail) good = true;
  else good = false;
  
  if (Trim(email) == "") good = true;
  return good;
}



function ShowAndHide(id1,id2){
if(document.getElementById){
el1=document.getElementById(id1);
el2=document.getElementById(id2);
if(el1.style.display=="none"){
 el1.style.display="block";
 el2.style.display="none";
 document.formcerca.tipo_ric.value = "semplice";
}
else{
 el1.style.display="none";
 el2.style.display="block";
 document.formcerca.tipo_ric.value = "avanzata";
}
}
}

function ShowAndHide_lite(id1,id2){
if(document.getElementById){
el1=document.getElementById(id1);
el2=document.getElementById(id2);
if(el1.style.display=="none"){
 el1.style.display="block";
 el2.style.display="none";
}
else{
 el1.style.display="none";
 el2.style.display="block";
}
}
}


function addCommas(nStr)
{
	var my_comma = ".";//","
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + my_comma + '$2');
	}
	return x1 + x2;
}


function apri_chiudi_div(div_id) {
 var apri_chiudi = "";
 var mydiv = document.getElementById(div_id);
 if (mydiv.style.display=="none") {
	 apri_chiudi = "block";
 } else {
	 apri_chiudi = "none";
 }
 document.getElementById(div_id).style.display=apri_chiudi;
}

function swappa_ico (id_ico, nomebase) {
	var myico = document.getElementById(id_ico);
	var oldsrc = myico.src
	var img = oldsrc.split("/");
	img = img[img.length-1];
	//img = img.lastIndexOf(".");
	
	var nome = img.substring(0, img.lastIndexOf("."));
	var ext = img.substring(img.lastIndexOf("."));
	
	var oldfilename = nome+ext;

	if (nome==nomebase) nome = nome+"2";
	else nome = nome.substring(0, nome.length-1);
	
	var newfilename = nome+ext;
	
	var newsrc = oldsrc.replace(oldfilename, newfilename);
	
	myico.src = newsrc;
}


function Show_ril(id1){

var quante_rilevazioni = document.getElementById('quante_rilevazioni').value;

if(document.getElementById){
	el1=document.getElementById(id1);
	for (c=0;c<quante_rilevazioni;c=c+1) {
	 var myid1 = "rilevazione_n"+c+"_1";
	 var myid2 = "rilevazione_n"+c+"_2";
	 myel1 = document.getElementById(myid1);
	 myel2 = document.getElementById(myid2);
	 if (myid1 == id1) {
	  myel1.style.display="none";
	  myel2.style.display="block";
	 } else {
	  myel1.style.display="block";
	  myel2.style.display="none";
	 }
	}
}

}



function Hide_ril(id1, id2){
if(document.getElementById){
el1=document.getElementById(id1);
el2=document.getElementById(id2);
el1.style.display="block";
el2.style.display="none";
}
}





function smfFooterHighlight(element, value)
{
element.src = 'images' + "/" + (value ? "h_" : "") + element.id + ".gif";
}
   // Original JavaScript code by Duncan Crombie: dcrombie@chirp.com.au
   // Please acknowledge use of this code by including this header.

   // CONSTANTS
  var separator = ",";  // use comma as 000's separator
  var decpoint = ".";  // use period as decimal point
  var percent = "%";
  var currency = "$";  // use dollar sign for currency

  function formatNumber(number, format, print) {  // use: formatNumber(number, "format")
  
    number = number.replace (/,/g, '.');
  
    if (print) document.write("formatNumber(" + number + ", \"" + format + "\")<br />");

    if (number - 0 != number) {
		if (format=="0") return "0";
		else return "00.00";//null;  // if number is NaN return null
	}
    var useSeparator = format.indexOf(separator) != -1;  // use separators in number
    var usePercent = format.indexOf(percent) != -1;  // convert output to percentage
    var useCurrency = format.indexOf(currency) != -1;  // use currency format
    var isNegative = (number < 0);
    number = Math.abs (number);
    if (usePercent) number *= 100;
    format = strip(format, separator + percent + currency);  // remove key characters
    number = "" + number;  // convert number input to string

     // split input value into LHS and RHS using decpoint as divider
    var dec = number.indexOf(decpoint) != -1;
    var nleftEnd = (dec) ? number.substring(0, number.indexOf(".")) : number;
    var nrightEnd = (dec) ? number.substring(number.indexOf(".") + 1) : "";

     // split format string into LHS and RHS using decpoint as divider
    dec = format.indexOf(decpoint) != -1;
    var sleftEnd = (dec) ? format.substring(0, format.indexOf(".")) : format;
    var srightEnd = (dec) ? format.substring(format.indexOf(".") + 1) : "";

     // adjust decimal places by cropping or adding zeros to LHS of number
    if (srightEnd.length < nrightEnd.length) {
      var nextChar = nrightEnd.charAt(srightEnd.length) - 0;
      nrightEnd = nrightEnd.substring(0, srightEnd.length);
      if (nextChar >= 5) nrightEnd = "" + ((nrightEnd - 0) + 1);  // round up

 // patch provided by Patti Marcoux 1999/08/06
      while (srightEnd.length > nrightEnd.length) {
        nrightEnd = "0" + nrightEnd;
      }

      if (srightEnd.length < nrightEnd.length) {
        nrightEnd = nrightEnd.substring(1);
        nleftEnd = (nleftEnd - 0) + 1;
      }
    } else {
      for (var i=nrightEnd.length; srightEnd.length > nrightEnd.length; i++) {
        if (srightEnd.charAt(i) == "0") nrightEnd += "0";  // append zero to RHS of number
        else break;
      }
    }

     // adjust leading zeros
    sleftEnd = strip(sleftEnd, "#");  // remove hashes from LHS of format
    while (sleftEnd.length > nleftEnd.length) {
      nleftEnd = "0" + nleftEnd;  // prepend zero to LHS of number
    }

    if (useSeparator) nleftEnd = separate(nleftEnd, separator);  // add separator
    var output = nleftEnd + ((nrightEnd != "") ? "." + nrightEnd : "");  // combine parts
    output = ((useCurrency) ? currency : "") + output + ((usePercent) ? percent : "");
    if (isNegative) {
      // patch suggested by Tom Denn 25/4/2001
      output = (useCurrency) ? "(" + output + ")" : "-" + output;
    }
    return output;
  }

  function strip(input, chars) {  // strip all characters in 'chars' from input
    var output = "";  // initialise output string
    for (var i=0; i < input.length; i++)
      if (chars.indexOf(input.charAt(i)) == -1)
        output += input.charAt(i);
    return output;
  }

  function separate(input, separator) {  // format input using 'separator' to mark 000's
    input = "" + input;
    var output = "";  // initialise output string
    for (var i=0; i < input.length; i++) {
      if (i != 0 && (input.length - i) % 3 == 0) output += separator;
      output += input.charAt(i);
    }
    return output;
  }





// Funzione per l'accesso automatico tramite EasySat (riceve i parametri, avvalora i campi per il logine  invia la form.
function accesso_SAT (SAT_userid) {

 var arr = new Array();
 var arr = SAT_userid.split("@", 2);

 document.form_login.userid.value=arr[0];
 document.form_login.password.value=arr[1];
 document.form_login.crypt.value="1";
 var x = document.getElementById("form_login");
 x.submit();
}


function conferma_privacy () {

	 
 if (document.form_conferma_privacy.confprivacy[0].checked == true) x = document.getElementById("form_conferma_privacy");
 else if (document.form_conferma_privacy.confprivacy[1].checked == true) x = document.getElementById("form_no_privacy");
 else return false;
 
 x.submit();
 
 
}



function intervd_indietro(stato) {

 conf = true;
 if (stato != "I") conf = window.confirm('Tutti i dati non salvati andranno persi, continuare?');
 
 if (conf) window.location = ('intervt.php');

}



function controlla_contatoreX (acv, datconta, cx, codx, X) {


//converto il formato della data: da gg/mm/aaaa a mm/gg/aaaa
var datint = document.form1.datint.value.substring(3,5) + "/" + document.form1.datint.value.substring(0,2) + "/" + document.form1.datint.value.substring(6,10);
var datconta_ita = datconta;
var datconta = datconta.substring(3,5) + "/" + datconta.substring(0,2) + "/" + datconta.substring(6,10);
var matricola = document.getElementById("matricola").value;

var d1 = new Date(datint);
var d2 = new Date(datconta);

/*alert(d1+"\n"+d2);
return false;*/

var myril = document.getElementById("rilcont"+X).value;

 if (Trim(myril) != "" && codx != '' && cx > -1) {

 if (isNaN(myril) || myril < 0) {
	alert("Inserire un numero intero positivo per il contatore "+X);
	return false;
 } else {

 if (myril < cx) {
	return window.confirm ("La Rilevazione del contatore "+X+" è inferiore a quella precedente, continuare?");
 } else {

	if (acv > 0) {
		var datdif = Math.round((d1.getTime() - d2.getTime())/86400000);
		var n_copie= (datdif*acv/30);
		if (n_copie > 0) {
			var minimo = Math.round(cx + (n_copie/2));
			var massimo = Math.round(cx + (n_copie * 3/2));

				if (myril > massimo || myril < minimo) {
					//alert("Inserire correttamente le rilevazioni (min "+minimo+", max "+massimo+")");
							
							
					return window.confirm (print_err_conta("Contatore "+X, myril, minimo, massimo, matricola, datconta_ita));
				}		
		}
	
	} // Chiuso if (acv)
 }// Chiuso if (rile < cont_prec)
 } // chiuso if (isNaN)
 } // Chiuso if (cod1)

}




function controlla_email (myemail) {
var contr1 = myemail.indexOf('@');
var contr2 = myemail.indexOf('.');
 if (contr1 == -1 || contr2 == -1) {
	alert('Inserire un indirizzo Email valido');
	return false;
 } else return true;
}





function controlla (c1, c2, c3, c4, c5, cod1, cod2, cod3, cod4, cod5, acv, datconta, datadocumento, orains, inviaemailintervento) {

var conf = true;
var js_check_difcauaz = document.getElementById("js_check_difcauaz").value;

if (js_check_difcauaz==1) {
//DIF/CAU/AZ
if (conf != false) {
dif_sel1 = z_dif1.getSelectedText();
dif_vis1 = z_dif1.getComboText();
if (Trim(dif_vis1) == "")  document.form1.difetto1.value = "";
else if (dif_sel1 != dif_vis1) {
	alert ("Difetto/Causa/Azione: Il difetto n.1 non è selezionato correttamente.\nSi prega di effettuare nuovamente la selezione");
	conf = false;
}
}
if (conf != false) {
cau_sel1 = z_cau1.getSelectedText();
cau_vis1 = z_cau1.getComboText();
if (Trim(cau_vis1) == "")  document.form1.causa1.value = "";
else if (cau_sel1 != cau_vis1) {
	alert ("Difetto/Causa/Azione: La causa n.1 non è selezionata correttamente.\nSi prega di effettuare nuovamente la selezione");
	conf = false;
}
}
if (conf != false) {
int_sel1 = z_int1.getSelectedText();
int_vis1 = z_int1.getComboText();
if (Trim(int_vis1) == "")  document.form1.azione1.value = "";
else if (int_sel1 != int_vis1) {
	alert ("Difetto/Causa/Azione: L'azione n.1 non è selezionata correttamente.\nSi prega di effettuare nuovamente la selezione");
	conf = false;
}
}


if (conf != false) {
dif_sel2 = z_dif2.getSelectedText();
dif_vis2 = z_dif2.getComboText();
if (Trim(dif_vis2) == "")  document.form1.difetto2.value = "";
else if (dif_sel2 != dif_vis2) {
	alert ("Difetto/Causa/Azione: Il difetto n.2 non è selezionato correttamente.\nSi prega di effettuare nuovamente la selezione");
	conf = false;
}
}
if (conf != false) {
cau_sel2 = z_cau2.getSelectedText();
cau_vis2 = z_cau2.getComboText();
if (Trim(cau_vis2) == "")  document.form1.causa2.value = "";
else if (cau_sel2 != cau_vis2) {
	alert ("Difetto/Causa/Azione: La causa n.2 non è selezionata correttamente.\nSi prega di effettuare nuovamente la selezione");
	conf = false;
}
}
if (conf != false) {
int_sel2 = z_int2.getSelectedText();
int_vis2 = z_int2.getComboText();
if (Trim(int_vis2) == "")  document.form1.azione2.value = "";
else if (int_sel2 != int_vis2) {
	alert ("Difetto/Causa/Azione: L'azione n.2 non è selezionata correttamente.\nSi prega di effettuare nuovamente la selezione");
	conf = false;
}
}


if (conf != false) {
dif_sel3 = z_dif3.getSelectedText();
dif_vis3 = z_dif3.getComboText();
if (Trim(dif_vis3) == "")  document.form1.difetto3.value = "";
else if (dif_sel3 != dif_vis3) {
	alert ("Difetto/Causa/Azione: Il difetto n.3 non è selezionato correttamente.\nSi prega di effettuare nuovamente la selezione");
	conf = false;
}
}
if (conf != false) {
cau_sel3 = z_cau3.getSelectedText();
cau_vis3 = z_cau3.getComboText();
if (Trim(cau_vis3) == "")  document.form1.causa3.value = "";
else if (cau_sel3 != cau_vis3) {
	alert ("Difetto/Causa/Azione: La causa n.3 non è selezionata correttamente.\nSi prega di effettuare nuovamente la selezione");
	conf = false;
}
}
if (conf != false) {
int_sel3 = z_int3.getSelectedText();
int_vis3 = z_int3.getComboText();
if (Trim(int_vis3) == "")  document.form1.azione3.value = "";
else if (int_sel3 != int_vis3) {
	alert ("Difetto/Causa/Azione: L'azione n.3 non è selezionata correttamente.\nSi prega di effettuare nuovamente la selezione");
	conf = false;
}
}

} // if (js_check_difcauaz==1) {
	
	
	
// DATA 
if (document.form1.datint.value != '') {


if (verifica_data(document.form1.datint.value.substring(0,2), document.form1.datint.value.substring(3,5), document.form1.datint.value.substring(6,10)) === false) {
	alert ("Data intervento non valida");
	document.form1.datint.focus();
	conf = false;
} else {
//verifico che la chiusura dell'intervento (datint) non sia precedente alla data del documento stesso
var mydatint = document.form1.datint.value.substring(3,5) + "/" + document.form1.datint.value.substring(0,2) + "/" + document.form1.datint.value.substring(6,10);
//alert("DatDoc: "+Date(datadocumento)+"\nDat chius: "+Date(mydatint));
mydatint = new Date(mydatint);
mydatadocumento = new Date(datadocumento);
mydatdif = Math.round((mydatint.getTime() - mydatadocumento.getTime())/86400000);

myorarioint = document.form1.orainih.value*60+document.form1.orainim.value*1;
//alert("Ora doc: "+orains+"\nOra int: "+myorarioint);

if (mydatdif < 0 || (mydatdif == 0 && orains > myorarioint)) {
	alert ("La data/ora di chiusura intervento non può essere inferiore alla data/ora del documento");
	document.form1.datint.focus();
	conf = false;	
}



}




} else {
   alert("Inserire Data dell\' Intervento");
   document.form1.datint.focus();
   conf = false;
}


// Verifico il range dei contatori

var flvisualizzacont = document.form1.flvisualizzacont.value;
if (flvisualizzacont == "1") {


//Verifico che siano stati inseriti tutti i contatori
if (conf != false && (
(cod1 != '' && Trim(document.form1.rilcont1.value) == "") ||
(cod2 != '' && Trim(document.form1.rilcont2.value) == "") ||
(cod3 != '' && Trim(document.form1.rilcont3.value) == "") ||
(cod4 != '' && Trim(document.form1.rilcont4.value) == "") ||
(cod5 != '' && Trim(document.form1.rilcont5.value) == "")
)
) conf = window.confirm("Non hai inserito tutte le rilevazioni, continuare?");
if (!conf) return false;

var acv2 = document.form1.ACV2.value;
var acv3 = document.form1.ACV3.value;
var acv4 = document.form1.ACV4.value;
var acv5 = document.form1.ACV5.value;

//if (conf != false) conf = controlla_contatore1 (acv , datconta, c1, cod1);
if (conf != false && cod1 != '') conf = controlla_contatoreX (acv , datconta, c1, cod1, 1);
if (conf != false && cod2 != '') conf = controlla_contatoreX (acv2 , datconta, c2, cod2, 2);
if (conf != false && cod3 != '') conf = controlla_contatoreX (acv3 , datconta, c3, cod3, 3);
if (conf != false && cod4 != '') conf = controlla_contatoreX (acv4 , datconta, c4, cod4, 4);
if (conf != false && cod5 != '') conf = controlla_contatoreX (acv5 , datconta, c5, cod5, 5);

}

///////////////////////////
///////////////////////////
///////////////////////////


var orario_di_inizio_intervento = parseFloat((document.form1.orainih.value * 60)) + parseFloat(document.form1.orainim.value);
var orario_di_fine_intervento = parseFloat((document.form1.orafinh.value * 60)) + parseFloat( document.form1.orafinm.value);



//Controllo che DATINT sia uguale o superiore a DATDOC
//Controllo durata intervento
	if (conf != false) {
		var dataintervento = document.form1.datint.value.substring(3,5) + "/" + document.form1.datint.value.substring(0,2) + "/" + document.form1.datint.value.substring(6,10);
		var data1 = new Date(dataintervento);
		var data2 = new Date(datadocumento);
		
//alert ("1: "+data1+"\n2: "+data2);
		
		var datdif = Math.round((data1.getTime() - data2.getTime())/86400000);
		if (datdif == 0) { //se il giorno di chiusura int. è = al giorno di inserimento chiamata controllo che l'orario di inizio intervento non sia inferiore all'ora di ins.chiam.
			
			if (orario_di_inizio_intervento - orains < 0 || isNaN(orario_di_inizio_intervento)) {
				alert ("L\'orario di inizio intervento non può essere inferiore all\'orario di inserimento della chiamata");
				conf = false;
			}
		} else {
			if (datdif < 0) {
			alert("La data di chiusura intervento e\' inferiore alla data della chiamata");
			conf = false;
			}
		}
		
	}



var ore_lavorate = parseFloat((document.form1.orelavh.value * 60)) + parseFloat(document.form1.orelavm.value);
var mydifforelav = (orario_di_fine_intervento-orario_di_inizio_intervento);

// se si specifica oraini e orafin controllo che orelav non superi la differenza fra orafin e oraini
if (conf != false) {
 if (mydifforelav > 0 && orario_di_inizio_intervento > 0 && orario_di_fine_intervento > 0 && ore_lavorate > mydifforelav) {
	alert("La durata dell'intervento non può essere maggiore della differenza fra l'orario di fine e inizio intervento");
	conf = false;
 }
}





// controllo che oraini non sia minore di orafin
if (conf != false) {
 if (orario_di_inizio_intervento >= orario_di_fine_intervento) {
	conf = window.confirm("L\'orario di inizio intervento e\' maggiore o uguale all\'orario di chiusura intervento\nContinuare?");
 }
}



//Controllo durata intervento
if (conf != false) {
	if (!isNaN(document.form1.orelavh.value) && !isNaN(document.form1.orelavm.value)) {
	if (parseFloat(document.form1.orelavh.value) == 0 && parseFloat(document.form1.orelavm.value) == 0) conf = window.confirm("Durata intervento uguale a zero! Continuare?");
	} else {
	alert("Durata intervento errata");
	conf = false;
	}	
}


//Chiedo l'invio dell'email dell'intervento tecnico, se necessario (cioè se il cliente è fuori contratto)
if (conf != false) {
var emailintervento = "";
if (document.form1.tipo_invio.value != "registra" && inviaemailintervento == 1) {
// Occorre inviare l'email dell'intervento al cliente perché è senza contratto
	var emailintervento = "";
	while (emailintervento == "") {
	 var email_int = document.form1.email_int.value;
	 emailintervento = window.prompt ("Il cliente è senza contratto. Specificare l'indirizzo email del cliente\na cui inviare l'intervento. Premere Annulla per non inviare l'email", email_int);
	 if (controlla_email(emailintervento) == false) emailintervento = "";
	}
if (emailintervento !== null) document.form1.emailintervento.value = emailintervento;
}
}


return conf;

}







// *************
// **  ORARI  **
// *************
// Calcola la differenza fra l'orario di inizio e di fine intervento
function diffHours() { 

	var H_ini = parseFloat(document.form1.orainih.value);
	var M_ini = parseFloat(document.form1.orainim.value);
	if (isNaN(H_ini) || H_ini == '' || H_ini > 23) H_ini = 0; 
	if (isNaN(M_ini) || M_ini == '' || M_ini > 59) M_ini = 0; 

	var H_fin = parseFloat(document.form1.orafinh.value);
	var M_fin = parseFloat(document.form1.orafinm.value);
	if (isNaN(H_fin) || H_fin == '' || H_fin > 23) H_fin = 0; 
	if (isNaN(M_fin) || M_fin == '' || M_fin > 59) M_fin = 0; 

//770

	var INIZIO = H_ini*60+M_ini;
	var FINE = H_fin*60+M_fin;

	var diff = FINE - INIZIO;
	//alert("DIFF: "+FINE+" - "+INIZIO+" = "+diff);

	var H = parseInt(diff/60);
	var M = parseInt(diff % 60);

	//alert("H = "+H+", M = "+M);

	if (H < 0 || isNaN(H)) H = 0; 
	if (M < 0 || isNaN(M)) M = 0; 

	document.form1.orelavh.value = H;
	document.form1.orelavm.value = M;


calcimporti(); // calcimporti() chiama totali(), totali() chiama mettizero()

}





















////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////


function calc (nTotMinuti, nPrz_Ora, nMin_MinFat, nArr) {

	if (nMin_MinFat==0) {
		var nDiv1 = 0;
	} else {
		var nDiv1 = 60/nMin_MinFat;
	}
	if (nMin_MinFat==0) {
		var nDiv2 = 0;
	} else {
		var nDiv2 = nTotMinuti/nMin_MinFat;
	}

   var nParti_Ora  = parseInt(nDiv1);
   var nParti      = parseInt(nDiv2);
   var nMinuti     = nParti * nMin_MinFat;

   if (nMin_MinFat != 0 && nTotMinuti % nMin_MinFat != 0) nMinuti = parseFloat(nMinuti) + parseFloat(nMin_MinFat);

	//alert("nPrz_Ora: "+nPrz_Ora+", nMinuti: "+nMinuti);
	return dfRound(nPrz_Ora * nMinuti / 60, nArr);

}


function dfRound( nNumber, nRound ) {

var nDiv, nDifSup, nDifInf, nRet;

nDiv = parseInt(nNumber/nRound);

nDifInf = nNumber - nDiv * nRound;
nDifSup = nRound  - nDifInf;

nRet = nDiv * nRound;

if (nDifSup < nDifInf) nRet += nRound;

return nRet;

}

function IntVal (num) {
	var mynum = parseInt(num);
	if (isNaN(mynum)) return 0;
	else return mynum;
}

////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////


function calcKM(nKm_Viag, nKm_Imp, nKm_MinFat, nArr)  {//

	if (nKm_MinFat==0) {
		var nDiv1 = 0;
		} else { 
		var nDiv1 = nKm_Viag/nKm_MinFat; 
		}

   var nPart = parseInt(nDiv1);            // d.g.
	if (isNaN(nPart)) nPart = 0;
   var nKm   = nPart*nKm_MinFat;

   if (nKm_MinFat != 0 && nKm_Viag % nKm_MinFat != 0) {
      nKm = nKm + nKm_MinFat  ;          // aggiungi minimo fatt.
   }

return dfRound(nKm_Imp * nKm, nArr);                

}


////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

function calcimporti () {
	
	
IVA			= document.form1.ivaint.value;

FLMANOPE	= document.form1.FLMANOPE.value;
FLTRASFE	= document.form1.FLTRASFE.value;
DC_TC		= document.form1.DC_TC.value;
SC1_DUR		= document.form1.SC1_DUR.value;
SC1_IMP		= document.form1.SC1_IMP.value;
SC1_MINFAT	= document.form1.SC1_MINFAT.value;
SC2_DUR		= document.form1.SC2_DUR.value;
SC2_IMP		= document.form1.SC2_IMP.value;
SC2_MINFAT	= document.form1.SC2_MINFAT.value;
SCO_IMP		= document.form1.SCO_IMP.value;
SCO_MINFAT	= document.form1.SCO_MINFAT.value;
VI_IMP		= document.form1.VI_IMP.value;
VI_MINFAT	= document.form1.VI_MINFAT.value;
KM_IMP		= document.form1.KM_IMP.value;
KM_MINFAT	= document.form1.KM_MINFAT.value;


   var aSca     = new Array();
   var nInd     = 0;
   var nArr     = 0.01; //IIF(S2EVBase()==EURO_VAL_EURO, .01, 100)
   var nFisso   = 0;
   var nManope  = 0;
   var nTrasfe  = 0;

	var KMVIAG = document.form1.kmviag.value;
	if (KMVIAG == '' || isNaN(KMVIAG)) KMVIAG = 0;

	var orelavh = parseFloat(document.form1.orelavh.value);
	var orelavm = parseFloat(document.form1.orelavm.value);
	if (isNaN(orelavh) || orelavh > 23) orelavh = 0; 
	if (isNaN(orelavm) || orelavm > 59) orelavm = 0; 

	var oraviagh = parseFloat(document.form1.oraviagh.value);
	var oraviagm = parseFloat(document.form1.oraviagm.value);
	if (isNaN(oraviagh) || oraviagh > 23) oraviagh = 0; 
	if (isNaN(oraviagm) || oraviagm > 59) oraviagm = 0; 


   var nMinMan  = parseInt(orelavh*60+orelavm); // tempo lavorato in minuti
   var nMinTra  = parseInt(oraviagh*60+oraviagm); // tempo trasporto (Viaggio) in minuti

	if (isNaN(nMinMan) || nMinMan < 0) nMinMan = 0;
	if (isNaN(nMinTra) || nMinTra < 0) nMinTra = 0;
	
	// sottraggo DC_TC (se è maggiore di 0)
	if (parseInt(nMinMan)>0 && parseInt(DC_TC)>0) {
		nMinMan = parseInt(parseInt(nMinMan) - parseInt(DC_TC));
		if (nMinMan<0) nMinMan = 0;
	}

	//alert("MinMan: "+nMinMan+", MinTra: "+nMinTra);
	
     if (FLMANOPE == 'S') { //&& nMinMan > 0

			var aSca = Array (
			  Array(SC1_DUR, SC1_IMP,SC1_MINFAT),
			  Array(SC2_DUR, SC2_IMP,SC2_MINFAT),
			  Array(0, SCO_IMP,SCO_MINFAT)
			)

            for (nInd=0; nInd < (aSca.length-1) && nMinMan > aSca[nInd][0];nInd++) {
               nMinMan = nMinMan - aSca[nInd][0];
               res_funz_calc = calc(aSca[nInd][0], aSca[nInd][1], aSca[nInd][2], nArr);
			   nManope = nManope + res_funz_calc;
            }
			
			res_funz_calc2 = calc(nMinMan, aSca[nInd][1], aSca[nInd][2], nArr);
            nManope = nManope + res_funz_calc2;
	  document.form1.tot_manodopera.value = Math.round(nManope*100)/100;
      }

//923

/////// CALCOLO COSTO DELLA TRASFERTA
      if (FLTRASFE == 'S') {
         if (nMinTra > 0) {
			variabile1 = calc(nMinTra, VI_IMP, VI_MINFAT, nArr);
            nTrasfe = nTrasfe + variabile1;
         }
         if (KMVIAG > 0) {
			variabile2 = calcKM(KMVIAG, KM_IMP, KM_MINFAT, nArr);
            nTrasfe = nTrasfe + variabile2;  
         }
	  document.form1.tot_trasferta.value = Math.round(nTrasfe*100)/100;                        
      }


// Chiamo la funzione che calcola i totali
totali (IVA);


}





function format_ora (h) {
	
myvar = h.replace ('.', '');

if (Trim(myvar) != "") {

if (isNaN(parseFloat(myvar)) || parseFloat(myvar) > 23 || parseFloat(myvar) < 0) myvar = "00";
else myvar = formatNumber(myvar, '00');

}


return myvar;

}

function format_min (m) {
	
myvar = m.replace ('.', '');

if (Trim(myvar) != "") {
	
if (isNaN(parseFloat(myvar)) || parseFloat(myvar) > 59 || parseFloat(myvar) < 0) myvar = "00";
else myvar = formatNumber(myvar, '00');

}

return myvar;

}


function mettizero () {	//Funzione che mette gli zeri nelle ore e i decimali negli importi

//document.form1.orainih.value = document.form1.orainih.value.replace ('.', '');
//if (isNaN(parseFloat(document.form1.orainih.value)) || parseFloat(document.form1.orainih.value) > 23 || parseFloat(document.form1.orainih.value) < 0) document.form1.orainih.value = "00";
//else document.form1.orainih.value = formatNumber(document.form1.orainih.value, '00');
document.form1.orainih.value = format_ora(document.form1.orainih.value);

//document.form1.orainim.value = document.form1.orainim.value.replace ('.', '');
//if (isNaN(parseFloat(document.form1.orainim.value)) || parseFloat(document.form1.orainim.value) > 59  || parseFloat(document.form1.orainim.value) < 0) document.form1.orainim.value = "00";
//else document.form1.orainim.value = formatNumber(document.form1.orainim.value, '00');
document.form1.orainim.value = format_min(document.form1.orainim.value);

//document.form1.orafinh.value = document.form1.orafinh.value.replace ('.', '');
//if (isNaN(parseFloat(document.form1.orafinh.value)) || parseFloat(document.form1.orafinh.value) > 23 || parseFloat(document.form1.orafinh.value) < 0) document.form1.orafinh.value = "00";
//else document.form1.orafinh.value = formatNumber(document.form1.orafinh.value, '00');
document.form1.orafinh.value = format_ora(document.form1.orafinh.value);

//document.form1.orafinm.value = document.form1.orafinm.value.replace ('.', '');
//if (isNaN(parseFloat(document.form1.orafinm.value)) || parseFloat(document.form1.orafinm.value) > 59 || parseFloat(document.form1.orafinm.value) < 0) document.form1.orafinm.value = "00";
//else document.form1.orafinm.value = formatNumber(document.form1.orafinm.value, '00');
document.form1.orafinm.value = format_min(document.form1.orafinm.value);

//document.form1.oraviagh.value = document.form1.oraviagh.value.replace ('.', '');
//if (isNaN(parseFloat(document.form1.oraviagh.value)) || parseFloat(document.form1.oraviagh.value) > 23 || parseFloat(document.form1.oraviagh.value) < 0) document.form1.oraviagh.value = "00";
//document.form1.oraviagh.value = formatNumber(document.form1.oraviagh.value, '00');
document.form1.oraviagh.value = format_ora(document.form1.oraviagh.value);

//document.form1.oraviagm.value = document.form1.oraviagm.value.replace ('.', '');
//if (isNaN(parseFloat(document.form1.oraviagm.value)) || parseFloat(document.form1.oraviagm.value) > 59 || parseFloat(document.form1.oraviagm.value) < 0) document.form1.oraviagm.value = "00";
//else document.form1.oraviagm.value = formatNumber(document.form1.oraviagm.value, '00');
document.form1.oraviagm.value = format_min(document.form1.oraviagm.value);

//document.form1.orelavh.value = document.form1.orelavh.value.replace ('.', '');
//if (isNaN(parseFloat(document.form1.orelavh.value)) || parseFloat(document.form1.orelavh.value) > 23 || parseFloat(document.form1.orelavh.value) < 0) document.form1.orelavh.value = "00";
//else document.form1.orelavh.value = formatNumber(document.form1.orelavh.value, '00');
document.form1.orelavh.value = format_ora(document.form1.orelavh.value);

//document.form1.orelavm.value = document.form1.orelavm.value.replace ('.', '');
//if (isNaN(parseFloat(document.form1.orelavm.value)) || parseFloat(document.form1.orelavm.value) > 59 || parseFloat(document.form1.orelavm.value) < 0) document.form1.orelavm.value = "00";
//else document.form1.orelavm.value = formatNumber(document.form1.orelavm.value, '00');
document.form1.orelavm.value = format_min(document.form1.orelavm.value);

if (isNaN(parseFloat(document.form1.kmviag.value)) || parseFloat(document.form1.kmviag.value) < 0) document.form1.kmviag.value = '00';
else document.form1.kmviag.value = formatNumber(document.form1.kmviag.value, '00');

// FORMATTA DECIMALI NUOVO SISTEMA
document.form1.tot_manodopera.value = formatNumber(document.form1.tot_manodopera.value, '00.00');
document.form1.tot_varie.value = formatNumber(document.form1.tot_varie.value, '00.00');
document.form1.tot_ricambi.value = formatNumber(document.form1.tot_ricambi.value, '00.00');
document.form1.tot_consumabili.value = formatNumber(document.form1.tot_consumabili.value, '00.00');
document.form1.tot_dirittochiamata.value = formatNumber(document.form1.tot_dirittochiamata.value, '00.00');
document.form1.tot_trasferta.value = formatNumber(document.form1.tot_trasferta.value, '00.00');
document.form1.tot_iva.value = formatNumber(document.form1.tot_iva.value, '00.00');
document.form1.tot_doc.value = formatNumber(document.form1.tot_doc.value, '00.00');
document.form1.incassato.value = formatNumber(document.form1.incassato.value, '00.00');
}







function totali (IVA) { //(IVA)calcolo i totali e prendo in input l'IVA

mettizero();

if (IVA == 'cercatela') IVA = document.form1.ivaint.value;

var totiva_ric = parseFloat(document.form1.ric_impiva.value);

var totrica = parseFloat(document.form1.tot_ricambi.value);
var totcons = parseFloat(document.form1.tot_consumabili.value);
var tottras = parseFloat(document.form1.tot_trasferta.value);
var totmano = parseFloat(document.form1.tot_manodopera.value);
var totdiri = parseFloat(document.form1.tot_dirittochiamata.value); 
var totvari = parseFloat(document.form1.tot_varie.value); 

if (isNaN(totiva_ric)) totiva_ric = 0;

if (isNaN(totrica)) totrica = 0;
if (isNaN(totcons)) totcons = 0;
if (isNaN(tottras)) tottras = 0;
if (isNaN(totmano)) totmano = 0;
if (isNaN(totdiri)) totdiri = 0;
if (isNaN(totvari)) totvari = 0;

//CALCOLO IVA

if (IVA == 0) {
var totiva = 0;
} else {
	var totaleperiva =  tottras + totmano + totdiri + totvari;
	var totiva = (totaleperiva*IVA)/100;
}

//CALCOLO TOTALE DOCUMENTO

var totaledoc = parseFloat(totrica) +
	parseFloat(totcons) +
	parseFloat(tottras) +
	parseFloat(totmano) +
	parseFloat(totdiri) +
	parseFloat(totvari) +
	parseFloat(totiva);

//alert (parseFloat(totiva)+"+"+parseFloat(totiva_ric)+"="+(parseFloat(totiva)+parseFloat(totiva_ric))+"\n\n"+Math.round(totiva)+"+"+Math.round(totiva_ric)+"="+(Math.round(totiva)+Math.round(totiva_ric)));

//Asseggno i valori alla textbox che , disabilitata, non passa i valori, quindi assegno anche a un campo HIDDEN

document.form1.tot_iva.value = (parseFloat(totiva) + parseFloat(totiva_ric));
document.form1.tot_doc.value = (parseFloat(totaledoc) + parseFloat(totiva_ric));


mettizero();
}






function controlla_ricambi (nform, FLCONSU, FLRICA, FLVARIE) {


var ok = true;

if (isNaN(document.forms[nform].qta.value) || document.forms[nform].qta.value == '' || document.forms[nform].qta.value == ' ') { 
 alert ('Inserire correttamente la Quantità');
 ok = false;
 }

if (document.forms[nform].sconto1.value != '' && isNaN(document.forms[nform].sconto1.value)) { 
 alert ('Inserire correttamente SCONTO 1');
 ok = false;
 }
if (document.forms[nform].sconto2.value != '' && isNaN(document.forms[nform].sconto2.value)) { 
 alert ('Inserire correttamente SCONTO 2');
 ok = false;
 }
if (document.forms[nform].sconto3.value != '' && isNaN(document.forms[nform].sconto3.value)) { 
 alert ('Inserire correttamente SCONTO 3');
 ok = false;
 }

if (isNaN(document.forms[nform].valuni.value) || document.forms[nform].valuni.value == '' || document.forms[nform].valuni.value == ' ') { 
 alert ('Inserire correttamente il Valore Unitario');
 ok = false;
 }

if (document.forms[nform].tipric.value == '') { 
 alert ('Inserire la tipologia dell\' articolo');
 ok = false;
 }


if (ok != false) {
    
	switch ( document.forms[nform].tipric.value ) {  
	 case 'R' :  
		//Ricambio
		if ((document.forms[nform].fatt.checked == false && FLRICA == 'S') || (document.forms[nform].fatt.checked == true && FLRICA != 'S')) {
			if (FLRICA == 'S') ok = window.confirm ("Non si sta fatturando l\'articolo, continuare?");
			else ok = window.confirm ("Si sta fatturando l\'articolo, continuare?");
			}
		break; 
	 case 'C' :  
		//Consumabile
		if ((document.forms[nform].fatt.checked == false && FLCONSU == 'S') || (document.forms[nform].fatt.checked == true && FLCONSU != 'S')) {
			if (FLCONSU == 'S') ok = window.confirm ("Non si sta fatturando l\'articolo, continuare?");
			else ok = window.confirm ("Si sta fatturando l\'articolo, continuare?");
			}
		break; 
	 case 'M' :  
		//Macchina
		if ((document.forms[nform].fatt.checked == false && FLVARIE == 'S') || (document.forms[nform].fatt.checked == true && FLVARIE != 'S')) {
			if (FLVARIE == 'S') ok = window.confirm ("Non si sta fatturando l\'articolo, continuare?");
			else ok = window.confirm ("Si sta fatturando l\'articolo, continuare?");
			}
		break; 
	 case 'A' :  
		//Accessorio
		if ((document.forms[nform].fatt.checked == false && FLVARIE == 'S') || (document.forms[nform].fatt.checked == true && FLVARIE != 'S')) {
			if (FLVARIE == 'S') ok = window.confirm ("Non si sta fatturando l\'articolo, continuare?");
			else ok = window.confirm ("Si sta fatturando l\'articolo, continuare?");
			}
		break; 
	 }  

 
}



return ok;
}




// Serve a passare da una pagina all'altra dell'elenco degli articoli
function jump(n) {
 document.formcerca.limit.value = n;
 document.formcerca.submit();
}

function jump_ajax(n) {
 document.getElementById("ric_limit").value = n;
 ric_search(0, -1);
}


// Serve a passare da una pagina all'altra dell'elenco degli articoli
function jump2(n, id_form) {
 myform = document.getElementById(id_form);
 myform.limit.value = n;
 myform.submit();
}

function jump_alfa(alfa, id_form) {
 myform = document.getElementById(id_form);
 myform.alfa.value = alfa;
 myform.submit();
}

function ric_ordina(ord) {			  
 document.formcerca.orderby.value = ord;
 document.formcerca.submit();
}


function ric_ordina_ajax(ord) {			  
 document.getElementById("ric_orderby").value = ord;
 ric_search(0, -1);
}

function chiedi() {
	var messaggio;
	var sicuro;
	if (document.form1.sospe.checked == false) {
		messaggio = "Chiudere l\'Intervento?\n(Non sarà possibile modificare i dati)";
		sicuro = window.confirm (messaggio);
	} else {
		messaggio = "L\'intervento è sospeso e non può essere chiuso definitivamente\nE\' possibile usare il tasto REGISTRA per salvare i dati dell\'Intervento";
		alert(messaggio);
		sicuro=false;
	}
	return sicuro;
}




function prox_prec (mydate) {
 document.form_agenda.hid_data.value = mydate;
 document.form_agenda.submit();
}

function prox_prec_AgendaAgenti (mydate) {
 document.formcerca.hid_data.value = mydate;
 document.formcerca.submit();
}


function controlla_sposta () {
	
ok1= true;

var data = document.form_sposta.data.value;
var data_d = data.substr(0, 2);// 11/04/1979
var data_m = data.substr(3, 2);
var data_Y = data.substr(6, 4);

if (ok1 == true && !(verifica_data (data_d, data_m, data_Y))) {
 alert ("Data non valida");
 ok1 = false;
}


if (ok1 == true && parseFloat(document.form_sposta.durata_H.value)*60+parseFloat(document.form_sposta.durata_i.value) > 480) {
 alert ("Durata massima per l\'intervento: 8 ore");
 ok1 = false;
}

return ok1;

}



function trova_giorno (myform) {

 var nomi_giorni=new Array("Domenica","Lunedì","Martedì","Mercoledì","Giovedì","Venerdì","Sabato");

 var dd = document.getElementById(myform).data_d.value;
 var mm = document.getElementById(myform).data_m.value;
 var yy = document.getElementById(myform).data_Y.value;

 if (dd != "" && mm != "" && yy != "") {
	 var ugo = verifica_data (dd,mm,yy);
	 if (ugo == true) {
	
		 var data=new Date(yy,(mm*1)-1,dd);
		 var giornosettimana=data.getDay();
		
		 document.getElementById(myform).giorno_della_settimana.value = nomi_giorni[giornosettimana];
	 } else document.getElementById(myform).giorno_della_settimana.value = "";
 } else document.getElementById(myform).giorno_della_settimana.value = "";

}




function filtra_agenda (filtro) {
	
 if (filtro == "tutti") {
  document.form_agenda.soloaperti.value = "";
  document.form_agenda.solochiusi.value = "";
  document.form_agenda.solocritici.value = "";
  
 } else if (filtro == "a") {
  document.form_agenda.soloaperti.value = "S";
  document.form_agenda.solochiusi.value = "";
  
  } else if (filtro == "aS") {
  document.form_agenda.soloaperti.value = "";
  
  } else if (filtro == "c") {
  document.form_agenda.soloaperti.value = "";
  document.form_agenda.solochiusi.value = "S";
  
  } else if (filtro == "cS") {
  document.form_agenda.solochiusi.value = "";
  
 } else if (filtro == "r") document.form_agenda.solocritici.value = "S";
 else if (filtro == "rS") document.form_agenda.solocritici.value = "";

document.form_agenda.submit();
}






function cambia_tariffa() {

codtar = document.form1.tariffa.value;

/*
alert ("tariffa: "+codtar);
alert(
		"SC1_DUR:" + tariffe_SC1_DUR[codtar] + "\n" +
		"SC1_IMP:" + tariffe_SC1_IMP[codtar] + "\n" +
		"SC1_MINFAT:" + tariffe_SC1_MINFAT[codtar] + "\n" +
		"...:" + tariffe_SC2_DUR[codtar] + "\n" +
		":" + tariffe_SC2_IMP[codtar] + "\n" +
		":" + tariffe_SC2_MINFAT[codtar] + "\n" +
		":" + tariffe_SCO_IMP[codtar] + "\n" +
		":" + tariffe_SCO_MINFAT[codtar] + "\n" +
		":" + tariffe_VI_IMP[codtar] + "\n" +
		":" + tariffe_VI_MINFAT[codtar] + "\n" +
		":" + tariffe_KM_IMP[codtar] + "\n" +
		":" + tariffe_KM_MINFAT[codtar]
		);
*/

document.form1.DC_TC.value 		= tariffe_DC_TC[codtar];
document.form1.SC1_DUR.value 	= tariffe_SC1_DUR[codtar];
document.form1.SC1_IMP.value 	= tariffe_SC1_IMP[codtar];
document.form1.SC1_MINFAT.value = tariffe_SC1_MINFAT[codtar];
document.form1.SC2_DUR.value 	= tariffe_SC2_DUR[codtar];
document.form1.SC2_IMP.value 	= tariffe_SC2_IMP[codtar];
document.form1.SC2_MINFAT.value = tariffe_SC2_MINFAT[codtar];
document.form1.SCO_IMP.value 	= tariffe_SCO_IMP[codtar];
document.form1.SCO_MINFAT.value = tariffe_SCO_MINFAT[codtar];
document.form1.VI_IMP.value 	= tariffe_VI_IMP[codtar];
document.form1.VI_MINFAT.value 	= tariffe_VI_MINFAT[codtar];
document.form1.KM_IMPvalue 		= tariffe_KM_IMP[codtar];
document.form1.KM_MINFAT.value 	= tariffe_KM_MINFAT[codtar];

calcimporti();

}




function ordina (var_ordinamento) {
		document.formcerca.orderby.value = var_ordinamento;
		document.formcerca.submit();
}



function solo_rile () {
	document.formcerca.solorile.value='S';
	document.formcerca.submit();
}


function solo_chiam () {
	
	document.formcerca.solochiam.value='S';
	document.formcerca.submit();

}

function stampa_matricole() {
 	document.formcerca.stampa.value='S';
	document.formcerca.submit();
}
function torna_stampa() {
 	document.formcerca.stampa.value='';
	document.formcerca.submit();
}


function filtra_statochiam (filtro) {
	document.formcerca.filt_statochiam.value=filtro.value;
	document.formcerca.submit();
}


function contr_modmatr() {

	var msg = "";
	var ret = true;
	
	if (document.form1.assegna_int.checked != false) msg+= "L'indirizzo email per l'intervento tecnico sara' assegnato a tutte le matricole.\n";
	if (document.form1.assegna_ril.checked != false) msg+= "L'indirizzo email per le rilevazioni sara' assegnato a tutte le matricole.\n";
	
	if (msg != "") {
	
		msg+= "Continuare?";
		ret = window.confirm (msg);
		
	}

	return ret;

}


function contr_abilitaUte () {

 var err = "";

 if (Trim(document.form1.userid.value) == "") {
	 err+= "Inserire un userid";
 }
 
 if (err != "") {
	
	alert(err);
	return false;
	
 } else return controlla_email(document.form1.email.value);
}



function contr_prof () {
	
 var err = "";
 
 var userid = Trim(document.form1.userid.value);
 
 var pwd = Trim(document.form1.pwd.value);
 var pwd2 = Trim(document.form1.pwd2.value);
 
 var email = Trim(document.form1.email.value);
 var email2 = Trim(document.form1.email2.value);
 
 //verifico userid
 if (userid == "") err+= "Inserire un userid\n";
 
 // verifico pwd
 if (pwd!="" && pwd.length < 4) err+= "La password deve essere composta da almeno 4 caratteri alfanumerici\n"; 
 if (pwd != pwd2) err+= "Le due password non corrispondono\n";
					   
 // verifico emil
 if(!checkEmail(email)) err+= "Email non valida\n";
 else if (email != email2) err+= "Gli indirizzi email non corrispondono\n";
	
	
// RETURN
 if (err != "") {
	
	alert(err);
	// elimino gli spazi(trim)
	document.form1.pwd.value = pwd;
	document.form1.pwd2.value = pwd2;
	document.form1.email.value = email;
	document.form1.email2.value = email2;
	return false;
	
 } else return true;

 
}


function contr_chiamata () {

document.form1.dalleoreri_H.value = format_ora(document.form1.dalleoreri_H.value);
document.form1.dalleoreri_i.value = format_min(document.form1.dalleoreri_i.value);

var motchia = document.form1.motchia.value;
var datric = document.form1.datric.value;
var arrdatric = datric.split("/");
var qconta = document.form1.qconta.value;
var oggi = document.form1.oggi.value;
var matricola = document.getElementById("matricola").value;

if (Trim(document.form1.dalleoreri_H.value) != "" || Trim(document.form1.dalleoreri_i.value) != "") var dalleoreri = (document.form1.dalleoreri_H.value*60)+(document.form1.dalleoreri_i.value*1);
else var dalleoreri = 1440;
var adesso_H = document.form1.adesso_H.value;
var adesso_i = document.form1.adesso_i.value;
var adesso = (adesso_H*60)+(adesso_i*1);

var ok = true;
var err = "";

if (Trim(motchia) == "") {
 err+="Inserire motivo chiamata\n";
 ok = false;
}

// verifico correttezza data
if (datric != "" && !verifica_data (arrdatric[0],arrdatric[1],arrdatric[2])) {
 err+="Formato data non corretto (richiesto: gg/mm/aaaa)\n";
 ok = false;
} else {
// verifico che non sia una data passata
 d1= arrdatric[2]+arrdatric[1]+arrdatric[0];
 if (d1<oggi) {
  err+="Impossibile inserire una data inferiore ad oggi\n";
  ok = false;
 } else if (d1==oggi && dalleoreri<adesso) {
   err+="Impossibile inserire un orario inferiore ad ora (orario server: "+adesso_H+":"+adesso_i+")\n";
   ok = false;
 }
}

//orario
if (Trim(document.form1.dalleoreri_H.value) != "" || Trim(document.form1.dalleoreri_i.value) != "") {
if (Trim(document.form1.dalleoreri_H.value) == "" || Trim(document.form1.dalleoreri_i.value) == "") {
 err+="Inserire orario correttamente\n";
 ok = false;
} else {
if (!(document.form1.dalleoreri_H.value > -1 && document.form1.dalleoreri_H.value < 24 && document.form1.dalleoreri_i.value>-1 && document.form1.dalleoreri_i.value < 60)) {
 err+="Inserire orario correttamente\n";
 ok = false;
}
}
}


// controllo contatori
if (qconta > 0) {
	
var datsca = document.form1.data_now.value.substring(3,5) + "/" +document.form1.data_now.value.substring(0,2) + "/" + document.form1.data_now.value.substring(6,10);
var datconta_ita = document.form1.datconta.value;
var datconta = document.form1.datconta.value.substring(3,5) + "/" + document.form1.datconta.value.substring(0,2) + "/" + document.form1.datconta.value.substring(6,10);

var d1 = new Date(datsca);
var d2 = new Date(datconta);
var datdif = Math.round((d1.getTime() - d2.getTime())/86400000);
var mycont;

 for (c=0; c<qconta; c++) {
	if (global_vars['dex_conta']==true) dex_conta = document.getElementById("dex_conta_"+(c+1)).value;
	else dex_conta = "Contatore "+(c+1);
	
	if (Trim(document.getElementById("contatore"+(c+1)).value)!="") mycont = parseFloat(Trim(document.getElementById("contatore"+(c+1)).value));
	else mycont="";
	var acv = parseFloat(document.getElementById("ACV"+(c+1)).value);
	var cx = parseFloat(document.getElementById("cx"+(c+1)).value);
	
	if (Trim(mycont) != "" && (isNaN(mycont) || mycont > 100000000 || mycont < 0)) {
	 err+= "Inserire correttamente le rilevazioni (0, 100000000)\n";
	 ok = false;
	 break;
	} else if (document.form1.FLRILCHIAM.value == "S" && Trim(mycont) == "") {
	 err+= "E' obbligatorio inserire tutte le rilevazioni\n";
	 ok = false;
	 break;
	} else if (mycont < cx && Trim(mycont) != "") {
	 err+= dex_conta+" non puo' essere inferiore alla rilevazione precedente\n";
	 ok = false;
	 break;
	} else {
	//controllo range
		if (acv > 0) {
			var n_copie= (datdif*acv/30);
			if (n_copie > 0) {
			var minimo = Math.round(cx + (n_copie/2));
			var massimo = Math.round(cx + (n_copie * 3/2));
			
			if (Trim(mycont) != "" && (mycont > massimo || mycont < minimo)) {
			 ok = window.confirm(print_err_conta(dex_conta, mycont, minimo, massimo, matricola, datconta_ita));
			 if (!ok) break;
			}		
			}
		} // Chiuso if (acv>0)
	}
 }
}



if (err != "") alert(err);
return ok;
}


function print_err_conta(dex_conta, mycont, minimo, massimo, matricola, datconta) {
 var msg = "Matricola: "+matricola+"\nUltima Lettura: "+datconta+"\n\nTipo Contatore: "+dex_conta+"\nValore Inserito: "+addCommas(mycont)+"\nTeorico Min.: "+addCommas(minimo)+"\nTeorico Max.: "+addCommas(massimo)+"\n\nConfermi l\'aggiornamento?";
 return msg;
}



function contr_ordine () {

var form_ordina = document.getElementById('form_ordina');
var qconta = form_ordina.qconta.value;
var matricola = document.getElementById("matricola").value;

var ok = true;
var err = "";

// controllo contatori
if (qconta > 0) {
	
var datsca = form_ordina.data_now.value.substring(3,5) + "/" +form_ordina.data_now.value.substring(0,2) + "/" + form_ordina.data_now.value.substring(6,10);
var datconta_ita = form_ordina.datconta.value;
var datconta = form_ordina.datconta.value.substring(3,5) + "/" + form_ordina.datconta.value.substring(0,2) + "/" + form_ordina.datconta.value.substring(6,10);

var d1 = new Date(datsca);
var d2 = new Date(datconta);
var datdif = Math.round((d1.getTime() - d2.getTime())/86400000);
var mycont;
var dex_conta;

 for (c=0; c<qconta; c++) {
	if (global_vars['dex_conta']==true) dex_conta = document.getElementById("dex_conta_"+(c+1)).value;
	else dex_conta = "Contatore "+(c+1);
	
	if (Trim(document.getElementById("contatore"+(c+1)).value)!="") mycont = parseFloat(Trim(document.getElementById("contatore"+(c+1)).value));
	else mycont="";
	var acv = parseFloat(document.getElementById("ACV"+(c+1)).value);
	var cx = parseFloat(document.getElementById("cx"+(c+1)).value);
	
	if (Trim(mycont) != "" && (isNaN(mycont) || mycont > 100000000 || mycont < 0)) {
	 err+= "Inserire correttamente le rilevazioni (0, 100000000)\n";
	 ok = false;
	 break;
	} else if (form_ordina.FLRILCHIAM.value == "S" && Trim(mycont) == "") {
	 err+= "E' obbligatorio inserire tutte le rilevazioni\n";
	 ok = false;
	 break;
	} else if (mycont < cx && Trim(mycont) != "") {
	 err+= dex_conta+" non puo' essere inferiore alla rilevazione precedente\n";
	 ok = false;
	 break;
	} else {
	//controllo range
		if (acv > 0) {
			var n_copie= (datdif*acv/30);
			if (n_copie > 0) {
			var minimo = Math.round(cx + (n_copie/2));
			var massimo = Math.round(cx + (n_copie * 3/2));
			
			if (Trim(mycont) != "" && (mycont > massimo || mycont < minimo)) {
			 ok = window.confirm(print_err_conta(dex_conta, mycont, minimo, massimo, matricola, datconta_ita));
			 if (!ok) return false;
			}		
			}
		} // Chiuso if (acv>0)
	}
 }
}


//verifico qta
var quanti_art = document.getElementById('countart').value;
var thisqta=0;
var tot_art_ordinati = 0;
for (nart=1;nart<=quanti_art;nart=nart+1) {
 thisqta = document.getElementById("qta_"+nart).value;
 if (isNaN(thisqta) || thisqta < 0) { // || Trim(thisqta) == ''
  err+="Inserire correttamente le quantità\n";
  ok = false;
  break;
 }
 if (thisqta!='' && thisqta>0) tot_art_ordinati=tot_art_ordinati+1;
}//for

if (err=="" && tot_art_ordinati==0) err+= "Devi selezionare almeno un articolo\n";


if (err != "") {
	alert(err);
	return false;
} else {
	return true;
	//document.getElementById('form_ordina').submit();
}

}







function contr_rileva (nform) {

var myform = document.getElementById("form"+nform);
var dataadesso = new Date();
var daa=dataadesso.getFullYear().toString();
var dmm=(dataadesso.getMonth()+1).toString();
    dmm=dmm.length==1?"0"+dmm:dmm
var dgg=dataadesso.getDate().toString();
    dgg=dgg.length==1?"0"+dgg:dgg
var dataadessostr = daa+dmm+dgg;
   
// recupero rifper
myform.rifper.value = document.getElementById("myrifper").value;

//rilevazioni precedenti ancora da fare
var rile_prec_dafare = myform.rile_prec_dafare.value;

var err = "";
var dataril = myform.dataril.value;
var arrdataril = dataril.split("/");
//var qconta = myform.qconta.value;
var qconta = myform.quanti_cont.value;

ok = true;

if (!verifica_data (arrdataril[0],arrdataril[1],arrdataril[2])) {
	err+= "Data rilevazione non valida (richiesto: gg/mm/aaaa)\n";
	ok = false;
} else {
    //verifico che non sia FUTURA ad ora
	var data_verita = arrdataril[2]+arrdataril[1]+arrdataril[0];
	if (dataadessostr<data_verita) {
	 err+= "Non puoi inserire una data di rilevazione futura!";
	 ok = false;
	} else {
	 //o che non sia troppo vecchia rispetto ad ora
	 var max_indietro = myform.BACK_RIL_DAYS.value;
	 if (max_indietro!="" && max_indietro>data_verita) {
		 var msgbackril = "Hai inserito una data rilevazione troppo lontana nel tempo";
		 if (myform.BACK_RIL_DAYS_BLOC.value=="1") {
			 err+= msgbackril;
	 		 ok = false;
		 } else {
			 ok = window.confirm(msgbackril+"\nContinuare?");
		 }
	 }
	}
}

if (rile_prec_dafare > 0) {
	ok = window.confirm("Ci sono delle rilevazioni precedenti ancora da effettuare\nContinuare?");
}

// controllo contatori
if (qconta > 0) {
 for (c=1; c<=qconta; c++) {
	if (ok != false) ok = controlla_rilevazioneX (c, nform);
	/*mycont = Trim(document.getElementById("contatore"+(c+1)).value);
	if (isNaN(mycont) || mycont > 100000000 || mycont < 0 || mycont.length == 0) {
	 err+= "Inserire correttamente le rilevazioni (0, 100000000)\n";
	 ok = false;
	 break;
	}*/
 }
}

if (ok == false && err != "") alert (err);
return ok;

}







function controlla_rilevazioneX (X, nform) {

myform = document.getElementById("form"+nform);

var matricola = document.getElementById("matricola").value;

if (global_vars['dex_conta']==true) dex_conta = document.getElementById(nform+"_dex_conta_"+X).value;
else dex_conta = "Contatore "+(X);

	
//converto il formato della data: da gg/mm/aaaa a mm/gg/aaaa
var datsca = myform.datsca.value.substring(3,5) + "/" + myform.datsca.value.substring(0,2) + "/" + myform.datsca.value.substring(6,10);
var datconta_ita = myform.datconta.value;
var datconta = myform.datconta.value.substring(3,5) + "/" + myform.datconta.value.substring(0,2) + "/" + myform.datconta.value.substring(6,10);

var d1 = new Date(datsca);
var d2 = new Date(datconta);

/*
alert(d1+" - \n"+d2);
return false;
*/

var cx = parseFloat(document.getElementById("cp"+X+"_"+nform).value);
var codx = document.getElementById("cod"+X+"_"+nform).value;
var acv = parseFloat(document.getElementById("ACV"+X).value);
var myril = document.getElementById("contatore"+X+"_"+nform).value;

//alert("Controllo "+X+": "+myril+"\ncod="+codx+", cx="+cx);

if (Trim(myril) == "") {
	alert(dex_conta+": Inserire la rilevazione.");
	return false;
}
 
if (isNaN(myril) || myril < 0) {
	alert(dex_conta+": Inserire un numero intero positivo.");
	return false;
}

if (codx != '' && cx > -1) {

 myril=parseFloat(myril);

 if (myril < cx) {
	return window.confirm (dex_conta+": La Rilevazione è inferiore a quella precedente.\nContinuare?");
 } else {

 
 
	if (acv > 0) {


		var datdif = Math.round((d1.getTime() - d2.getTime())/86400000);
		var n_copie= (datdif*acv/30);
		
		if (n_copie > 0) {
			 		
			var minimo = Math.round(cx + (n_copie/2));
			var massimo = Math.round(cx + (n_copie * 3/2));

			//alert("uuu: "+minimo+" a "+massimo+"");

				if (myril > massimo || myril < minimo) {
					//alert("Inserire correttamente le rilevazioni (min "+minimo+", max "+massimo+")");
					return window.confirm (print_err_conta(dex_conta, myril, minimo, massimo, matricola, datconta_ita));
				}
		}
	
	} // Chiuso if (acv)
 }// Chiuso if (rile < cont_prec)
 } // Chiuso if (cod1)


}





function apri_tracking (ID_WEB) {
	
window.open ('vis_tracking.php?ID_WEB='+ID_WEB, 'TRACKING', 'width=400, height=400, resizable=1, scrollbars=1');
return false;

}







function mostra_difcauaz (stato_int, conf_combo_difcauaz_orderby, conf_combo_difcauaz_show_CODTAB, conf_combo_difcauaz_spacer, conf_combo_difcauaz_show_DESTAB, dif1, cau1, int1, dif2, cau2, int2, dif3, cau3, int3) {
	
	myspan = document.getElementById("span_difcauaz");
	myspan.innerHTML = "Attendere, prego...";
	agent.call('','mostra_difcauaz','span_difcauaz', stato_int, conf_combo_difcauaz_orderby, conf_combo_difcauaz_show_CODTAB, conf_combo_difcauaz_spacer, conf_combo_difcauaz_show_DESTAB, dif1, cau1, int1, dif2, cau2, int2, dif3, cau3, int3);
}




function mostra_articoli (tipart, codart) {
	myspan = document.getElementById("sel_articoli");
	myspan.innerHTML = "Attendere, prego...";
	agent.call('','mostra_articoli','sel_articoli', tipart, codart);
}

function mostra_articoli2 (tipart, codart) {
	strsrch = remove_badchar(document.getElementById("filtra_sel_art").value);
	myspan = document.getElementById("sel_articoli");
	myspan.innerHTML = "Attendere, prego...";
	agent.call('','mostra_articoli','sel_articoli', tipart, codart, strsrch);
}


function mostra_anagraf (tipana, codana) {
	myspan = document.getElementById("sel_anagraf");
	myspan.innerHTML = "Attendere, prego...";
	agent.call('','mostra_anagraf','sel_anagraf', tipana, codana);
}



// riceve l'elemento (es: document.form_sposta) + giorno, mese, anno
function to_oggi(elemento, giorno, mese, anno) {	
	elemento.data_d.value=giorno;
	elemento.data_m.value=mese;
	elemento.data_Y.value=anno;
}







function noHtml(txt) {
    a = txt.indexOf('<');
    b = txt.indexOf('>');
    len = txt.length;
    c = txt.substring(0, a);
    if(b == -1) {
       b = a;
    }
    d = txt.substring((b + 1), len);
    txt = c + d;
    cont = txt.indexOf('<');
    if (cont != -1) {
      txt = noHtml(txt);
    }
    return txt;
}



function remove_badchar (str) {

 if (Trim(str) != "") {
 // per prima cosa elimino i tag html
 res = noHtml(str);
 res = res.replace ('\"', '&quot;');
 // trasformo le & in un codice riconoscibile: "*:and:*"
 res = res.replace ('&', '*:and:*');
 } else res=str;
 
return res;
	
}






function check_ins_anagraf (id_form) {
  
 myform = document.getElementById(id_form);
 
 // preparo le variabili, le inserisco in un array
 vars = new Array();
 vars[0] = remove_badchar(myform.TIPANA.value);
 vars[1] = remove_badchar(myform.CODANA.value);
 vars[2] = remove_badchar(myform.TIPANA_old.value);
 vars[3] = remove_badchar(myform.CODANA_old.value);
 
 
 
 // prima i controlli JS semplici
 var err = ""; 
 if (Trim(vars[0]) == "") err+= "Inserire TIPO CLIENTE\n";
 if (Trim(vars[1]) == "") err+= "Inserire CODICE CLIENTE\n";
 
 email = remove_badchar(myform.EMAIL.value);
 if(!checkEmail(email)) err+= "Email non valida\n";
 
 if (err != "") {
	 alert(err);
 } else agent.call('','check_ins_anagraf','check_alerts', vars, id_form);
 return false;
}




function check_ins_anaweb (id_form) {
  
 myform = document.getElementById(id_form);
 
 // preparo le variabili, le inserisco in un array
 vars = new Array();
 vars[0] = remove_badchar(myform.USERID.value);
 vars[1] = remove_badchar(myform.USERID_old.value);
 vars[2] = remove_badchar(myform.PWD.value);
 vars[3] = remove_badchar(myform.PWD2.value);
 vars[4] = remove_badchar(myform.TIPANA.value);
 vars[5] = remove_badchar(myform.CODANA.value);
 vars[6] = remove_badchar(myform.action.value);
 vars[7] = remove_badchar(myform.TIPANA_old.value);
 vars[8] = remove_badchar(myform.CODANA_old.value);
 
 // prima i controlli JS semplici
 var err = ""; 
 if (Trim(vars[5]) == "") err+= "Inserire CODICE CLIENTE\n";
 if (Trim(vars[0]) == "") err+= "Inserire USERID\n";
	  
 if (vars[2] != vars[3]) err+= "Le password non corrispondono\n";
 else if (vars[6] == "wri" && Trim(vars[2]) == "") err+= "Inserisci password\n";
 else if (Trim(vars[2]) != "") {
	mypwd = vars[2];
	if (mypwd.length < 4) err+= "La password deve essere composta da almeno 4 caratteri\n";
 }

 email = remove_badchar(myform.EMAIL.value);
 if(!checkEmail(email)) err+= "Email non valida\n";
 
 
 if (err != "") {
	 alert(err);
 } else agent.call('','check_ins_anaweb','check_alerts', vars, id_form);
 return false;
}



function check_ins_matrico (id_form) {
  
 myform = document.getElementById(id_form);
 
 // preparo le variabili, le inserisco in un array
 vars = new Array();
 vars[0] = remove_badchar(myform.MATRICOLA.value);
 vars[1] = remove_badchar(myform.MATRICOLA_old.value);
 
 // prima i controlli JS semplici (senza ajax)
 var err = "";
 var continua = true;
 
 art_sel = z.getSelectedText();
 art_vis = z.getComboText();
 if (Trim(art_vis) == "")  document.form_matrico.TIPART_CODART.value = "";
 else if (art_sel != art_vis) err+= "L'articolo non è stato selezionato correttamente.\nSi prega di effettuare nuovamente la selezione\n";

 ana_sel = y.getSelectedText();
 ana_vis = y.getComboText();
 if (Trim(ana_vis) == "")  document.form_matrico.TIPANA_CODANA.value = "";
 else if (ana_sel != ana_vis) err+= "Il cliente non è stato selezionato correttamente.\nSi prega di effettuare nuovamente la selezione\n";
 
 /* con il confirm nn funziona (vedi la variabile post inviata quando si modifica il testo dell'articolo selezionato
if (art_sel != art_vis) continua = window.confirm("Attenzione! l'articolo selezionato è "+art_sel+"\nContinuare?");
 if (!continua) return false;*/


 if (Trim(vars[0]) == "") err+= "Inserire MATRICOLA\n";
 
 if (err != "") {
	 alert(err);
 } else agent.call('','check_ins_matrico','check_alerts', vars, id_form);
 return false;
}



// questa funzione mostra l'alert e invia la form se non ci sono errori
function check_alerts (vars) {
 
 str = vars[0];
 id_form = vars[1];
 myform = document.getElementById(id_form);
 
 if (str != "") {
	 alert(str);
 } else myform.submit();
 
}






function mostra_anaweb (TIPANA, CODANA) {

myspan = 'spananaweb_'+TIPANA+CODANA;
myimg1 = document.getElementById('imgexpprof1_'+TIPANA+CODANA);
myimg2 = document.getElementById('imgexpprof2_'+TIPANA+CODANA);

myspanelement = document.getElementById(myspan);
myspanelement.innerHTML = "Attendere, prego...";

agent.call('','mostra_anaweb',myspan, TIPANA, CODANA);

myimg1.style.display='none';
myimg2.style.display='block';

}

function nascondi_anaweb (TIPANA, CODANA) {

myspan = 'spananaweb_'+TIPANA+CODANA;
myimg1 = document.getElementById('imgexpprof1_'+TIPANA+CODANA);
myimg2 = document.getElementById('imgexpprof2_'+TIPANA+CODANA);

agent.call('','nascondi_anaweb',myspan, TIPANA, CODANA);
myimg1.style.display='block';
myimg2.style.display='none';

}





function mostra_matricole (TIP, COD) {

myspan = 'spanmatricole_'+TIP+COD;
myimg1 = document.getElementById('imgexpmatr1_'+TIP+COD);
myimg2 = document.getElementById('imgexpmatr2_'+TIP+COD);

myspanelement = document.getElementById(myspan);
myspanelement.innerHTML = "Attendere, prego...";

agent.call('','mostra_matricole',myspan, TIP, COD);

myimg1.style.display='none';
myimg2.style.display='block';

}

function nascondi_matricole (TIP, COD) {

myspan = 'spanmatricole_'+TIP+COD;
myimg1 = document.getElementById('imgexpmatr1_'+TIP+COD);
myimg2 = document.getElementById('imgexpmatr2_'+TIP+COD);

agent.call('','nascondi_matricole',myspan, TIP, COD);
myimg1.style.display='block';
myimg2.style.display='none';

}






function mostra_rilev (MATRICOLA) {

myspan = 'spanrilev_'+MATRICOLA;
myimg1 = document.getElementById('imgexprilev1_'+MATRICOLA);
myimg2 = document.getElementById('imgexprilev2_'+MATRICOLA);

myspanelement = document.getElementById(myspan);
myspanelement.innerHTML = "Attendere, prego...";

agent.call('','mostra_rilev',myspan, MATRICOLA);

myimg1.style.display='none';
myimg2.style.display='block';

}

function nascondi_rilev (MATRICOLA) {

myspan = 'spanrilev_'+MATRICOLA;
myimg1 = document.getElementById('imgexprilev1_'+MATRICOLA);
myimg2 = document.getElementById('imgexprilev2_'+MATRICOLA);

agent.call('','nascondi_rilev',myspan, MATRICOLA);
myimg1.style.display='block';
myimg2.style.display='none';

}



function del_record (spanID, table, TIP, COD) {

 if (window.confirm("Vuoi eliminare definitivamente il record selezionato?")) {
  
 myspan = document.getElementById(spanID);
 imgmod = document.getElementById('imgmod'+table+TIP+COD);
 imgdel = document.getElementById('imgdel'+table+TIP+COD);
 
 imgmod.style.display="none";
 imgdel.style.display="none";
 
 agent.call('','del_record','del_record_ret', table, TIP, COD);
 
 //myspan.style.color="#CCCCCC";
 myspan.style.display="none";
 
 
 } // chiuso if confirm
}

function del_record_ret (msg) {
 if (msg!="") alert(msg);
}



function check_ins_matralter (id_form) {

  myform = document.getElementById(id_form);
 
 // preparo le variabili, le inserisco in un array
 vars = new Array();
 vars[0] = remove_badchar(myform.MATRICOLA.value);
 vars[1] = remove_badchar(myform.CODMATRSTD.value);
 vars[2] = remove_badchar(myform.MATRSATWEB.value);
 
 // prima i controlli JS semplici
 var err = ""; 
 if (Trim(vars[0]) == "") err+= "Inserire MATRICOLA (Contattare l'amministratore)!)\n";
 if (Trim(vars[1]) == "") err+= "Inserire COD.OID\n";
 if (Trim(vars[2]) == "") err+= "Inserire MATRICOLA ALTERNATIVA\n";
 
 if (err != "") {
	 alert(err);
 } else agent.call('','check_ins_matralter','check_alerts', vars, id_form);
 return false;

}


function sys_setDefault(idEle) {
	
	ele1 = document.getElementById(idEle);
	ele2 = document.getElementById(idEle+"_h");
	ele1.value = ele2.value;
	
}


function mostra_carrello(agg_imp) {
 var mydiv = document.getElementById("ric_wait_div");
 mydiv.innerHTML = msg_waiting();
 agent.call('','mostra_carrello','mostra_carrello_ret', agg_imp);
}
function mostra_carrello_ret(ret) {
 var mydiv = document.getElementById("div_ricambi");
 mydiv.innerHTML = ret;
 var mydiv = document.getElementById("ric_wait_div");
 mydiv.innerHTML = msg_waiting_vuoto();
 
 if (document.getElementById("agg_imp").value == 1) calc1_ajax();
}





function ric_search(nuova_ric, mod) {
	
	ric_search2(nuova_ric, mod);
	/*
 if (nuova_ric==1) {
	document.getElementById("ric_orderby").value = "";
	document.getElementById("ric_limit").value = "0";
 }
 var str_cerca = remove_badchar(z_strsearch.getComboText());
 var ric_solosche = document.getElementById("ric_solosche").checked;
 var ric_soloric = document.getElementById("ric_soloric").checked;
 var ric_solocons = document.getElementById("ric_solocons").checked;
 var ric_orderby = document.getElementById("ric_orderby").value;
 var ric_limit = document.getElementById("ric_limit").value;

 var vars=Array();
 vars[0] = str_cerca;
 vars[1] = ric_solosche;
 vars[2] = ric_soloric;
 vars[3] = ric_solocons;
 vars[4] = ric_orderby;
 vars[5] = ric_limit;
 vars[6] = mod;
 var mydiv = document.getElementById("ric_wait_div");
 mydiv.innerHTML = msg_waiting();
 agent.call('','ric_search','ric_search_ret', vars);
 */
}
/*
function ric_search_ret(ret) {
 var mydiv = document.getElementById("div_ricambi");
 mydiv.innerHTML = ret;
 var mydiv = document.getElementById("ric_wait_div");
 mydiv.innerHTML = msg_waiting_vuoto();
 
 //riempio tendine IVA
 var countart = document.getElementById("countart").value;
 var myivacodart = "";
 for (c=1;c<=countart;c=c+1) {
  myivacodart = document.getElementById("my_iva_"+c).value;
  agent.call('','tendine_iva',"td_iva_"+c, c, myivacodart);
 }
}
*/

function ric_search2(nuova_ric, mod) {
 if (nuova_ric==1) {
	document.getElementById("ric_orderby").value = "";
	document.getElementById("ric_limit").value = "0";
 }
 var str_cerca = remove_badchar(z_strsearch.getComboText());

 var ric_orderby = document.getElementById("ric_orderby").value;
 var ric_limit = document.getElementById("ric_limit").value;
 var sez = document.getElementById("sez").value;
 var matricola = "";
 var ric_solosche = "";
 var ric_soloric = "";
 var ric_solocons = "";
 var ric_carkit = "";
 if (sez=="cli") {
  matricola = document.getElementById("matricola").value;
 } else {
  ric_solosche = document.getElementById("ric_solosche").checked;
  ric_soloric = document.getElementById("ric_soloric").checked;
  ric_solocons = document.getElementById("ric_solocons").checked;
  ric_carkit = document.getElementById("ric_carkit").checked;
 }

 var vars=Array();
 vars[0] = str_cerca;
 vars[1] = ric_solosche;
 vars[2] = ric_soloric;
 vars[3] = ric_solocons;
 vars[4] = ric_orderby;
 vars[5] = ric_limit;
 vars[6] = mod;
 vars[7] = sez;
 vars[8] = matricola;
 vars[9] = ric_carkit;
 
 var mydiv = document.getElementById("ric_wait_div");
 mydiv.innerHTML = msg_waiting();
 agent.call('','ric_search','ric_search2_ret', vars);
}
function ric_search2_ret(ret) {
 var sez = document.getElementById("sez").value;
 var mydiv = document.getElementById("div_ricambi");
 mydiv.innerHTML = ret;
 var mydiv = document.getElementById("ric_wait_div");
 mydiv.innerHTML = msg_waiting_vuoto();
 
 //riempio tendine IVA
 if (sez=="tec") {
  var countart = document.getElementById("countart").value;
  var myivacodart = "";
  for (c=1;c<=countart;c=c+1) {
   myivacodart = document.getElementById("my_iva_"+c).value;
   agent.call('','tendine_iva',"td_iva_"+c, c, myivacodart);
  }
 }
}


function ins_ric (myid, FLCONSU, FLRICA, FLVARIE) {

var ok = true;
var err="";
var vars = Array();

if (isNaN(document.getElementById("qta_"+myid).value) || Trim(document.getElementById("qta_"+myid).value) == '' || document.getElementById("qta_"+myid).value < 0) { 
//alert ('Inserire correttamente la Quantità');
err+="Inserire correttamente la Quantità\n";
ok = false;
}

if (document.getElementById("sconto1_"+myid).value != '' && (isNaN(document.getElementById("sconto1_"+myid).value) || document.getElementById("sconto1_"+myid).value>99 || document.getElementById("sconto1_"+myid).value<0)) { 
//alert ('Inserire correttamente SCONTO 1');
err+="Inserire correttamente SCONTO 1\n";
ok = false;
}
if (document.getElementById("sconto2_"+myid).value != '' && (isNaN(document.getElementById("sconto2_"+myid).value) || document.getElementById("sconto2_"+myid).value>99 || document.getElementById("sconto2_"+myid).value<0)) { 
//alert ('Inserire correttamente SCONTO 2');
err+="Inserire correttamente SCONTO 2\n";
ok = false;
}
if (document.getElementById("sconto3_"+myid).value != '' && (isNaN(document.getElementById("sconto3_"+myid).value) || document.getElementById("sconto3_"+myid).value>99 || document.getElementById("sconto3_"+myid).value<0)) { 
//alert ('Inserire correttamente SCONTO 3');
err+="Inserire correttamente SCONTO 3\n";
ok = false;
}

if (isNaN(document.getElementById("valuni_"+myid).value) || Trim(document.getElementById("valuni_"+myid).value) == '' || document.getElementById("valuni_"+myid).value < 0) { 
//alert ('Inserire correttamente il Valore Unitario');
err+="Inserire correttamente il Valore Unitario\n";
ok = false;
}

if (Trim(document.getElementById("tipric_"+myid).value) == '') { 
//alert ('Inserire la tipologia dell\' articolo');
err+="Inserire la tipologia dell'articolo\n";
ok = false;
}

if (ok != false) {

var default_flfattu = document.getElementById("default_flfattu_"+myid).value;
if ((document.getElementById("fatt_"+myid).checked == false && default_flfattu == 'S') || (document.getElementById("fatt_"+myid).checked == true && default_flfattu != 'S')) {
if (default_flfattu == 'S') ok = window.confirm ("Non si sta fatturando l\'articolo, continuare?");
else ok = window.confirm ("Si sta fatturando l\'articolo, continuare?");
}

}

if (ok==true) {
	
	
vars[0] = document.getElementById("tipart_"+myid).value;
vars[1] = document.getElementById("codart_"+myid).value;
vars[2] = document.getElementById("unimis_"+myid).value;
vars[3] = document.getElementById("mod_"+myid).value;
vars[4] = document.getElementById("tipric_"+myid).value;
vars[5] = document.getElementById("qta_"+myid).value;
vars[6] = document.getElementById("valuni_"+myid).value;
vars[7] = document.getElementById("iva_"+myid).value;
vars[8] = document.getElementById("sconto1_"+myid).value;
vars[9] = document.getElementById("sconto2_"+myid).value;
vars[10] = document.getElementById("sconto3_"+myid).value;
vars[11] = document.getElementById("codmag_"+myid).value;
if (document.getElementById("fatt_"+myid).checked) fatt = "S";
else fatt = "N";
vars[12] = fatt;

 var mydiv = document.getElementById("ric_wait_div");
 mydiv.innerHTML = msg_waiting();
 agent.call('','ins_ric','ins_ric_ret', vars);
} else {
 if (err!="") alert(err);
 return false;
}

}


function ins_ric_ret(ret) {
 //agg.varie
 var arr1 = Array();
 var arr1 = ret[0];
 var warnings = ret[1];
 var indice = ret[2];
 if (arr1[0]==1) {
	var prima = document.form1.tot_varie.value*1;
 	var dopo = prima - arr1[1] + arr1[2];
 	document.form1.tot_varie.value = dopo;
 }
 
 var conferma = true;
 if (warnings!="") conferma = window.confirm(warnings);
 
 if (conferma==true) mostra_carrello(1);
 else ric_del (indice);
}


function ric_del (indice) {
 var mydiv = document.getElementById("ric_wait_div");
 mydiv.innerHTML = msg_waiting();
 agent.call('','ric_del','ric_del_ret', indice);
}
function ric_del_ret(ret) {
 //agg.varie
 var arr1 = Array();
 var arr1 = ret[0];
 if (arr1[0]==1) {
  var prima = document.form1.tot_varie.value*1;
  var dopo = prima - arr1[1];
  if (dopo < 0) dopo = 0;
  document.form1.tot_varie.value = dopo;
 }
 mostra_carrello(1);
}


function ric_del2 (indice) {
 var mydiv = document.getElementById("ric_wait_div");
 mydiv.innerHTML = msg_waiting();
 agent.call('','ric_del','ric_del2_ret', indice);
}
function ric_del2_ret(ret) {
 //agg.varie
 var arr1 = Array();
 var arr1 = ret[0];
 //mostra_carrello2(0,"cli");
}




function aggiorna_importi_ric_ajax () {

 var tot_intD_Cons = document.getElementById("tot_intD_Cons").value;
 var tot_intD_Ric = document.getElementById("tot_intD_Ric").value;
 document.form1.tot_ricambi.value = tot_intD_Ric;
 document.form1.tot_consumabili.value = tot_intD_Cons;
 totali('cercatela');
}

function calc1_ajax() {
 var tot_iva_pezzi = document.getElementById("tot_iva_pezzi").value;
 document.form1.ric_impiva.value = tot_iva_pezzi;
 aggiorna_importi_ric_ajax ();
} 


function msg_waiting() {
 //var msg = "Caricamento in corso, attendere prego...";
 var msg = '<img src="../images/ajax-loader_small.gif" alt="Loading" />';
 return msg;
}
function msg_waiting_vuoto() {
 return "&nbsp;";	
}



function impostaz_filtri() {
	var conf_age_contact_solo_asse = document.formsystem.conf_age_contact_solo_asse;
	var conf_age_contact_vis_nonasse = document.formsystem.conf_age_contact_vis_nonasse;
	var conf_tele_contact_solo_asse = document.formsystem.conf_tele_contact_solo_asse;
	var conf_tele_contact_vis_nonasse = document.formsystem.conf_tele_contact_vis_nonasse;
	var p_age_contact_1 = document.getElementById("p_age_contact_1");
	var p_tele_contact_1 = document.getElementById("p_tele_contact_1");
	if(conf_age_contact_solo_asse.checked==false) {
		conf_age_contact_vis_nonasse.disabled=true;
		p_age_contact_1.style.color="#999999";
	} else {
		conf_age_contact_vis_nonasse.disabled=false;
		p_age_contact_1.style.color="#000000";
	}
	if(conf_tele_contact_solo_asse.checked==false) {
		conf_tele_contact_vis_nonasse.disabled=true;
		p_tele_contact_1.style.color="#999999";
	} else {
		conf_tele_contact_vis_nonasse.disabled=false;
		p_tele_contact_1.style.color="#000000";
	}
}



function anag_showdiv(mydiv) {

 var arr_div = new Array('anag_daticont', 'anag_interni', 'anag_schetecsoft', 'anag_schetecrete', 'anag_parcmacest', 'anag_atti');
 var mydisp="";
 document.getElementById("whatTab").value = mydiv;
 for( var i =0; i <arr_div.length; i++) {
  if (arr_div[i]==mydiv) {
	  mydisp = "block";
	  mynewblockname = arr_div[i];
  } else {
	  mydisp = "none";
	  document.getElementById('tabmenu_item_'+arr_div[i]).className="";
  }
  document.getElementById(arr_div[i]).style.display=mydisp;
 }
 document.getElementById('tabmenu_item_'+mynewblockname).className="item_active";
 
}

function set_last_div_open(myid) {
 if (document.getElementById(myid).style.display=="block") document.getElementById("LastDivOp").value = myid;
 else document.getElementById("LastDivOp").value = "";
}


function email_intervento () {
	var annocom = document.form_email_int.annocom.value;
	var tipdoc = document.form_email_int.tipdoc.value;
	var numdoc = document.form_email_int.numdoc.value;
	var emailto = document.form_email_int.emailto.value;

	//recupero indirizzi predefiniti
	var n_preset_email = document.form_email_int.n_preset_email.value;
	var preset_emails = Array();
	var n_ok_email = 0;
	for (c=0;c<n_preset_email;c=c+1) {
	 if (document.getElementById("emailto_preset_"+c).checked) {
		 preset_emails[n_ok_email] = document.getElementById("emailto_preset_"+c).value;
		 n_ok_email=n_ok_email+1;
	 }
	}
	//if (controlla_email(emailto)) {
	document.form_email_int.inviaemail_ajax.value=" Attendere prego... ";
	document.form_email_int.inviaemail_ajax.disabled=true;
	agent.call('','email_intervento','email_intervento_ret', annocom, tipdoc, numdoc, emailto, preset_emails);
}
function email_intervento_ret (ret) {
	//alert(ret);
	if (ret.substr(0, 10) != "__RETURN__") alert (ret);
	else {
		var emails = ret.substr(10);
		document.getElementById('txt_email_inv').innerHTML = "Email inviata a: "+emails;
		document.form_email_int.emailto.value="";
	}
	document.form_email_int.inviaemail_ajax.value=" INVIA EMAIL ";
	document.form_email_int.inviaemail_ajax.disabled=false;
}

function set_trimestre (dal_al, anno_id) {
 var arr_date = dal_al.split(",");
 var dal = arr_date[0];
 var al = arr_date[1];
 var anno_trim = document.getElementById(anno_id).value;
 document.formcerca.dal.value=dal+"/"+anno_trim;
 document.formcerca.al.value=al+"/"+anno_trim;
 document.formcerca.submit();
}

function ordine_canc (cosa, annocom, tipdoc, numdoc) {
 if (!window.confirm('Eliminare la richiesta di Ordine selezionata?')) return false;
 agent.call('','ordine_canc','ordine_canc_ret', cosa, annocom, tipdoc, numdoc);
}
function ordine_canc_ret (ret) {
 if (ret.substr(0,10) != "__RETURN__") {
  alert(ret);
 } else {
  //alert(ret);
  ret = ret.substr(10);
  var arr_ret = ret.split("__");
  var cosa = arr_ret[0];
  var annocom = arr_ret[1];
  var tipdoc = arr_ret[2];
  var numdoc = arr_ret[3];
  var matricola = arr_ret[4];
  if (cosa=="lista_ordini") {
	  var mydiv = document.getElementById("row_"+annocom+"_"+tipdoc+"_"+numdoc);
	  var mydiv2 = document.getElementById("row2_"+annocom+"_"+tipdoc+"_"+numdoc);
	  mydiv.style.display='none';
	  mydiv2.style.display='none';
  } else {
	  window.location="matricole.php?okord=2&matricola="+matricola;  
  }
  
 }
}

function lista_ordiniD (annocom, tipdoc, numdoc) {

 var exp_img = document.getElementById("img_"+annocom+"_"+tipdoc+"_"+numdoc);
 var flagexp = document.getElementById("flagexp_"+annocom+"_"+tipdoc+"_"+numdoc);
 var mydiv = document.getElementById("row2_"+annocom+"_"+tipdoc+"_"+numdoc);
 var mydiv_cont = document.getElementById("row2cont_"+annocom+"_"+tipdoc+"_"+numdoc);
 if (flagexp.value==1) {
  flagexp.value = 0;
  mydiv_cont.innerHTML = '';
  exp_img.src = conf_url+"images/icons/expand.png";
 } else {
  flagexp.value = 1;
  mydiv_cont.innerHTML = msg_waiting();
  exp_img.src = conf_url+"images/icons/collapse.png";
  agent.call('','lista_ordiniD','lista_ordiniD_ret', annocom, tipdoc, numdoc);
 }
}
function lista_ordiniD_ret (ret) {
 if (ret.substr(0,10) != "__RETURN__") {
  alert(ret);	 
 } else {
  //alert(ret);
  ret = ret.substr(10);
  var arr_ret = ret.split("__");
  var annocom = arr_ret[0];
  var tipdoc = arr_ret[1];
  var numdoc = arr_ret[2];
  var content = arr_ret[3];
  var mydiv_cont = document.getElementById("row2cont_"+annocom+"_"+tipdoc+"_"+numdoc);
  mydiv_cont.innerHTML = content;
 }
}

function ord_exp_all() {
	
 var exp_img_all = document.getElementById("img_exp_all");
 var flagexp_all = document.getElementById("flagexp_all");

 var count_rows = document.getElementById('count_rows').value;
 var mykey = "";
 var arrkey = Array();
 for (c=1;c<=count_rows;c=c+1) {

  mykey = document.getElementById('hid_key_'+c).value;
  arrkey = mykey.split(",");
  
  document.getElementById("flagexp_"+arrkey[0]+"_"+arrkey[1]+"_"+arrkey[2]).value=flagexp_all.value;
  //alert("imposto ext = "+flagexp_all.value);
  
  //alert(arrkey[0]+", "+arrkey[1]+", "+arrkey[2]);
  lista_ordiniD(arrkey[0],arrkey[1],arrkey[2]);
 }
 
 if (flagexp_all.value==1) {
  flagexp_all.value = 0;
  exp_img_all.src = conf_url+"images/icons/expand.png";
 } else {
  flagexp_all.value = 1;
  exp_img_all.src = conf_url+"images/icons/collapse.png";
 }
 
}



function set_agenda_filtro_tec(siono) {
 document.form_agenda.saf.value = siono;
 document.form_agenda.submit();	
}

function chk_sel_all(cod, quanti, onoff) {
 var checked_ctrl = false;
 if (onoff==1) checked_ctrl = true;
 for (c=1;c<=quanti;c=c+1) {
	document.getElementById('chk_'+cod+'_'+c).checked=checked_ctrl; 
 }
}

function tecnici_gruppi_check () {
 var err = "";
 var CODGRUPold = document.getElementById('CODGRUPold').value;
 var CODGRUP = Trim(document.getElementById('CODGRUP').value);
 var DESGRUP = Trim(document.getElementById('DESGRUP').value);
 if (CODGRUP=="new") err = "Attenzione! Non e' possibile usare il codice 'new'";
 if (Trim(CODGRUP)=="" || Trim(DESGRUP)=="") err = "Inserisci Codice e Descrizione";
 
 if (err!="") {
	 alert(err);
	 return false;
 } else {
	agent.call('','tecnici_gruppi_check','tecnici_gruppi_check_ret', CODGRUPold, CODGRUP);
 }
 
}

function tecnici_gruppi_check_ret(ret) {
 if (ret!="__RETURN__") {
	 alert(ret);
 } else {
	document.getElementById("form_tecnici_gruppi").submit(); 
 }
}


function record_canc (cosa, id_chiave) {
 var arr_chiave = Array();
 var arr_altridati = Array();
 if (cosa=="tecnici_gruppi") {
	var id = document.getElementById(id_chiave+"_id").value;
	arr_chiave[0] = id;
 } else if (cosa=="ordSemi") {
	var appoid_chiave = id_chiave;
	var arr_idchiave = appoid_chiave.split(",");//0=matr, 1=matr_cons
	var this_ele = document.getElementById('toner_'+arr_idchiave[1]);
	arr_chiave[0] = this_ele.value;
	var matricola = document.getElementById('matricola_'+arr_idchiave[0]).value;
	arr_altridati[0] = matricola;
 }
 if (!window.confirm('Eliminare definitivamente il record selezionato?')) return false;
 agent.call('','record_canc','record_canc_ret', cosa, id_chiave, arr_chiave, arr_altridati);
}
function record_canc_ret (ret) {
 if (ret.substr(0,10) != "__RETURN__") {
  alert(ret);
 } else {
  //alert(ret);
  ret = ret.substr(10);
  var arr_ret = ret.split("__");
  var cosa = arr_ret[0];
  var id_chiave = arr_ret[1];
  if (cosa=="tecnici_gruppi") {
   var mydiv = document.getElementById(id_chiave);
   mydiv.style.display='none';

  } else if (cosa=="ordSemi") {
   var arr_idchiave = id_chiave.split(",");//0=matr, 1=matr_cons
   var mydiv = document.getElementById('span_ordCanc_'+arr_idchiave[1]);
   //mydiv.style.display='none';
   mydiv.innerHTML='Ordine annullato!';
  }//cosa
 }
}

function ordine_semi (idmatr, quanti_toner) {
 global_vars['ordS_idmatr'] = idmatr;
 var imgSpan = "span_ord_"+idmatr;
 var imgSpanW = "span_ordW_"+idmatr;
 
 var this_ele;
 var array = new Array;
 var matricola = document.getElementById('matricola_'+idmatr).value;
 if (quanti_toner==0) return false;
 for (c=1;c<=quanti_toner;c=c+1) {
  this_ele = document.getElementById('toner_'+idmatr+'_'+c);
  if (this_ele.checked==true) {
	//alert('matri:'+idmatr+', toner:'+this_ele.value);
	array.push(this_ele.value);
  }
 }//for
 if (array.length==0) return false;
 
 ShowAndHide_lite(imgSpan, imgSpanW);
 agent.call('','crea_ordine_semiauto','ordine_semi_ret', matricola, array);
}
function ordine_semi_ret (ret) {
 //document.getElementById('temp_ret').innerHTML = ret;
 if (ret.substr(0,10) != "__RETURN__") {
  alert(ret);
  var imgSpan = "span_ord_"+global_vars['ordS_idmatr'];
  var imgSpanW = "span_ordW_"+global_vars['ordS_idmatr'];
 } else {
  ret = ret.substr(10);
  var arr_ret = ret.split("__");
  //var ret1 = arr_ret[0];
  alert("Ordine Inserito Correttamente");
  //window.location.reload();
  document.getElementById('formcerca').submit();
 }
}

function waiting_msg() {
 return '<img src="../images/ajax-loader_small.gif" alt="please wait" />';
}

