/*
 * Copyright (c) 1999, by SonicWALL, Inc.
 * 5400 Betsy Cross Road, Suite 206, Santa Clara, CA 95054, USA
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of SonicWALL, Inc. ("Confidential Information").  You
 * shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement
 * you entered into with SonicWALL, Inc.
 */

/***************************************************************
** isBlank()
***************************************************************/
function isBlank(formTextElement, desc)
{
	//+ "   value=" + formTextElement.value);
	testValue = formTextElement.value;
	if (testValue.length > 0) {
		while(testValue.substring(0,1) == " " && testValue.length-1>0)
			testValue=testValue.substring(1,testValue.length);
		// after loop need to check the very last one
		if (testValue.substring(0,1) ==" ")
			testValue = "";
	}
	if (testValue.length > 0) 
		return false;
	else {
		if (desc && desc.length > 0)
			alert("'"+desc+"' is blank. Please fill a value in.");
		formTextElement.value = '';	// force a pure empty field
		formTextElement.focus();
		formTextElement.select();
		return true;
	}
}

/***************************************************************
** isPos() - called internally by isPosInteger() and validIP()
**           assume the string passed is non-blank
***************************************************************/
function isPos(testValue)
{
	var inputStr = testValue.toString();
	for (var i = 0; i < inputStr.length; i++) {
		var oneChar = inputStr.charAt(i)
		if (oneChar < "0" || oneChar > "9")
			return false;
	}
	return true
}

/***************************************************************
** isPosInteger()
***************************************************************/
function isPosInteger(formTextElement, desc)
{
	if (isBlank(formTextElement,desc))
		return false;
	if (isPos(formTextElement.value))
		return true;
	if (desc && desc.length > 0)
		alert("'" + desc + "' is not a positive integer. Please fill a positive integer.");
	formTextElement.focus();
	formTextElement.select();
	return false
}

/***************************************************************
** inRange()
***************************************************************/
function inRange(formTextElement, lowValue, highValue, desc)
{
	if (isBlank(formTextElement,desc))
		return false;
	if (lowValue >=0 && highValue >= 0) {
		if (!isPosInteger(formTextElement,desc))
			return false;
	}
	testValue = formTextElement.value;
	inputStr = testValue.toString()
	num = parseInt(inputStr);
	if (num < lowValue || num > highValue) {
		if (desc && desc.length > 0)
			alert("'" + desc + "' is not in the valid range of [" + lowValue + ".." + highValue + "]. Please fill a number within this range.");
		formTextElement.focus();
		formTextElement.select();
		return false;
	}
	return true
}

/***************************************************************
** invalidEmailAlert() - called by validEmail() to display alert
***************************************************************/
function invalidEmailAlert(formTextElement, desc)
{
	if (desc && desc.length > 0)
		alert("'" + desc + "' is not a valid email address. Please provide a valid email address.");
	formTextElement.focus();
	formTextElement.select();
	return false;
}

/***************************************************************
** validEmail()
***************************************************************/
function validEmail(formTextElement, desc)
{
	// is it blank ?
	if (isBlank(formTextElement,desc))
		return false;

	testValue = formTextElement.value;
	email = testValue.toString()
	
	// does it contain any invalid characters ?
	invalidChars = " /:,;";
	for (i = 0; i < invalidChars.length; i++)
		if (email.indexOf(invalidChars.charAt(i),0) > -1)
			return invalidEmailAlert(formTextElement,desc);
	
	// there must be one @ symbol
	if ((atPos = email.indexOf("@",1)) == -1)
		return invalidEmailAlert(formTextElement,desc);

	// there cannot be any more @ symbol
	if (email.indexOf("@",atPos+1) != -1)
		return invalidEmailAlert(formTextElement,desc);
	
	// there must be at least one period after "@"
	if ((periodPos = email.indexOf(".",atPos)) == -1)
		return invalidEmailAlert(formTextElement,desc);

	// there must be atleast 2 characters after the "."
	if (periodPos+3 > email.length)
		return invalidEmailAlert(formTextElement,desc);
	return true;
}

/***************************************************************
** trimSpaces()
***************************************************************/
function trimSpaces(text)
{
	newText = "";
	// Leading spaces
	for (i = 0; i < text.length; i++)
	{
		if (text.charAt(i) == ' ')
			newText = text.substring(i + 1, text.length);
		else
			break;
	}
	if (newText.length != 0)
		text = newText;
	
	// Trailing spaces
	for (i = text.length - 1; i > -1; i--)
	{
		if (text.charAt(i) == ' ')
			newText = text.substring(0, i);
		else
			break;
	}
	if (newText.length != 0)
		text = newText;
	
	return text;
}

