// JavaScript Document
// ______________________________________________________________________________________________________________________________
// funzioni jquery 
arrotonda = function(numero, quantidecimali, come){
	numero = String(numero);
	
	arrNum = numero.split(".");
	intero = arrNum[0];
	decimali = arrNum[1];
	
	if(quantidecimali>0)
	{
		cifra_arrotonda = decimali.charAt(quantidecimali-1)*1;
		cifra_dopo = decimali.charAt(quantidecimali)*1;
		if(cifra_dopo>=5 && come!="difetto")
			cifra_arrotonda = cifra_arrotonda+1;
	
		numeroRit = intero+"."+decimali.slice(0,(quantidecimali-1))+cifra_arrotonda;
		numeroRit = numeroRit*1
	}
	else
	{
		primodec = decimali.charAt(quantidecimali)*1;
		posUnita = (intero.length)-1*1;
		unita = intero.charAt(posUnita)*1;
		if(primodec>=5 && come!="difetto")
			unita = unita+1;
		numeroRit = intero.substr(0,(posUnita))+unita;
		numeroRit = numeroRit*1
	}
	
	return numeroRit
}


waitElement = function(quale){
	if(quale=="" || quale==undefined)
		quale = "div.waitElement";

	if($(quale).css("display")=="none"){
		$(quale).css("display","inline");
		$(quale).animate({ left: "0px" }, "normal");
		return true;
	}
	else{
		$(quale).animate({ left: "-3000px" }, "fast");
		$(quale).css("display","none");
		return false;
	}	
}

// ______________________________________________________________________________________________________________________________
// funzioni js 

function in_array(string, array){
   for (i = 0; i < array.length; i++)
   {
      if(array[i] == string)
      {
         return true;
      }
   }
return false;
}

function checkdateformat(userinput){
	var dateformat = /^\d{2}\/\d{2}\/\d{4}$/
	return dateformat.test(userinput) //returns true or false depending on userinput
}

function checkhourformat(userinput){
	var hourformat = /^\d{2}\:\d{2}$/
	return hourformat.test(userinput) //returns true or false depending on userinput
}

