var _COSTANTE_NOT_LOGGED = "N#O#T#L#O#G#G#E#D";
var _COSTANTE_LOGIN = "default.php";

     function pId(id_elemento) {
			var elemento;
			if(document.getElementById)
				elemento = document.getElementById(id_elemento);
			else
				elemento = document.all[id_elemento];
			return elemento;
		};
     
        function setCookie(sNome, sValore, iGiorni) {
		var dtOggi = new Date()
		var dtExpires = new Date()
		dtExpires.setTime
		(dtOggi.getTime() + 24 * iGiorni * 3600000);
		document.cookie += sNome + "=" + escape(sValore) + "; expires=" + dtExpires.toGMTString();
	}

function getCookie(NameOfCookie)
{

// Prima controlliamo se c'è  un cookie memorizzato.
// Altrimenti la lunghezza del document.cookie sarebbe zero.

if (document.cookie.length > 0)
{

begin = document.cookie.indexOf(NameOfCookie+"=");
if (begin != -1) 
{

begin += NameOfCookie.length+1;
end = document.cookie.indexOf(";", begin);
if (end == -1) end = document.cookie.length;
return unescape(document.cookie.substring(begin, end)); 
}
}
return null;

}
 

function isLegal(input, legalchars) {
	var ok = true;
	var chr = null;
	var i = 0;
	
	for (i=0; (i<input.length) && (ok); i++) {
		chr = input.charAt(i);
		ok = (legalchars.indexOf(chr,0) != -1);
	}
	return ok;
}

function eliminaSpazi(input) {
	var i = 0;
	var out = "";
	for (i=0; (i<input.length); i++) {
		chr = input.charAt(i);
		if( chr != " " )
		   out = out + chr; 
	}
	return out;
}


function isNotLegal(input, illegalchars) {
	var ok = false;
	var chr = null;
	var i = 0;

	for (i=0; (i<input.length) && (!ok); i++) {
		chr = input.charAt(i);
		ok = (illegalchars.indexOf(chr,0) != -1);
		   
	}
	return  ok;
}


function CheckLength(input, maxlen) {
	
	if (input.length > maxlen ) 
	    return false;
		
	return  true;
}


function CheckMinLength(input, minlen) {
	
	if (input.length < minlen ) 
	    return false;
		
	return  true;
}



function isblank(s) {
	for ( var i=0; i<s.length; i++ ) {
   	var c = s.charAt(i)	;
   	if ( (c != ' ') && (c != '\n') && (c != '\t') )  return false;
	}
	return true;

}

function testNumerico(formfield) {
	var ok = true;
	if (!isblank(formfield.value)) {
		if (!(isLegal(formfield.value, "0123456789,"))) {
			ok = false;
			formfield.focus();
		}
	}
	return(ok);
}

function testIntero(formfield) {
	var ok = true;
	if (!isblank(formfield.value)) {
		if (!(isLegal(formfield.value, "0123456789"))) {
			ok = false;
			formfield.focus();
		}
	}
	return(ok);
}


function checkEmail(input)
{
   var ok=false;
   var i=0;
   var charToSearch = '@';
   for (i=0; (i<input.length) && (ok==false); i++) 
	{
		chr = input.charAt(i);
		if ( chr == charToSearch ) 
		     if( charToSearch == '@') 
		         charToSearch = '.';
		     else
		         ok=true;
	}
	
   return(ok);
}



function checkDate(string) 
{
	// Verifica che una stringa sia nel formato gg/mm/aaaa
	if (typeof(string)!="string") return false;
	var dateArray=string.match(/^\s*(\d+)\/(\d+)(\/(\d+))?\s*$/);
	if (dateArray==null) return false;
	var d=new Date();
	var gg=parseInt(dateArray[1],10);
	var mm=parseInt(dateArray[2],10);
	var aa=((dateArray[3]=="" || typeof(dateArray[3])!="string")?(d.getFullYear()):(parseInt(dateArray[4],10)));
	var dd=(mm==2)?((aa%4)?(28):(((!(aa%100))&&(aa%400))?(28):(29))):(((mm==4)||(mm==6)||(mm==9)||(mm==11))?(30):(31));
	return ((gg>=1)&&(gg<=dd)&&(aa>999)&&(mm>=1)&&(mm<=12));
}