/***************************************************************
** invalidDateAlert() - called by isValidDate() to display alert
***************************************************************/
function invalidDateAlert(formElementDay, desc)
{
	if (desc && desc.length > 0)
		alert("'" + desc + "' is not a valid day of the month.\n\nPlease select another day");
	formElementDay.focus();
	return false;
}

/***************************************************************
** isValidDate() : returns true if date is valid
**		parameters: month (1..12) day (1..31) year (nnnn), desc
***************************************************************/
function isValidDate(month, day, year, formElementDay, desc)
{
	if (month < 1 || month > 12 || day < 1 || day > 31 || year < 0)
		return invalidDateAlert(formElementDay,desc);	// should never come here, since UI takes care of it
	if (day < 29)	// every month has atleast 28 days
		return true;
	if (day > 29 && month==2)	// feb can have at the most 29 days
		return invalidDateAlert(formElementDay,desc);
	if (day==31 && (month==4  || month==6 || month==9 || month==11))	// these months can have at the most 30 days
		return invalidDateAlert(formElementDay,desc);
	// now, check for leap year
	if (day==29 && month==2) {
		// return false if this is not a leap year
		if (year%4==0) {
			if (year%100==0) {
				if (year%400==0)
					return true;
				return invalidDateAlert(formElementDay,desc);
			}
			return true;
		}
		return invalidDateAlert(formElementDay,desc);
	}
	return true;
}

/***************************************************************
** validURL()
**	rudimentary: look for spaces and semicolons basically!
**				 we will make it more sophisticated later
***************************************************************/
function validURL(formTextElement, desc, blankIsValid)
{
	// if blankIsValid, then blank field is a valid IP field (such as in DNS)
	if (blankIsValid && blankIsValid==true && isBlank(formTextElement))
		return true;
		
	// is it blank ?
	if (isBlank(formTextElement,desc))
		return false;

	var testValue = formTextElement.value;
	var url = testValue.toString()
	
	// does it contain any invalid characters ?
	var invalidChars = " ;";
	for (var i = 0; i < invalidChars.length; i++) {
		if (url.indexOf(invalidChars.charAt(i),0) > -1) {
			if (desc && desc.length > 0)
				alert("'" + desc + "' is not a valid URL.\n\nPlease enter a valid URL.");
			formTextElement.focus();
			formTextElement.select();
			return false;
		}
	}

	return true;
}

/***************************************************************
** validLength()
**	  : looks for minimum length specified
**				 
***************************************************************/
function validLength(formTextElement,desc,length)
{
	var ilength=formTextElement.value.length;
	
	if(ilength<length){
		if(desc && desc.length > 0)
		   alert("'" + desc + "' must contain atleast '"+length+"' characters.");
		 formTextElement.focus();
		 formTextElement.select();
		 return false;
		}

		return true;
}


/***************************************************************
** validString()
**	  : looks whether String entered is IPAddress Or IPName
**				 
***************************************************************/
function validString(formTextElement,desc,IPVal)
{
	
	   for(var i=0;i<formTextElement.value.length;i++)
	   {
	     	if (IPVal.indexOf(formTextElement.value.charAt(i)) == -1)
		{
			if(desc && desc.length > 0)
			{
				alert("'"+desc+"'must contain hexcharacters Only");
				formTextElement.focus();
				formTextElement.select();
				return false;
			}

		   return false;
		}
	    }
		
	
	  return true;
}

/***************************************************************
** validAlphaNumeric()
***************************************************************/
function validAlphaNumeric(formTextElement, minLen, maxLen, desc)
{
	if (isBlank(formTextElement,desc))
		return false;
	var valString = formTextElement.value;
	if (valString.length < minLen) {
		if (desc && desc.length > 0)
			alert('"'+desc+"' should have atleast " + minLen + " letters.");
			formTextElement.focus();
			formTextElement.select();
			return false;
	}
	if (valString.length > maxLen) {
		if (desc && desc.length > 0)
			alert('"'+desc+"' should have maximum " + maxLen + " letters.");
		formTextElement.focus();
		formTextElement.select();
		return false;
	}

	var inputStr = formTextElement.value.toString();
	for (var i = 0; i < inputStr.length; i++) {
		var oneChar = inputStr.charAt(i)
		if ((oneChar >= "0" && oneChar <= "9") ||
			(oneChar >= "a" && oneChar <= "z") ||
			(oneChar >= "A" && oneChar <= "Z")) ;
		else {
			if (desc && desc.length > 0)
				alert('"'+desc+"' is not valid. Only alphanumeric input is allowed."); 
			formTextElement.focus();
			formTextElement.select();
			return false;
		}
	}
	return true;
}


