﻿// JScript File JS/funzioni.js
filtro_spazi = /^\s*$/;     //se contine solo spazi 
//filtro_alfanum = /^[\sA-z0-9àèéòùì_\-]+$/; //admette spazi
filtro_alfanum = /^[\sA-z0-9àèéòùì_\,/()-]+$/; //admette spazi
filtro_digit = /^\d+$/;
filtro_mail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
//filtro_float = /^\d+[\,\.]\d\d?$|^\d+$/;
filtro_float = /^[-+]?[0-9]+([\,\.][0-9]+)?$/;
filtro_data = /^\d\d\/\d\d\/\d\d\d\d$/;
filtro_phone = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/
Phone_format = '\r\nlocal format (eg. 02 1234 5678 or 123 123 4567)' 
Phone_format += '\r\ninternational format (eg. +61 (0) 2 1234 5678 or +1 123 123 4567). '
Phone_format += '\r\noptional extention of up to five digits prefixed by x or ext (eg. 123 123 4567 x89).'
filtro_phone = /\(?\d{3}\)?([-\/\.])\d{3}\1\d{4}/;
filtro_phone = /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/;
Phone_format = '\r\n339-4248'
Phone_format += '\r\n339-42-48'
Phone_format += '\r\n339 42 48'
Phone_format += '\r\n339 4248'
Phone_format += '\r\n3394248'
Phone_format += '\r\n(095) #phone#'
Phone_format += '\r\n(095)#phone#'
Phone_format += '\r\n+7 (095) #phone#'
Phone_format += '\r\n+7 (095)#phone#'
Phone_format += '\r\n+7(095) #phone#'
Phone_format += '\r\n+7(095)#phone#'
filtro_phone = /D*(\d{3})\D*(\d{3})\D*(\d{4})\D*(\d*)$/;
filtro_phone = /D*(\d{3})\D*(\d{3})\D*(\d{3})\D*(\d*)$/;
filtro_phone = /D*(\d{3})\D*(\d{2})\D*(\d{2})\D*(\d{2})\D*(\d*)$/;
filtro_mailRe = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/
filtro_PIVA = /^\d{5}\d{6}$/; //controllaPIVA()
filtro_mese = /^0?[1-9]$|^1[0-2]$/;
filtro_anno = /^1[89]|^2\d\d\d$/;

filtri=new Array(   filtro_alfanum, //0 
					filtro_digit, //1
					filtro_mail, //2
					filtro_float, //3
					filtro_data, //4
					filtro_digit, //5
					filtro_mailRe,//6
					filtro_PIVA,//7
					filtro_phone  //8
					);

function Trim(){return this.replace(/\s+$|^\s+/g,"");} 
function LTrim(){return this.replace(/^\s+/,"");} 
function RTrim(){return this.replace(/\s+$/,"");} 
//function replaceAll(sA, sB){while (this.indexOf(sA) != -1){this = this.replace(sA,sB);}return this;}
String.prototype.Trim=Trim;    
String.prototype.RTrim=RTrim;    
String.prototype.LTrim=LTrim;    
//String.prototype.replaceAll=replaceAll;    
function replaceAll(t, sA, sB){while ( t.indexOf(sA) != -1){t = t.replace(sA,sB);}return t;}