//first e second sono le stringhe data
function dateDiff(firstdate,seconddate ) {
date1 = new Date();
date2 = new Date();
diff  = new Date();

if( checkDate(firstdate) ) 
{ 
date1temp = new Date(firstdate.substring(6,10), parseInt(firstdate.substring(3,5), 10)-1,firstdate.substring(0,2));
date1.setTime(date1temp.getTime());
}
else return 1000; // otherwise exits

if ( checkDate(seconddate))
{
date2temp = new Date(seconddate.substring(6,10), parseInt(seconddate.substring(3,5),10)-1,seconddate.substring(0,2));
date2.setTime(date2temp.getTime());
}
else return 1000; // otherwise exits

// sets difference date to difference of first date and second date

diff.setTime(Math.abs(date1.getTime() - date2.getTime()));

timediff = diff.getTime();

weeks = Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));
timediff -= weeks * (1000 * 60 * 60 * 24 * 7);

days = Math.floor(timediff / (1000 * 60 * 60 * 24)); 
timediff -= days * (1000 * 60 * 60 * 24);

return  7*weeks + days; 
}


function checkMail(stringa) 
{
	if (typeof(stringa)!="string") return false;
	//var espressione = new RegExp('(([\w]+:)?//)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?');
	var espressione = new RegExp("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+[\.]([a-z0-9-]+)*([a-z]{2,3})$");
	if( espressione.test(stringa))
	    return true;
	return false;
}
    

function ControllaData(giorno,mese,anno) 
{
    var datatocheck;
	datatocheck="";
	if ( giorno.length == 1 ) 
	     datatocheck = "0" + giorno;
	else
         datatocheck = giorno;
    datatocheck = datatocheck  + "/";

	if ( mese.length == 1 ) 
	     datatocheck = datatocheck  + "0" + mese;
	else
         datatocheck = datatocheck + mese;
    datatocheck = datatocheck  + "/";
    datatocheck = datatocheck  + anno;

	return checkDate(datatocheck);

}


function getScrollTop()
{
	if (document.documentElement && document.documentElement.scrollTop)
// IE6 +4.01 and user has scrolled
		return document.documentElement.scrollTop;
	else if (document.body && document.body.scrollTop)
	     return document.body.scrollTop;
	else
	     return 0;
}

function getScrollLeft()
{
	if (document.documentElement && document.documentElement.scrollLeft)
// IE6 +4.01 and user has scrolled
		return document.documentElement.scrollLeft;
	else if (document.body && document.body.scrollLeft)
	     return document.body.scrollLeft;
	else
	     return 0;
}

function lz(numero, cifre) {
	n = String(numero);
	while (n.length<cifre) { 
		n="0"+n 
	}
	return n;
}
//formatta da g/m/y a gg/mm/yyyy
function formatDataOut(data){

	var gio = data.substring(0, data.indexOf("/")) + "/";
	data = data.substring(data.indexOf("/") + 1);
	var mese = data.substring(0, data.indexOf("/")) + "/";
	data = data.substring(data.indexOf("/"));
	var anno = data.substring(1);
	
	
	//alert("mese: " + mese+" ---- giorno: "+gio+"  ---- " + " anno: "+anno);
	//alert((mese.substring(0, mese.length - 1)+"_"));
	if (parseInt(gio.substring(0, gio.length - 1), 10) > 0 && parseInt(mese.substring(0, mese.length - 1), 10) > 0 && parseInt(anno, 10) > 0) 
	{
		if( gio.length == 2)
	    	gio = "0"+gio;
		if( mese.length == 2)
		    mese = "0"+mese;
		return gio + mese + anno;
	}
	else
       return "";
}




