// Last Update 11/28/2005

/**************************************************************
 findOption(strText,strOption)
 
 Function to fild a string in an option box
 
 Arguments:
   strText :  The object to look for (this)
   strOption: function to do after found

 Usage: onKeyUp="findOption(this.value,'AgencyOrgNumber')" 
 <select name="orgid" query="" onKeyDown="return skipTo(event,choosecompany)" onchange="choosecompany();">
**************************************************************/

function findOption(strText,strOption)
{
     objForm = document.forms[0];
     objSelect = objForm.elements[strOption];
     intStringLength = strText.length;
     for(i=0;i<objSelect.length;i++){
          strDisplayText = objSelect.options[i].text.substring(0,intStringLength);
          if(strDisplayText.toUpperCase() == strText.toUpperCase()){
               objSelect.selectedIndex=i;
               break;
          }
     }
}

function skipTo(e,doThis)
{
	if (e.keyCode == 9)
	{
		// clear on tabs
		theSel = e.srcElement;
		theSel.query = "";
	}
	
	if (e.keyCode == 32 || e.keyCode > 47) 
	{
		theSel = e.srcElement;
		query = theSel.query += String.fromCharCode(e.keyCode);
		window.status = "Query: "+query;
		opt = theSel.options;
		for(var i=0;i<opt.length;i++)
		{
			if(opt[i].text.toUpperCase().substr(0,query.length)==query)
			{
				theSel.selectedIndex = i;
				return false;
			}
		}
		theSel.query = "";
		window.status = "Query: "+query+" (not found)";
		doThis();
		return false;
	}
	doThis();
	return true;
}

/**************************************************************
 nothing()
 
 Function to do nothing
**************************************************************/
function nothing()
{
	return true;
}

/**************************************************************
 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;

}

/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}



/**************************************************************
GetFieldById(targetName)
***************************************************************/
function GetFieldById(targetName) {
       if( document.getElementById ) { // NS6+
           target = document.getElementById(targetName);
       } else if( document.all ) { // IE4+
           target = document.all[targetName];
       }
	if( target ) {
          return target;
       }
   }

/**************************************************************
GetFieldByName(targetName)
***************************************************************/
function GetFieldByName(targetName) {
       if( document.getElementByName ) { // NS6+
           target = document.getElementByName(targetName);
       } else if( document.all ) { // IE4+
           target = document.all[targetName];
       }
	if( target ) {
          return target;
       }
   }

/**************************************************************
getCheckedValue(radioObj)
***************************************************************/
// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

/**************************************************************
setCheckedValue(radioObj, newValue)
***************************************************************/
// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}
