// Last Update 8/18/2004

/**************************************************************
 TabNext(obj,event,len,next_field)
 
 Function to auto-tab phone field
 
 Arguments:
   obj :  The input object (this)
   event: Either 'up' or 'down' depending on the keypress event
   len  : Max length of field - tab when input reaches this length
   next_field: input object to get focus after this one

 Usage: <input name="Phone1" maxlength="3" onkeyup="TabNext(this,'up',3,this.form.Phone2)">
**************************************************************/
function TabNext(obj,event,len,next_field)
{
	var temp_field_length=0;
	if (event == "down")
	{
		temp_field_length=obj.value.length;
	}
	else if (event == "up") 
	{
		if (obj.value.length != temp_field_length) 
		{
			temp_field_length=obj.value.length;
			if (temp_field_length == len) 
			{
				next_field.focus();
			}
		}
	}
}

/**************************************************************
 IsAlpha: Returns a Boolean value indicating whether an 
                 expression is all alpha

 Parameters:
      Expression = Variant containing a numeric expression or 
                   string expression.

 Returns: Boolean
***************************************************************/
function IsAlpha(Expression)
{
    Expression = Expression.toLowerCase();
    RefString = "abcdefghijklmnopqrstuvwxyz-' ";

    if (Expression.length < 1) 
        return (false);

    for (var i = 0; i < Expression.length; i++) 
    {
        var ch = Expression.substr(i, 1)
        var a = RefString.indexOf(ch, 0)
        if (a == -1)
            return (false);
    }
    return(true);
}

/**************************************************************
 IsEmail: Returns a boolean if the specified Expression is a
          valid e-mail address. If Expression is null, false
          is returned.

 Parameters:
      Expression = e-mail to validate.

 Returns: boolean
***************************************************************/
function IsEmail(Expression)
{
    if (Expression == null)
        return (false);

    var supported = 0;
    if (window.RegExp)
    {
        var tempStr = "a";
        var tempReg = new RegExp(tempStr);
        if (tempReg.test(tempStr)) supported = 1;
    }
    if (!supported) 
        return (Expression.indexOf(".") > 2) && (Expression.indexOf("@") > 0);
    var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
    var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
    return (!r1.test(Expression) && r2.test(Expression));
}

function IsEmail2(Expression)
{
    RefString = " !";

    if (Expression.length < 1) 
        return (false);

    for (var i = 0; i < Expression.length; i++) 
    {
        var ch = Expression.substr(i, 1);
        var a = RefString.indexOf(ch, 0);

        if (a != -1)
            return (false);
    }
    return(true);
}

/**************************************************************
 IsDate: Returns a Boolean (true) if the date is true, false
         is not

 Parameters:
    - DateStr: String date in format (MM/DD/YYYY or MM-DD-YYYY or YY)

 Returns: Boolean
***************************************************************/
function IsDate(dateStr)
{
    // Checks for the following valid date formats:
    // MM/DD/YYYY   MM-DD-YYYY or YY

    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;

    var matchArray = dateStr.match(datePat);
    if (matchArray == null)
        return false;

    month = matchArray[1];
    day = matchArray[3];
    year = matchArray[4];
    if (month < 1 || month > 12)
        return false;

    if (day < 1 || day > 31)
        return false;

    if ((month==4 || month==6 || month==9 || month==11) && day==31)
        return false;

    if (month == 2)
    {
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))
        if (day>29 || (day==29 && !isleap))
            return false;
    }
    
	getnow = new Date();
    //if (year < 1900)    //requirement restraint (between 1900 & current year)
    //    return false; 

    //if (year > getnow.getFullYear())    //requirement restraint (between 1900 & current year)
    //    return false;    


    //if ((year >= 1000) && (year <= 1752))    //DB restraint
    //    return false

    return true;
}

/**************************************************************
 IsNumber: Returns a Boolean value indicating whether an 
                 expression is all Number

 Parameters:
      Expression = Variant containing a numeric expression or 
                   string expression.

 Returns: Boolean
***************************************************************/
function IsNumber(Expression)
{
	var newstring = parseFloat(Expression).toString();
	if(newstring == "NaN") 
	{
		return(false);
	}
    return(true);
}

