// File jsFunctions.asp "compilato" per migliorare l'uso cache

function setAllLabelColor(colorCode) 
{
	//imposto un colore ai link della barra inferiore
	var i
	for(i=0; i<document.all.length; i++) 
	{
		//alert(document.all(i).id.substr(0,3));
		if (document.all(i).tagName.toUpperCase() == "SPAN" && document.all(i).id.substr(0,5) == 'menu_')
		{
			document.all(i).style.color = colorCode;				
		}
	}
}
	
function setLabelColor(divCode,colorCode)
{
	//imposto un colore ad una label specifica
	document.all['menu_'+divCode].style.color= colorCode;

}
	
function checkEmailField(fieldName,errMsg,isMandatory,minLength,maxLength)
{
	//isMandatory=true controllo che non sia vuoto. False altrimenti
	var myField=document.getElementById(fieldName); 
	var myFieldValue=trim(myField.value);
	myField.value=myFieldValue;
	//alert(myFieldValue)
	if (!isMandatory && myFieldValue == '')
	{
		return true
	}
	
	if (myFieldValue.length<minLength || myFieldValue.length>maxLength || 
		myFieldValue == '' || (! isValidEmail(myFieldValue))) 
	{
		//alert('E\' necessario inserire il Nome Utente.')
		window.alert(errMsg);
		if (myField.type.toLowerCase()!='hidden')
			{myField.focus();}
		return false;
	}
	return true

}

function checkEmailValue(fieldName,errMsg,isMandatory,minLength,maxLength)
{
	//isMandatory=true controllo che non sia vuoto. False altrimenti
	var myField=document.getElementById(fieldName); 
	var myFieldValue=trim(myField.value);
	myField.value=myFieldValue;
	if (!isMandatory && myFieldValue == '')
	{
		return true
	}
	if (myFieldValue.length<minLength || myFieldValue.length>maxLength || 
		myFieldValue == '' || (! isValidEmail(myFieldValue))) 
	{
		if (myField.type.toLowerCase()!='hidden')
			{myField.focus();}
		return false;
	}
	return true

}

function checkValidFieldGeneric(fieldName,errMsg,isMandatory,domainId,minLength,maxLength)
{
	//isMandatory=true controllo che non sia vuoto. False altrimenti
	var myField=document.getElementById(fieldName); 
	var myFieldValue=trim(myField.value);
	myField.value=myFieldValue;
	if (!isMandatory && trim(myFieldValue) == '')
	{
		return true
	}
	if (myFieldValue.length<minLength || myFieldValue.length>maxLength || 
		trim(myFieldValue) == '' || (! isValidValue(myFieldValue,domainId))) 
	{
		window.alert(errMsg);
		if (myField.type.toLowerCase()!='hidden')
			{myField.focus();}
		return false;
	}
	return true
}

function checkAlfaField(fieldName,errMsg,includeSpace,isMandatory,minLength,maxLength)
{
	//includeSpace=true include lo spazio come carattere valido, false altrimenti
	//isMandatory=true controllo che non sia vuoto. False altrimenti
	var myField=document.getElementById(fieldName); 
	var myFieldValue=trim(myField.value);
	myField.value=myFieldValue;
	//alert(myFieldValue)
	if (!isMandatory && myFieldValue == '')
	{
		return true
	}
	if (myFieldValue.length<minLength || myFieldValue.length>maxLength || 
		myFieldValue == '' || (! isOnlyAlphaNumeric(myFieldValue,includeSpace))) 
	{
		//alert('E\' necessario inserire il Nome Utente.')
		window.alert(errMsg);
		if (myField.type.toLowerCase()!='hidden')
			{myField.focus();}
		return false;
	}
	return true
}

function checkNumericField(fieldName,errMsg,bottomValue,topValue,bottomFormatSize,topFormatSize,isMandatory)
{
	//Ritorna true se il dato è numerico e compreso nell'intervallo specificato
	//isMandatory=true controllo che non sia vuoto. False altrimenti
	var myField=document.getElementById(fieldName); 
	var myFieldValue=trim(myField.value);
	myField.value=myFieldValue;
	
	if (!isMandatory && myFieldValue == '')
	{
		return true
	}

	if (myFieldValue == '' || (! isOnlyDigit(myFieldValue)) || 
		myFieldValue<bottomValue || myFieldValue>topValue ||
		myFieldValue.toString().length<bottomFormatSize || myFieldValue.toString().length>topFormatSize)
	{
		window.alert(errMsg);
		if (myField.type.toLowerCase()!='hidden')
			{myField.focus();}
		return false;
	}
	return true	
}