function dateFormat(data, formato){

	var giorni = new Array("Domenica", "Luned�", "Marted�", "Mercoled�", "Gioved�", "Venerd�", "Sabato");
	var mesi = new Array("Gennaio", "Febbraio", "marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre");
	
	// preparo la data...  verificare di passarla corretta!
	var adesso = new Date(data);
	var anno = adesso.getFullYear();
	var mese = adesso.getMonth() + 1;
	var giorno = adesso.getDate();
	var settim = adesso.getDay()
	var ore = adesso.getHours()
	var minuti = adesso.getMinutes()
	var secondi = adesso.getSeconds()
	
	// preparo la stringa di risposta
	var rVal = '';
	
	if (formato.length == 0) {
		// assenza del secondo parametro
		return String(adesso);
	}
	else {
	
		// inizio loop
		while (formato.length > 0) {
		
			// verifico se c'e' qualche separatore e lo aggiungo
			while (formato.length > 0 && String("ymdphnst").indexOf(formato.charAt(0).toLowerCase()) < 0) {
				rVal += formato.charAt(0);
				formato = formato.substr(1);
			}
			
			
			// Separo il gruppo
			if (formato.length > 0) {
				ff = formato.charAt(0);
				formato = formato.substr(1);
				while (formato.length > 0 && formato.charAt(0).toLowerCase() == ff.charAt(0).toLowerCase()) {
					ff += formato.charAt(0);
					formato = formato.substr(1);
				}
				
				// espando il formato nella stringa corrispondente
				ff = ff.toLowerCase(); // operazione preliminare... tutto in minuscolo
				switch (ff) {
					case "yy":
						rVal += String(anno).substr(2);
						break;
					case "yyyy":
						rVal += String(anno);
						break;
					case "m":
						rVal += String(mese);
						break;
					case "mm":
						rVal += lz(mese, 2);
						break;
					case "mmm":
						rVal += mesi[mese - 1].substr(0, 3);
						break;
					case "mmmm":
						rVal += mesi[mese - 1];
						break;
					case "d":
						rVal += String(giorno);
						break;
					case "dd":
						rVal += lz(giorno, 2);
						break;
					case "ddd":
						rVal += giorni[settim].substr(0, 3);
						break;
					case "dddd":
						rVal += giorni[settim];
						break;
					case "p":
						var inizio = new Date(anno, 0, 0);
						rVal += Math.floor((adesso - inizio) / 86400000);
						break;
					case "ppp":
						var inizio = new Date(anno, 0, 0);
						rVal += lz(Math.floor((adesso - inizio) / 86400000), 3);
						break;
					case "h":
						rVal += String(ore);
						break;
					case "hh":
						rVal += lz(ore, 2);
						break;
					case "n":
						rVal += String(minuti);
						break;
					case "nn":
						rVal += lz(minuti, 2);
						break;
					case "s":
						rVal += String(secondi);
						break;
					case "ss":
						rVal += lz(secondi, 2);
						break;
					case "t":
						rVal += lz(ore, 2) + ":" + lz(minuti, 2) + ":" + lz(secondi, 2);
						break;
					default: // il numero dei caratteri del formato non e' permesso
						rVal += ff.replace(/./gi, "?");
				}
				
			}
			
		} // fine loop principale
		return rVal;
	}
}	
	
	function evidenziaErrore(oggetto)
	{
		if (oggetto) 
			oggetto.style.backgroundColor = "#FAC074";
			oggetto.style.borderColor  = "#9A450C";
			oggetto.style.borderWidth  = "medium";
			oggetto.style.fontWeight = "bold";
	}
	
	function annullaEvidenziaErrore(oggetto)
	{
		if (oggetto) 
			oggetto.style.backgroundColor = "";
			oggetto.style.borderColor  = "";
			oggetto.style.borderWidth  = "";
			oggetto.style.fontWeight = "";
	}
 
	function EvidenziaCampi(  )
	{
		myarr = pId("_fieldscheckedlast").value.split("-");
		for( idx = 0; idx < myarr.length; idx++)
		{
			if (pId(myarr[idx])) {
				annullaEvidenziaErrore(pId(myarr[idx]));
			}
		}
		myarr = pId("_fieldschecked").value.split("-");
		for( idx = 0; idx < myarr.length; idx++)
		{
			if (pId(myarr[idx])) {
				evidenziaErrore(pId(myarr[idx]));
			}
		}
		pId("_fieldscheckedlast").value = pId("_fieldschecked").value;
	}

	
	function checkLogin(r)
	{
		nocl();
		if( r.indexOf( _COSTANTE_NOT_LOGGED ) >= 0)
		    location.replace(_COSTANTE_LOGIN);
	}
	
// aggiunto da PEO
function ControlloNumeroX(obj){
  var segno='' 
  if(/^-/.test(obj.value))segno='-'
  obj.value=obj.value.replace(/^-/,'')
  valore = obj.value.replace(/[^\d]/g,'').replace(/^0+/g,'')   
  nuovovalore=''
  while(valore.length>3){
    nuovovalore='.'+valore.substr(valore.length-3)+nuovovalore
    valore = valore.substr(0,valore.length-3)
  }
  obj.value=segno+valore+nuovovalore
}

function unix_time() {
var now = new Date();
return parseInt(now.getTime().toString().substring(0,10));
} 


function selezionaPerCodice(oggetto, valore)
{
	var idx=0;
	//alert("selezionepercodice");
	for (idx = 0; idx < oggetto.options.length; idx++) {
		if (oggetto.options[idx].value == valore) 
		{
			oggetto.selectedIndex = idx;
			return;
		}
	}
}