function checkFormattazione(valore, tipo){
	switch (tipo) {
		case 'az': // caratteri semplici [a-z] e spazi
			regExp=/^([a-zA-Z \-]+)$/;
			error=2;
		break;
		case '09': // caratteri numerici [0-9] non negativo
			regExp=/(^\d\d*$)/;
			error=3;
		break;
		case 'az09': // char-num
			regExp=/^([a-zA-Z0-9]+)$/;
			error=4;
		break;
		case 'az09_': // char-num
			regExp=/^([a-zA-Z0-9_]+)$/;
			error=4;
		break;
		case 'az09_ ': // char-num
			regExp=/^([a-zA-Z0-9_ ]+)$/;
			error=4;
		break;
		case 'az09trim': // char-num no spazi
			regExp=/^([a-zA-Z0-9_]+)$/;
			error=4;
		break;
		case 'dec': // decimale -[0-9\.\,] anche negativo
			regExp=/(^-?\d\d*\.\d*$)|(^-?\d\d*\,\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;
			error=5;
		break;
		case 'int': // numero intero anche negativo
			regExp=/(^-?\d\d*$)/;
			error=6;
		break;
		case 'txt': // caratteri standard ,אטילעש,',",&,+,-,?,=,(,),*,/,@,#,:,;,.,,
			regExp=""; 
			//regExp=/^([a-zA-Z0-9 אטילעשח\'\"\&\+\-\?\!\=\(\)\*\/\@\:\;\.\,\_\r\n]+)$/;
			error=7;
		break;
		case 'name': // Nome e Cognome: solo caratteri standard e spazi
			regExp=/^([a-zA-Z אטילעש\']+)$/;
			error=8;
		break;
		case 'pwd': // Password: solo caratteri standard e underscore @ - .
			regExp=/^([a-zA-Z0-9_\@\.\-]{6,10})$/;
			error=9;
		break;
		case 'email': // email xxx@yyy.zzz
			regExp=/^([a-zA-Z0-9_\.\-]{2,})+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z]{2,4})$/;
			error=10;
		break;
		case 'cap': //US ZIP CODE:  99999 or 99999-9999
			regExp=/(^\d{5}$)|(^\d{5}-\d{4}$)/;
			error=11;
		break;
		case 'cf': // Codice Fiscale: 11 numeri oppure 16 caratteri maiuscoli
			regExp=/(^\d{11}$)|(^[A-Z]{6}\d{2}[A-Z]{1}\d{2}[A-Z]{1}\d{3}[A-Z]{1}$)/;
			error=12;
		break;
		case 'piva': // Partita iva 11 digits
			regExp=/^\d{11}$/;
			error=13;
		break;
		case 'tel': //Telefono con o senza prefisso internaz.
			regExp=new RegExp("^([+]?)([0-9]{5,15})$");
			error=14;
		break;
		/*
		case 'date':
			if (!dateSuffix || dateSuffix=="IT" || dateSuffix=="EN") regExp=/^\d{1,2}(\-|\/)\d{1,2}\1\d{4}$/;
			else regExp=/^\d{4}(\-|\/)\d{1,2}\1\d{1,2}$/;
			error=15;
		break;
		case 'dateIT':
			regExp=/^\d{1,2}(\-|\/)\d{1,2}\1\d{4}$/;
			error=15;
		break;
		case 'dateEN':
			regExp=/^\d{1,2}(\-|\/)\d{1,2}\1\d{4}$/;
			error=15;
		break;
		case 'datePC':
			regExp=/^\d{4}(\-|\/)\d{1,2}\1\d{1,2}$/;
			error=15;
		break;
		*/
		case 'euro': // VALUTA EURO con virgola e due decimali
			regExp=/^(\d\d*)\,(\d){2}$/;
			error=16;
		break;
		case 'ccard': // CREDIT CARD : 20 numeri
			regExp=/^[0-9]{20}$/;
			error=17;
		break;
		case 'IP': // IP ADDRESS 
			regExp=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
			error=18;
			//regExp=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
		break;
		case 'url': // url solo caratteri semplici, numeri e ?&=:._-
			regExp=/^([a-zA-Z0-9\#\.\:\_\-\/\&\?\=\%]+)$/;
			//regExp=(^|[ \t\r\n])((http|https): (([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]));
			//regExp=(^|[ \t\r\n])((ftp|http|https|gopher|mailto|news|nntp|telnet|wais|file|prospero|aim|webcal): (([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]));
			error=19;
		break;
		case 'uri': // uri solo caratteri semplici, numeri e _-
			if (currField.value.substring(0,7)=="http://") regExp=/^([a-zA-Z0-9 \#\.\:\_\-\/\&\?\=\%]+)$/;
			else regExp=/^([a-zA-Z0-9\_\-]+)$/;
			//regExp=(^|[ \t\r\n])((http|https): (([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]));
			//regExp=(^|[ \t\r\n])((ftp|http|https|gopher|mailto|news|nntp|telnet|wais|file|prospero|aim|webcal): (([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]));
			error=20;
		break;
		default: regExp=false;
	}
	if (regExp && error) {
		if (!regExp.test(valore)) {
			return false;
		} else {
			return true;
		}
	} else {
		return false;
	}
}

// JavaScript Document
function genericPop(myUrl,myWinName,myWidth,myHeight,myPars) {
	var winl = (screen.width - myWidth) / 2;
	var wint = (screen.height - myHeight) / 2;
	parameters = myPars + '';
	if (parameters == '') parameters = ',toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no';
	gwin=window.open(myUrl,myWinName,'width='+myWidth+',height='+myHeight+',left='+winl+',top='+wint+parameters);
	gwin.focus();
}

function giorni_differenza(data1,data2, lingua){
	data1 = str_replace("/","",data1);
	data2 = str_replace("/","",data2);
	if(data1.length>8)
		data1 = data1.substr(0,8);
	if(data2.length>8)
		data2 = data2.substr(0,8);
	
	if(lingua==undefined || lingua=="ita"){
		anno1 = parseInt(data1.substr(4,4));
		mese1 = parseInt(data1.substr(2,2));
		giorno1 = parseInt(data1.substr(0,2));
	
		anno2 = parseInt(data2.substr(4,4));
		mese2 = parseInt(data2.substr(2,2));
		giorno2 = parseInt(data2.substr(0,2));
	} else if(lingua=="eng"){
		anno1 = parseInt(data1.substr(0,4));
		mese1 = parseInt(data1.substr(4,2));
		giorno1 = parseInt(data1.substr(6,2));
	
		anno2 = parseInt(data2.substr(0,4));
		mese2 = parseInt(data2.substr(4,2));
		giorno2 = parseInt(data2.substr(6,2));
	}

    var dataok1=new Date(anno1, mese1-1, giorno1);
	var dataok2=new Date(anno2, mese2-1, giorno2);
	differenza = dataok1-dataok2;    
	giorni_diff = new String(differenza/86400000);
	//alert(dataok1+"\n"+dataok2+"\n"giorni_diff);
	
	return giorni_diff*1;
}

function number_format( number, decimals, dec_point, thousands_sep ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
 
    var n = number, prec = decimals, dec = dec_point, sep = thousands_sep;
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    sep = sep == undefined ? ',' : sep;
 
    var s = n.toFixed(prec),
        abs = Math.abs(n).toFixed(prec),
        _, i;
 
    //if (abs > 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;
 
        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
 
        s = _.join(dec || '.');
   // }
 
    return s;
}

/*
function trim(stringa){
	stringa = String(stringa);
    while (stringa.substring(0,1) == ' '){
        stringa = stringa.substring(1, stringa.length);
    }
    while (stringa.substring(stringa.length-1, stringa.length) == ' '){
        stringa = stringa.substring(0,stringa.length-1);
    }
    return stringa;
}*/

function print_r(theObj){
	stampa = ""
  if(theObj.constructor == Array ||
     theObj.constructor == Object){
    stampa += "<ul>\n"
    for(var p in theObj){
      if(theObj[p].constructor == Array || theObj[p].constructor == Object){
		stampa +="\n <li>["+p+"] => "+typeof(theObj)+"</li>"
        stampa +="\n<ul>"
        print_r(theObj[p]);
        stampa +="\n</ul>"
      }
	  else {
		stampa +="\n <li>["+p+"] => "+theObj[p]+"</li>";
      }
    }
    stampa +="\n</ul>"
  }
  
  return stampa
}


function stampaData(timeStamp, lingua, modo){
	giorno = timeStamp.substr(8,2);
	mese = timeStamp.substr(5,2);
	anno = timeStamp.substr(0,4);
	ora = timeStamp.substr(11,2);
	minuti = timeStamp.substr(14,2);
	sec = timeStamp.substr(17,2);
	
	if(modo==1)
	{
		rit = giorno+"/"+mese+"/"+anno+" "+ora+":"+minuti+":"+sec;
	}
	
	return rit;
}

function str_replace (search, replace, subject, count) {
    // Replaces all occurrences of search in haystack with replace  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/str_replace
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order
    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'
    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }
 
    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}

function trim(str, chars) {
	if(str==undefined)
		return "";
	if(chars==undefined)
		chars = "&nbsp;";
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