function isOnlyDigit(myString)
{
	//Restituisce true se la stringa è numerica. False altrimenti
	var retVal=true;
	var all = "0123456789.";
	for (i=0;i<myString.length;i++)
	{
		if (all.indexOf(myString.charAt(i))==-1)
		{
			//Se non trovo un carattere numerico
			if (myString.charAt(i)=="-")
			{ 
				//Se trovo il -
				if (i==0) 
				{
					//Se sono nella prima posizione è OK
				}
				else
				{
					//Se non sono nella prima posizione è KO
					retVal=false
				}
			}
			else
			{
				//Se non è il - allora è KO
				retVal=false
			}
		}
	}
	return retVal;
}

function isOnlyAlphaNumeric(myString,canContainSpace)
{
	//Restituisce true se la stringa è alfanumerica. False altrimenti
	var retVal=true;
	var all = "0123456789.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_@";
	if (canContainSpace==1) 
	{
		all=all + " ";
	}
	for (i=0;i<myString.length;i++)
	{
		if (all.indexOf(myString.charAt(i))==-1)
		{
			retVal=false
		}
	}
	return retVal;
}

function checkOnlyDigit()
{
	//Restituisce true se vengono premuti solo tasti numerici. False altrimenti
	var myChar;
	var all = "0123456789.";
	
	if (document.all)
	{
		e = window.event;
		myChar = String.fromCharCode(e.keyCode);
	}
	else
		if (document.layers)
			var myChar = String.fromCharCode(e.which); 

	if (all.indexOf(myChar) == -1)
	{
		if (document.layers)
			return false;
		else if (document.all)
            e.returnValue = false
	}
	return true;
}

function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
}					//Ends the "trim" function


function checkValidDate(dateStr) {
    // dateStr must be of format month day year with either slashes
    // or dashes separating the parts. Some minor changes would have
    // to be made to use day month year or another format.
    // This function returns True if the date is valid.
    
    //Ricerca il primo divisore
    var slash1 = dateStr.indexOf("/");
    if (slash1 == -1) { slash1 = dateStr.indexOf("-"); }
    // if no slashes or dashes, invalid date
    if (slash1 == -1) { return false; }
    
    //
    var dateMonth = dateStr.substring(0, slash1)
    var dateMonthAndYear = dateStr.substring(slash1+1, dateStr.length);
    var slash2 = dateMonthAndYear.indexOf("/");
    if (slash2 == -1) { slash2 = dateMonthAndYear.indexOf("-"); }
    // if not a second slash or dash, invalid date
    if (slash2 == -1) { return false; }
    var dateDay = dateMonthAndYear.substring(0, slash2);
    var dateYear = dateMonthAndYear.substring(slash2+1, dateMonthAndYear.length);
    
    if ( (dateMonth == "") || (dateDay == "") || (dateYear == "") ) { return false; }
    
    // if any non-digits in the month, invalid date
    for (var x=0; x < dateMonth.length; x++) {
        var digit = dateMonth.substring(x, x+1);
        if ((digit < "0") || (digit > "9")) { return false; }
    }
    
    // convert the text month to a number
    var numMonth = 0;
    for (var x=0; x < dateMonth.length; x++) {
        digit = dateMonth.substring(x, x+1);
        numMonth *= 10;
        numMonth += parseInt(digit);
    }
    
    if ((numMonth <= 0) || (numMonth > 12)) { return false; }
    
    // if any non-digits in the day, invalid date
    for (var x=0; x < dateDay.length; x++) {
        digit = dateDay.substring(x, x+1);
        if ((digit < "0") || (digit > "9")) { return false; }
    }
    // convert the text day to a number
    var numDay = 0;
    for (var x=0; x < dateDay.length; x++) {
        digit = dateDay.substring(x, x+1);
        numDay *= 10;
        numDay += parseInt(digit);
    }

    // if any non-digits in the year, invalid date
    for (var x=0; x < dateYear.length; x++) {
        digit = dateYear.substring(x, x+1);
        if ((digit < "0") || (digit > "9")) { return false; }
    }
    // convert the text year to a number
    var numYear = 0;
    for (var x=0; x < dateYear.length; x++) {
        digit = dateYear.substring(x, x+1);
        numYear *= 10;
        numYear += parseInt(digit);
    }

    // check date is valid with field split
	return checkValidDateSplit(numDay,numMonth,numYear)
}

function checkValidDateSplit(numDay,numMonth,numYear)