//function check_input(oggetto, descrizione, indice_filtri, obbligatorio) {
//	alert('check_input: '+oggetto);
//	if(oggetto) {
//		if(filtro_spazi.test(oggetto.value)) {
//			if(obbligatorio) {
//				alert("Completare il campo "+descrizione);
//				oggetto.focus();
//				return false;
//			}
//		} else if(indice_filtri>=0) {
//				if(!filtri[indice_filtri].test(oggetto.value)) {
//					//alert("ATTENTION, YOU HAVE ENTERED AN INVALID VALUE ("+oggetto.value+") IN "+descrizione + "\r\n\ filtro: "+filtro_phone+ "\r\nformat: "+Phone_format);
//					if (indice_filtri == 5){
//						//Verify if phone is a number
//						if(!filtro_digit.test(oggetto.value))	
//							alert("ATTENZIONE, solo numeri (" + oggetto.value + ") in "+descrizione); //only digit + "\r\nformat: "+Phone_format);
//						else
//							return true;
//					}
//					else
//						alert("ATTENZIONE, avete inserito dati non corretti -" + oggetto.value + "- in  "+descrizione);
//					oggetto.focus();
//					return false;
//				}
//				else{
//					//additional control for filter 2: email
//					if(indice_filtri==2){
//						if(!isEmail(oggetto.value)){
//							alert("ATTENZIONE, EMAIL non valido (zz_zz@yy.xx) " + descrizione.toUpperCase() );
//							oggetto.focus();
//							return false;						
//						}
//					}
//				}
//		}
//		return true;
//	} 
//	else
//	{
//	    alert("check_input null --> " + oggetto + " per " + descrizione);
//		return true;
//	}
//}
function check_input(oggetto, descrizione, indice_filtri, obbligatorio) {
	return checkinputTest(oggetto, descrizione, indice_filtri, obbligatorio, "ATTENZIONE, avete inserito dati non corretti ", "Completare il campo ")
}
function check_inputLang(oggetto, descrizione, indice_filtri, obbligatorio) {
	//alert('descrizione: '+descrizione+', InvalidValue: '+InvalidValue+', CompleteField: '+CompleteField)
	return checkinputTest(oggetto, descrizione, indice_filtri, obbligatorio, "", "")
}
function checkinputTest(oggetto, descrizione, indice_filtri, obbligatorio, msgInvalid, msgIncomplete) {
try{
//alert('typeof(oggetto): '+typeof(oggetto)+', da: '+descrizione)
var IsObject = false; // != undefined); /*== function*/
var _val = oggetto; /*undefined or string*/
	if(oggetto){
	  IsObject = (oggetto.focus && oggetto.type != 'hidden')
	  //alert('oggetto.type: '+oggetto.type)
	  if(oggetto.value != undefined){/*input*/
	    _val = oggetto.value};
	  if(oggetto.selectedIndex != undefined){
	    	//alert('oggetto.value['+oggetto.selectedIndex+']:'+ oggetto.options[oggetto.selectedIndex].value )
  			_val = oggetto.options[oggetto.selectedIndex].value};
  }
	
//alert('descrizione: '+descrizione+', indice_filtri: '+indice_filtri+', oggetto: '+IsObject+', _val: '+_val)
  if (_val == undefined){_val = ''}
	if (HaveInvalidChar(_val)){
		alert(msgInvalid + ' ' + descrizione.toUpperCase() + '. Avoid invalid Char (' + GetUnSafeCharSET()+')');
		if (IsObject){oggetto.focus();}
		return false;
	}
	if(filtro_spazi.test(_val)) 
	{
		if(obbligatorio) {
			alert(msgIncomplete + ' ' + descrizione.toUpperCase());
			if (IsObject){oggetto.focus();}
			return false;
		}
	} 
	//else if(indice_filtri  >= 0)	{ TODO fare isalfanum con lingue estesse cirillico, india, cinese... 
	else if(indice_filtri  > 0)	{
		
		if(!filtri[indice_filtri].test(_val)) {
			//alert(msgInvalid + ' test('+indice_filtri+') ' + descrizione.toUpperCase()+', Val: '+_val);
			alert(msgInvalid + descrizione.toUpperCase());
			if (IsObject){oggetto.focus();}
			return false;
		}
		else
		{
			//additional control 
			if(indice_filtri==2){
				if(!isEmail(_val)){
					alert(msgInvalid + ' (EMAIL zz_zz@yy.xx) ' + descrizione.toUpperCase() );
					if (IsObject){alert('oggetto.focus4: '+oggetto.focus); oggetto.focus();}
					return false;						
				}
			}
		}
	}
	return true;
	}catch(Err){ShowError('CheckInput on ' + descrizione, Err);return false;}
}
function GetUnSafeCharSET(){
		//return "<>&/|\!£$%";  filtro date non funziona, campo text & permit
		//return "<>|\!£$%";  20080917 authorization for exclamative point fron client request
		return "<>|\£$%"; 
}
function HaveInvalidChar(Str_To_Check){
	StrToCheck =Str_To_Check.Trim();
	if (StrToCheck.length == 0)
		return false;
	NoGoodChars = GetUnSafeCharSET();
	//alert('AvoidChar('+Str_To_Check+')'+NoGoodChars)
    for (i = 0; (i < StrToCheck.length); i++)
    	if ( NoGoodChars.indexOf(String(StrToCheck.charAt(i))) >=0 )
				return true;	
	return false;
}
function dc(D) { // gives YYYYMMDD
   var x = /(\d+)\D+(\d+)\D+(\d+)/.test(D)
   with (RegExp) return ($3*100 + +$2)*100 + +$1 
}