function minimizzaPromemoria()
{
   if( pId("butmin").value == "Mostra promemoria")
   {
    $("#_boxalert").slideDown("fast", function() { $("#butmin").val("Chiudi promemoria"); setCookie	( "prom", "1", 30 );
	});
   }
   else
   {
   $("#_boxalert").slideUp("fast", function() {$("#butmin").val("Mostra promemoria");  setCookie( "prom", "0", 30 );
	}); 
    }  
}


function cl()
{
	
	document.body.style.cursor='Wait' ;
	//if( pId("_validation"))  pId("_validation").value = 1;
	
}

function nocl()
{
	
	document.body.style.cursor='Default' ;
	//if( pId("_validation")) pId("_validation").value = 0;	
}

function trim11 (str) {
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}


function tasto_default( e )
{
var keynum;
var keychar;
var numcheck;

if(window.event) // IE
{
keynum = e.keyCode;
}
else if(e.which) // Netscape/Firefox/Opera
{
keynum = e.which;
}
 
if (keynum == 13) {
	if (pId("_tastodefault") && pId("_tastodefault").value!="") 
		pId(pId("_tastodefault").value).click();
}
}


// This function formats numbers by adding commas
function numberFormat(nStr, decimali){
  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' + '.' + '$2');
	if( decimali )
	return x1 + x2;
	else
  return x1;
}
	
function restituisciValoreCombo( id)
{
	if( !pId(id))
		return "";
	return pId(id).options[pId(id).selectedIndex].text;
	
} 


function cercaValoreCheck( nome, valore)
{
	var idx=0;

	var e=document.getElementsByName(nome);
	for(idx=0;idx<e.length;idx++)
	{
		if (e[idx].type == "checkbox" && e[idx].value == valore) {
			return e[idx].title;
			break;
		}
			
	}
	
	return ""; 
	//return valore; 

} 


function formattaNumeri()
{
	if( !pId("_formatted"))
		return;
		var arr = 	pId("_formatted").value.split("-");
	for( idx=0; idx < arr.length; idx++ )
	    if( pId(arr[idx])) ControlloNumeroX( pId(arr[idx]) );
}


function select_innerHTML(objeto,innerHTML){


    objeto.innerHTML = "";

    var selTemp = document.createElement("micoxselect")
    var opt;
	selTemp.style.display="none"
    selTemp.id="micoxselect1"
    document.body.appendChild(selTemp)
    selTemp = document.getElementById("micoxselect1")
    if(innerHTML.toLowerCase().indexOf("<option")<0){//se não é option eu converto
        innerHTML = "<option>" + innerHTML + "</option>"
    }
 
	innerHTML = innerHTML.replace(/<option/g,"<span").replace(/<\/option/g,"</span").replace("selected", "id=selected ");
    selTemp.innerHTML = innerHTML
      
    
    for(var i=0;i<selTemp.childNodes.length;i++){
  		var spantemp = selTemp.childNodes[i];
        if(spantemp.tagName){     
            opt = document.createElement("OPTION")
    	
   if(document.all){ //IE
    objeto.add(opt)
   }else{
    objeto.appendChild(opt)
   }       
    
   //getting attributes
	if (false) {
		for (var j = 0; j < spantemp.attributes.length; j++) {
			var attrName = spantemp.attributes[j].nodeName;
			var attrVal = spantemp.attributes[j].nodeValue;
			if (attrVal) {
				try {
					
					opt.setAttribute(attrName, attrVal);
					opt.setAttributeNode(spantemp.attributes[j].cloneNode(true));
				} 
				catch (e) {
				}
			}
		}
	}
   //value and text
   if (spantemp.id == "selected" ) {
	opt.selected = true;
   }
   opt.value = spantemp.getAttribute("value")
   opt.text = spantemp.innerHTML
  } 
 }    
 document.body.removeChild(selTemp)
 selTemp = null
}

function apriWinStampa(valore, finestra){
	if( finestra == "" )
	   window.open(valore, '_blank', "width=800,height=600,status=yes,resizable=yes,scrollbars=yes");
	else
	   window.open(valore, finestra, "width=800,height=600,status=yes,resizable=yes,scrollbars=yes");
	
}

function getBrowser()
{
	if( navigator.userAgent.indexOf("MSIE") > 0 ) 
	    return "IE";
	else
		  return "FF";
}
 