{
	//Controlla che i dati passati su tre campi siano validi come giorno/mese/anno
	//Controllo validità generica dei campi
	if ((numDay <= 0) || (numDay > 31)) { return false; }
	if ((numMonth <= 0) || (numMonth > 12)) { return false; }
	if ((numYear <= 1800) || (numDay > 2100)) { return false; }
	
	//Controllo validità specifica dei campi
    // February can't be greater than 29 (leap year calculation comes later)
    if ((numMonth == 2) && (numDay > 29)) { return false; }
    // check for months with only 30 days
    if ((numMonth == 4) || (numMonth == 6) || (numMonth == 9) || (numMonth == 11)) { 
        if (numDay > 30) { return false; } 
    }

    // Year must be a 2-digit year or a 4-digit year
    if ( (numYear.length != 2) && (numYear.length != 4) ) { return false; }

    // if 2-digit year, use 50 as a pivot date
    if ( (numYear < 50) && (numYear.length == 2) ) { numYear += 2000; }
    else if ( (numYear < 100) && (numYear.length == 2) ) { numYear += 1900; }

    // check for leap year if the month and day is Feb 29
    if ((numMonth == 2) && (numDay == 29)) {
        var div4 = numYear % 4;
        var div100 = numYear % 100;
        var div400 = numYear % 400;
        // if not divisible by 4, then not a leap year so Feb 29 is invalid
        if (div4 != 0) { return false; }
        // at this point, year is divisible by 4. So if year is divisible by
        // 100 and not 400, then it's not a leap year so Feb 29 is invalid
        if ((div100 == 0) && (div400 != 0)) { return false; }
    }
    // date is valid
    return true;
}

//funzione per gestire lo scaricamento progressivo degli oggetti flash nella pagina
function ShowFlash() {
    document.getElementById('aibiflash').style.display = 'block';
}

function isValidEmail(emailAddress) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    return re.test(emailAddress);
}

function isValidValue(value,domainId)
{
	

	if (domainId=='N')
	{
		//Solo numerici

		regExp=/^((\\+|-)?[0-9]*)(\\.([0-9]*))?([0-9])$/
	} 
	else if (domainId=='A')
	{
		//SOlo alfanumerici senza spazio
		regExp=/^([a-zA-Z0-9@_.|-]*)([a-zA-Z0-9@_.|-]*)$/
	}
	else if (domainId=='B')
	{
		//SOlo alfanumerici con spazio
		regExp=/^([a-zA-Z0-9@_. |-]*)([a-zA-Z0-9@_. |-]*)$/
	
	}
	else if (domainId=='C')
	{
		//Ogni carattere è permesso
		regExp=/.*/
	
	}
	else if (domainId=='D')
	{
		//Regular Expr per validare nome, cognome,  etc
		regExp=/^([-A-Za-zàáâãäåèéêëìíîïñòóôõùúûüÀÁÂÃÄÅÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜ°ºª`´~ç^]?)([-A-Za-zàáâãäåèéêëìíîïñòóôõùúûüÀÁÂÃÄÅÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜ°ºª`´~ç^.\' ]*)([-A-Za-zàáâãäåèéêëìíîïñòóôõùúûüÀÁÂÃÄÅÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜ°ºª`´~ç^\'])$/
	
	}
	else if (domainId=='F')
	{
		//Regular Expr per validare indirizzo, numeri civici etc
		regExp=/^([-A-Za-zàáâãäåèéêëìíîïñòóôõùúûüÀÁÂÃÄÅÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜ°ºª`´~ç^-]?)([-A-Za-zàáâãäåèéêëìíîïñòóôõùúûüÀÁÂÃÄÅÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜ°ºª`´~ç^0-9.,\' /-]*)([-A-Za-zàáâãäåèéêëìíîïñòóôõùúûüÀÁÂÃÄÅÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜ°ºª`´~ç^0-9.-]?)$/
	
	}
	else if (domainId=='E')
	{
		//regExp=/^([-A-Za-zàáâãäåèéêëìíîïñòóôõùúûüÀÁÂÃÄÅÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜ°ºª`´~ç^0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$/
		regExp =	/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
	}
	else if (domainId=='G')
	{
		//Usato per fare il login tramite uid e pwd. Considera caratteri inseriti dal vecchio FE
		regExp=/^([a-zA-Z0-9@_. |-]*)([a-zA-Z0-9@_. |-]*)$/
	
	}

	else
	{
		return false
	}	
	
	return regExp.test(value)


}