function euroconv(valore) {
	var temp = valore.toString().replace(".",",");
	var arraytemp = temp.split(",");
	temp = "€ " + temp;
	if(arraytemp.length == 1) return temp + ",00";
	else if(arraytemp[1].toString().length == 1) return temp + "0";
	else return temp;
}

function cambiaCase(valore){
	if(valore.value){
		valore.value = valore.value.toUpperCase();
	}
}

function isMember(strValue, arrValueList){
 for(var i = 0; i < arrValueList.length; i++){
  if(arrValueList[i] == strValue){
   return true;
  }
 }
 return false;
}

function isEmail(str){
//validazione dell'email: codice originale qui (http://www.itsuckstobejoe.com/Jdn/jsemail.asp)
var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
return (!r1.test(str) && r2.test(str));
}

function check_length(oggetto, descrizione, aLength, obbligatorio){return check_len(0,oggetto, descrizione, aLength, obbligatorio)}
function check_length_MIN(oggetto, descrizione, aLength, obbligatorio){return check_len(1,oggetto, descrizione, aLength, obbligatorio)}
function check_length_MAX(oggetto, descrizione, aLength, obbligatorio){return check_len(2,oggetto, descrizione, aLength, obbligatorio)}
function check_len(OP, obj, D, L, OBL) {
	if(!obj) {/*alert('obj not defined: '+obj);*/return true;}
	var X=0;
	if (obj.length){X=obj.Trim().length;}
	if (obj.value){X=obj.value.Trim().length;}
	if ((X==0) && (OBL)){
			alert("Completare il campo "+D);
			if(obj.focus){obj.focus();}
			return false;} 
	//alert('X: '+X+', L: '+L);
  switch (OP){
    case 1:
    if (X < L){alert("IL CAMPO "+D+"("+obj.length+") ESSERE ALMENO LUNGO "+L+" caratteri");return false;}break
    case 2:
    if (X > L){alert("IL CAMPO "+D+"("+obj.length+") NON DEVE SUPERARE "+L+" caratteri");return false;}break
    default: 
    if (X != L){alert("IL CAMPO "+D+"("+obj.length+") DEVE ESSERE LUNGO "+L+" caratteri");return false;}
  } 
	return true;		
}

function check_value(oggetto) {
	// return lenght compare if object exist
	if(!oggetto) {return false;}
	if(!oggetto.value) {return false;}
	if(filtro_spazi.test(oggetto.value)) {return false;}
	return (oggetto.value.length > 0)
}