/***************************************************************
** checkForInvalidCharacter()
**	  : checks if the given character exists in the given text element
**      if so, we alert the user
***************************************************************/
function checkForInvalidCharacter(formTextElement, formTextElementDesc, desc, testChar)
{
	if(isBlank(formTextElement, formTextElementDesc))
		return false;
			
	if (formTextElement.value.indexOf(testChar) != -1) {
		alert(desc);
		formTextElement.focus();
		formTextElement.select();
		return false;
	}
	return true;
}

/***************************************************************
** validDecimalNumber()
**	  : checks if the number in the form's element is a valid decimal
**	    number and constructs it(if needed) in the form xxx.yyy restricting
**		number of digits after decimal dot as specified.
**	  : checks if the number is less than the minimum value specified.
**
***************************************************************/
function validDecimalNumber(formTextElement, desc, maxDecimalDigits, minValue)
{
	if(isBlank(formTextElement, desc))
		return false;
	
	var testValue = formTextElement.value.toString();
	var integerNumPart = "";
	var valBeforeDecimal;
	
	var decimalPos = testValue.indexOf(".");
	if(decimalPos != -1)
	{
		// we have a decimal dot and some value before it
		if(decimalPos != 0)
			integerNumPart = testValue.substring(0, decimalPos);
	}
	// we just have only the integral part as the inputted number
	else
		integerNumPart = testValue;
	
	// check if the value before the decimal dot is valid
	while(integerNumPart.length > 0 && integerNumPart.substring(0, 1) == " " && integerNumPart.length-1 > 0)
		integerNumPart = integerNumPart.substring(1, integerNumPart.length);
	
	// we either have a blank value or no value before the decimal dot
	if(integerNumPart.substring(0, 1) == " " || decimalPos == 0)
		valBeforeDecimal = "";
	else
	{
		// we have some value before the decimal dot
		if(decimalPos > 0)
			valBeforeDecimal = testValue.substring(0, decimalPos);
		// input number does not contain a decimal part
		else
			valBeforeDecimal = testValue;
		
		// check if the value inputted before the decimal dot is valid positive number
		var ignoreLeadingSpace = true;
		var valWithNoLeadingSpace = "";
		for(var i = 0; i < valBeforeDecimal.length; i++)
		{
			var oneChar = valBeforeDecimal.charAt(i);
			if(oneChar == " " && ignoreLeadingSpace == true)
				continue;
			
			if(oneChar < "0" || oneChar > "9")
			{
				alert("'" + desc + "' is not a valid positive number. Please fill a value in.");
				formTextElement.focus();
				formTextElement.select();
				return false;
			}
			else
			{
				valWithNoLeadingSpace += oneChar;
				ignoreLeadingSpace = false;
			}
		}
		
		if(valWithNoLeadingSpace.length > 0)
			valBeforeDecimal = valWithNoLeadingSpace;
	}
	
	// check if the value entered after the decimal dot is valid and does not exceed 'maxDecimalDigits'
	// number of digits
	var valAfterDecimal = "";
	if(decimalPos != -1)
	{
		// we have some value after the decimal dot
		if(!(decimalPos == (testValue.length -1)))
		{
			var decimalPart = testValue.substring(decimalPos+1);
			
			// check if value is blank
			while(decimalPart.substring(0,1) == " " && decimalPart.length-1 > 0)
				decimalPart = decimalPart.substring(1,decimalPart.length);
				
			// we have some value after the decimal dot
			if(!(decimalPart.substring(0,1) == " "))
			{
				valAfterDecimal = testValue.substring(decimalPos+1);
				for(var i = 0; i < valAfterDecimal.length; i++)
				{
					var oneChar = valAfterDecimal.charAt(i)
					if(oneChar < "0" || oneChar > "9")
					{
						alert("'" + desc + "' is not a valid positive number. Please fill a value in.");
						formTextElement.focus();
						formTextElement.select();
						return false;
					}
				}
				
				// check for number of digits after decimal dot 
				if(valAfterDecimal.length > maxDecimalDigits)
				{
					if(desc && desc.length > 0)
						alert("'" + desc + "' can contain at most '"+maxDecimalDigits+"' digits after the decimal dot.");
					
					formTextElement.focus();
					formTextElement.select();
					return false;
				}
				// pad zeroes to have 'maxDecimalDigits' number of digits after decimal dot
				else if(valAfterDecimal.length != maxDecimalDigits)
				{
					var len = valAfterDecimal.length;
					for(var i = 0; i < maxDecimalDigits - len; i++)
						valAfterDecimal += "0";
				}
			}
		}
	}
	
	// disallow zero value
	/*if(valBeforeDecimal == 0 && valAfterDecimal == 0)
	{
		alert("'" + desc + "' is invalid. Please input a value greater than 0.000");
		formTextElement.focus();
		formTextElement.select();
		return false;
	}
	else*/ if(valBeforeDecimal.length == 0 && valAfterDecimal.length != 0)
		valBeforeDecimal = "0";
	else if(valBeforeDecimal.length != 0 && valAfterDecimal.length == 0)
		valAfterDecimal = "000";
	
	var finalValue = valBeforeDecimal + "." + valAfterDecimal;
	if(parseFloat(finalValue) < parseFloat(minValue))
	{
		alert("'" + desc + "' must be atleast " + minValue + "Kbps.");
		formTextElement.focus();
		formTextElement.select();
		return false;
	}
	
	formTextElement.value = finalValue;
	
	return true;
}