/**************************************************************
setVisibility(objId, sVisibility)

Parameters: 
objId - the id of an element (case sensitive)
sVisibility - "visible" | "inherit" | "none" (case insensitive)

USAGE: 
Show div1:
onclick='setVisibility("div1","visible")' 

Inherit the visibility of div2's parentNode:
onblur='setVisibility("div2", "inherit")' 

Hide span3:
onblur='setVisibility("span3", "hidden")'
***************************************************************/

function setVisibility(objId, sVisibility)
{
	var obj = document.getElementById(objId);
	obj.style.visibility = sVisibility;
}

/**************************************************************
round_decimals(original_number, decimals)

Parameters: 
original_number - the number to be rounded
decimals - the number of decimal places desired
***************************************************************/
function round_decimals(original_number, decimals) {
    var result1 = original_number * Math.pow(10, decimals)
    var result2 = Math.round(result1)
    var result3 = result2 / Math.pow(10, decimals)
    return pad_with_zeros(result3, decimals)
}

function pad_with_zeros(rounded_value, decimal_places) {

    // Convert the number to a string
    var value_string = rounded_value.toString()
    
    // Locate the decimal point
    var decimal_location = value_string.indexOf(".")

    // Is there a decimal point?
    if (decimal_location == -1) {
        
        // If no, then all decimal places will be padded with 0s
        decimal_part_length = 0
        
        // If decimal_places is greater than zero, tack on a decimal point
        value_string += decimal_places > 0 ? "." : ""
    }
    else {

        // If yes, then only the extra decimal places will be padded with 0s
        decimal_part_length = value_string.length - decimal_location - 1
    }
    
    // Calculate the number of decimal places that need to be padded with 0s
    var pad_total = decimal_places - decimal_part_length
    
    if (pad_total > 0) {
        
        // Pad the string with 0s
        for (var counter = 1; counter <= pad_total; counter++) 
            value_string += "0"
        }
    return value_string
}

/**************************************************************
DateAdd(startDate, numDays, numMonths, numYears)

Parameters: 
startDate - the date to be added
numDays - the number of days to add
numMonths - the number of months to add
numYears - the number of years to add
***************************************************************/
function DateAdd(startDate, numDays, numMonths, numYears)
{
	var returnDate = new Date(startDate.getTime());
	var yearsToAdd = numYears;
	
	var month = returnDate.getMonth()	+ numMonths;
	if (month > 11)
	{
		yearsToAdd = Math.floor((month+1)/12);
		month -= 12*yearsToAdd;
		yearsToAdd += numYears;
	}
	returnDate.setMonth(month);
	returnDate.setFullYear(returnDate.getFullYear()	+ yearsToAdd);
	
	returnDate.setTime(returnDate.getTime()+60000*60*24*numDays);
	
	return returnDate;
}

/**************************************************************
daycounter(datestart,dateend)

Parameters: 
datestart - the date to start from
dateend - the date to end at

Returns:
Number of days between the dates
***************************************************************/
function  daycounter(datestart,dateend)
{
	if (!IsDate(datestart))
	{
		return 0;
	}
	if (!IsDate(dateend))
	{
		return 0;
	}
	var endDate = new Date(dateend);
	var startOfYear = new Date(datestart);
	
	var one_day=1000*60*60*24;
	return Math.ceil((endDate.getTime()-startOfYear.getTime())/(one_day));
}

/**************************************************************
formatCurrency(num)

Parameters: 
num - the nubmer to format

Returns:
formated number $0.00
***************************************************************/
function formatCurrency(num) 
{
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

/**************************************************************
StripDollar(Expression)

Parameters: 
Expression - the number to format

Returns:
String with ($) (,) and spaces( ) removed
***************************************************************/
function StripDollar(Expression)
{
	r = "";
	for (i=0; i < Expression.length; i++) {
	  if (Expression.charAt(i) != '$' &&
	      Expression.charAt(i) != ',' &&
	      Expression.charAt(i) != ' ') {
	    r += Expression.charAt(i);
	    }
	  }
	return r;

}