/*
function controllaPIVA(pi)
{
     if( pi == '' )  return '';
     if( pi.length != 11 )
             return "La lunghezza della partita IVA non è\n" +
                     "corretta: la partita IVA dovrebbe essere lunga\n" +
                     "esattamente 11 caratteri.\n";
     validi = "0123456789";
     for( i = 0; i < 11; i++ ){
             if( validi.indexOf( pi.charAt(i) ) == -1 )
                     return "La partita IVA contiene un carattere non valido `" +
                             pi.charAt(i) + "'.\nI caratteri validi sono le cifre.\n";
          }
     s = 0;
     for( i = 0; i <= 9; i += 2 )
             s += pi.charCodeAt(i) - '0'.charCodeAt(0);
     for( i = 1; i <= 9; i += 2 ){
             c = 2*( pi.charCodeAt(i) - '0'.charCodeAt(0) );
             if( c > 9 )  c = c - 9;
             s += c;
     }
     if( ( 10 - s%10 )%10 != pi.charCodeAt(10) - '0'.charCodeAt(0) )
             return "La partita IVA non è valida:\n" +
                     "il codice di controllo non corrisponde.\n";
     return '';

 }
function GetSafeCharSET(){
		return "QWERTYUIOPASDFGHJKLLLLZXCVBNM    qwertyuiopasdfghjkllzxcvbnm1234567890$()=@*_;-'.,"; 
		// alcuni caratteri non passano nell'URL altri non possono essere memorizzati nel DB
}
function isAlphaNum(Str_To_Check){
	StrToCheck =Str_To_Check.Trim();
	if (StrToCheck.length == 0)
		return false;
	GoodChars = GetSafeCharSET();
    for (i = 0; (i < StrToCheck.length); i++)
    	if ( GoodChars.indexOf(String(StrToCheck.charAt(i))) < 0 )
			return false;	
	return true;
} 
function isInt(StrToCheck){
    if (StrToCheck == "") 
    	return false;
    for ( i = 0; (i < StrToCheck.length); i++) 
    { 
    	if (StrToCheck.charAt(i) == "-") 
		{
			if (i != 0) 
				return false;
		}  //
    	else
	        if ((StrToCheck.charAt(i) < "0") || (StrToCheck.charAt(i) > "9")  ) 
	        	return false;
	} 
	return true;
} 
/*

/**********************************************************************/
/****************************MESSAGE**************************************/
/**********************************************************************/
var TextMsg='';
var delimitator = '</PARAMS>'
var separator = '</VAL>'
var delimitatorPost = ' -- '
var browserName=navigator.appName; 
var messageBackgroundColor = "#EEEEEE";
var messageWarningBackgroundColor = "#FF6600";
var messageErrorBackgroundColor = "#992137";
var messageColor = "black";
var messageWarningColor = "white";
var messageErrorColor = "white";
function ShowErrorLocal(Ori, err)
{ 
	var txt
	txt='\n\nRoutine ' + Ori + ' error.'
	if ((err != undefined) && (err != null) && (err.description) && (err.description != ''))
  	txt+='\n\n     Error description: ' + err.description + '\n\n'
  else
  	txt+='\n\n ' + err
 	alert(txt)
}
function ShowError(Ori, err)
{
	var txt
	txt='\n\nRoutine ' + Ori + ' error.'
	if ((err != undefined) && (err != null) && (err.description) && (err.description != ''))
  	txt+='<BR>     Error description: ' + err.description + '<BR>'
  else
  	txt+='<BR> ' + err
 	showMessage( txt, 'error')
}
function showMessage(xtext, xtype, erase)
{
    var divMessage = prendiElementoDaId('divClientMessage');
    var tblMsg = prendiElementoDaId('tblClientMessage');
    if (divMessage != null)
    {
    		//alert('erase: '+ erase)
			 	if (erase == undefined)
				{
				    if (TextMsg != '')
				        xtext = TextMsg + '<BR>'+ xtext;
					TextMsg = xtext}
				else
				{TextMsg = ''}

        if (tblMsg != null)	
            tblMsg.style.display = '';
        divMessage.style.display = '';
		divMessage.style.backgroundColor = messageBackgroundColor;
        divMessage.style.color = messageColor;
        divMessage.innerHTML = xtext;
        if (xtype != null)
        {
            if (xtype == 'error')
            {
                divMessage.style.backgroundColor = messageErrorBackgroundColor;
                divMessage.style.color = messageErrorColor;
            }
            else if (xtype == 'warning')
            {
                divMessage.style.backgroundColor = messageWarningBackgroundColor;
                divMessage.style.color = messageWarningColor;
            }
        }
    }
}
function clearMessage(Num)
{
    var divMessage =prendiElementoDaId('divClientMessage');
    var tblMsg = prendiElementoDaId('tblClientMessage');
    if (Num == undefined)
    {
        if (tblMsg != null)	
            tblMsg.style.display = 'none';
       	divMessage.style.display = 'none';
	    TextMsg = '';
    }
    else
    	showMessage('Request ' + Num + ' running, wait...',null, 'erase')
}
function prendiElementoDaId(id_elemento){
	//alert('prendiElementoDaId: ' +id_elemento)
	var elemento;
	if(document.getElementById)
		elemento = document.getElementById(id_elemento);
	else
		elemento = document.all[id_elemento];
	return elemento;
}