/************************************************************************************
**function validateDate(fieldName, dateStr)
**
** Checks if the date is of the form mm/dd/yyyy
************************************************************************************/ 
function validateDate(fieldName, dateStr)
{
	if ((dateStr == "null") || (dateStr == ""))
	{
		alert(fieldName + ": No date provided. \nPlease provide a valid date of the form mm/dd/yyyy");
		return false;
	}

	if (dateStr.length != 10)
	{
		alert(fieldName + ": Wrong Date Format. \nPlease provide a valid date of the form mm/dd/yyyy");
		return false;
	}

	var index = dateStr.indexOf("/");
	if (index == -1)
	{
		alert(fieldName + ": Wrong Date Format. \nPlease provide a valid date of the form mm/dd/yyyy");
		return false;
	}

	var month = dateStr.substring(0, index);
	if ((month.length != 2) || (month <= 0) || (month > 12)) 
	{
		alert(fieldName + ": Wrong month value in the date. \nPlease provide a valid date of the form mm/dd/yyyy");
		return false;
	}

	dateStr = dateStr.substring(index+1, dateStr.length);
	index = dateStr.indexOf("/");
	if (index == -1)
	{
		alert(fieldName + ": Wrong Date Format. \nPlease provide a valid date of the form mm/dd/yyyy");
		return false;
	}
	var day = dateStr.substring(0, index);
	if ((day.length != 2) || (day <= 0) || (day > 31)) 
	{
		alert(fieldName + ": Wrong day value in the date. \nPlease provide a valid date of the form mm/dd/yyyy");
		return false;
	}

	return true;
}

/***************************************************************
**  limitTextAreaSize()
***************************************************************/
function limitTextAreaSize(textAreaControl, maxLen)
{
	var msg = textAreaControl.value;
	var msgLen= msg.length;
	if (msgLen >= maxLen)
	{
		textAreaControl.value = msg.substring(0,maxLen);
	}

}

function isInteger(s)
{ 
	var i;
	for (i = 0; i < s.length; i++)
	{   
	// Check that current character is number.
	var c = s.charAt(i);
	if (((c < "0") || (c > "9"))) return false;
	}
	// All characters are numbers.
	return true;
}




/**************************************************************/
/***************************************************************
**  function to get age from a date of birth()
***************************************************************/

function getAge(month,date,year) {
 var now = new Date();
    var today = new Date(now.getYear(),now.getMonth(),now.getDate());

    var yearNow = now.getYear();
    var monthNow = now.getMonth();
    var dateNow = now.getDate();

    var dob = new Date(year,month,date);
		
    var yearDob = dob.getYear();
    var monthDob = dob.getMonth();
    var dateDob = dob.getDate();
    yearAge = yearNow - yearDob;
	if(yearAge>1900)	yearAge=yearAge-1900;
    if (monthNow >= monthDob)
        var monthAge = monthNow - monthDob;
    else {
        yearAge--;
        var monthAge = 12 + monthNow -monthDob;
    }

    if (dateNow >= dateDob)
        var dateAge = dateNow - dateDob;
    else {
        monthAge--;
        var dateAge = 31 + dateNow - dateDob;

        if (monthAge < 0) {
            monthAge = 11;
            yearAge--; 
        }
    }

//    return yearAge + ' years ' + monthAge + ' months ' + dateAge + ' days';
	
    return yearAge;
}
/**************************************************************/
