
var gSafeOnload = new Array();
function SafeAddOnload(f)
{
// Body onload utility (supports multiple onload functions)
// Call the following with your function as the argument
//SafeAddOnload(yourfunctioname);

// Browser Detection
	isMac = (navigator.appVersion.indexOf("Mac")!=-1) ? true : false;
	NS4 = (document.layers) ? true : false;
	IEmac = ((document.all)&&(isMac)) ? true : false;
	IE4plus = (document.all) ? true : false;
	IE4 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 4.")!=-1)) ? true : false;
	IE5 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 5.")!=-1)) ? true : false;
	ver4 = (NS4 || IE4plus) ? true : false;
	NS6 = (!document.layers) && (navigator.userAgent.indexOf('Netscape')!=-1)?true:false;
	if (IEmac && IE4)  // IE 4.5 blows out on testing window.onload
	{
		window.onload = SafeOnload;
		gSafeOnload[gSafeOnload.length] = f;
	}
	else if  (window.onload)
	{
		if (window.onload != SafeOnload)
		{
			gSafeOnload[0] = window.onload;
			window.onload = SafeOnload;
		}		
		gSafeOnload[gSafeOnload.length] = f;
	}
	else
		window.onload = f;
}
function SafeOnload()
{
	for (var i=0;i<gSafeOnload.length;i++)
	{
		gSafeOnload[i]();
	}
}



function showNewWindow (page, height, width, center, left, top, scrollbars, resizable) {
/*
Show a new window
	page		page to show ie: etf.aspx
	height		height of window in pixels
	width		width of window  in pixels
	center		center true or false
	left		left position of window in pixels 0 ignored if center is true
	top			top position of window in pixels 0 ignored if center is true
	scrollbars  show scrollbars true or false
	resizeable	window resizeable true or false
*/


	if (center == true) {
		var myLeft = parseInt((document.body.offsetWidth - parseInt(width))/2 + window.screenLeft );
		var myTop = parseInt((document.body.offsetHeight - parseInt(height))/2 + window.screenTop);
	}
	else {
		myLeft = left;
		myTop = top;
	}

	var myscrollbars = (scrollbars == true ? "yes" : "no");
	var myresizable = (resizable == true ? "yes" : "no");

	var args = "height="+ height + ",width=" + width + ",Left=" + myLeft + ",top=" + myTop + ",resizable=" + myresizable + ",scrollbars=" + myscrollbars + ",status=no,titlebar=no,toolbar=no,menubar=no,location=no";
	var retwin = window.open (page, "_blank", args);
	return retwin;
}

function getParam (q, arg) {
/*
	Get the value of a parameter in a query string
	ie: returns V if q = etf.aspx?mode=V&id=1 and arg = mode
	q = query string
	arg = parameter
*/
	if (q.indexOf(arg) >= 0) {
		var pntr = q.indexOf(arg) + arg.length + 1;
		if (q.indexOf("&", pntr) >= 0) { return q.substring(pntr, q.indexOf("&", pntr)); }
		else { return q.substring(pntr, q.length); }
	}
	else { return null; }
}

function splitParams () {
/*
	Returns an array of the query string parameters and values
	ie: etf.aspx?mode=V&id=1 returns
	[0] = mode=V
	[1] = id=1
*/
	var query = window.location.search;
	tmp = query.split("?");
	return tmp[tmp.length -1].split("&");
}

function setDirtyPage() {
	document.getElementById("BP_bIsDirty").value=true;
}
			
function inputSSN (vSSNName, vSSNValue, e)
{
    // Check browser version
    var isNav4 = false;
    var isNav5 = false;
    var isIE4 = false;
    var strSeperator = "-";
    // If you are using any Java validation on the back side you will want to use the / because
    var err = 0; // Set the error code to a default of zero
    if (navigator.appName == "Netscape")
    {
        if (navigator.appVersion < "5")
        {
            isNav4 = true;
            isNav5 = false;
        }
        else
            if (navigator.appVersion > "4")
        {
            isNav4 = false;
            isNav5 = true;
        }
    }
    else
    {
        isIE4 = true;
    }
    // vSSNName = object name
    // vSSNValue = value in the field being checked
    // e = event
    var whichCode = (window.Event) ? e.which : e.keyCode;
    // Check to see if a seperator is already present.
    // bypass the ssn if a seperator is present and the length greater than 11
    if (vSSNValue.length > 11 && isNav4)
    {
        if ((vSSNValue.indexOf("-") >= 1) || (vSSNValue.indexOf("/") >= 1))
            return true;
    }
    //Eliminate all the ASCII codes that are not valid
    var alphaCheck = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/-";
    if (alphaCheck.indexOf(vSSNValue) >= 1)
    {
        if (isNav4)
        {
            vSSNName.value = "";
            vSSNName.focus();
            vSSNName.select();
            return false;
        }
        else
        {
            vSSNName.value = vSSNName.value.substr(0, (vSSNValue.length - 1));
            return false;
        }
    }
    if (whichCode == 8)
    //Ignore the Netscape value for backspace. IE has no value
        return false;
    else
    {
        //Create numeric string values for 0123456789/
        //The codes provided include both keyboard and keypad values
        var strCheck = '47,48,49,50,51,52,53,54,55,56,57,58,59,95,96,97,98,99,100, 101, 102, 103, 104, 105 ';
        if (strCheck.indexOf(whichCode) != - 1)
        {
            if (isNav4)
            {
            }
            else
            {
                // Non isNav Check
                if (vSSNValue.length == 3)
                {
                    vSSNName.value = vSSNValue + strSeperator;
                }
                if (vSSNValue.length == 6)
                {
                    vSSNName.value = vSSNValue + strSeperator;
                }
                if (vSSNValue.length <= 11) return true;
                return false;
            }
        }
        else
        {
            // If the value is not in the string return the string minus the last
            // key entered.
            if (isNav4)
            {
                vSSNName.value = "";
                vSSNName.focus();
                vSSNName.select();
                return false;
            }
            else
            {
                vSSNName.value = vSSNName.value.substr(0, (vSSNValue.length - 1));
                return false;
            }
        }
    }
}


function inputDate (vDateName, vDateValue, e)
{
    // Check browser version
    var isNav4 = false;
    var isNav5 = false;
    var isIE4 = false;
    var strSeperator = "/";
    // If you are using any Java validation on the back side you will want to use the / because
    var err = 0; // Set the error code to a default of zero
    if (navigator.appName == "Netscape")
    {
        if (navigator.appVersion < "5")
        {
            isNav4 = true;
            isNav5 = false;
        }
        else
            if (navigator.appVersion > "4")
        {
            isNav4 = false;
            isNav5 = true;
        }
    }
    else
    {
        isIE4 = true;
    }
    // vDateName = object name
    // vDateValue = value in the field being checked
    // e = event
    var whichCode = (window.Event) ? e.which : e.keyCode;
    // Check to see if a seperator is already present.
    // bypass the Date if a seperator is present and the length greater than 11
    if (vDateValue.length > 11 && isNav4)
    {
        if ((vDateValue.indexOf("-") >= 1) || (vDateValue.indexOf("/") >= 1))
            return true;
    }
    //Eliminate all the ASCII codes that are not valid
    var alphaCheck = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/-";
    if (alphaCheck.indexOf(vDateValue) >= 1)
    {
        if (isNav4)
        {
            vDateName.value = "";
            vDateName.focus();
            vDateName.select();
            return false;
        }
        else
        {
            vDateName.value = vDateName.value.substr(0, (vDateValue.length - 1))
                ;
            return false;
        }
    }
    if (whichCode == 8)
    //Ignore the Netscape value for backspace. IE has no value
        return false;
    else
    {
        //Create numeric string values for 0123456789/
        //The codes provided include both keyboard and keypad values
        var strCheck = '47,48,49,50,51,52,53,54,55,56,57,58,59,95,96,97,98,99,100, 101, 102, 103, 104, 105 ';
        if (strCheck.indexOf(whichCode) != - 1)
        {
            if (isNav4)
            {
            }
            else
            {
                // Non isNav Check
                if (vDateValue.length == 2)
                {
                    vDateName.value = vDateValue + strSeperator;
                }
                if (vDateValue.length == 5)
                {
                    vDateName.value = vDateValue + strSeperator;
                }
                if (vDateValue.length <= 11) return true;
                return false;
            }
        }
        else
        {
            // If the value is not in the string return the string minus the last
            // key entered.
            if (isNav4)
            {
                vDateName.value = "";
                vDateName.focus();
                vDateName.select();
                return false;
            }
            else
            {
                vDateName.value = vDateName.value.substr(0, (vDateValue.length - 1));
                return false;
            }
        }
    }
}

function formatPhone (phoneNumber) {
	var retStr = phoneNumber;
	if (phoneNumber.length == 7) retStr = phoneNumber.substr(0,3) + "-" + phoneNumber.substr(3,4);
	if (phoneNumber.length == 10) retStr = "(" + phoneNumber.substr(0,3) + ") " + phoneNumber.substr(3,3) + "-" + phoneNumber.substr(6,4);
	return retStr;
}

function validateEmail( strValue) {
/************************************************
DESCRIPTION: Validates that a string contains a
  valid email pattern.

 PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS: Accounts for email with country appended
  does not validate that email contains valid URL
  type (.com, .gov, etc.) or valid country suffix.
*************************************************/
var objRegExp  =
 /(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\.]*)@([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i;

  //check for valid email
  return objRegExp.test(strValue);
}

  function formatNumber(number, format) {  // use: formatNumber(number, "format")
  var separator = ",";  // use comma as 000's separator
  var decpoint = ".";  // use period as decimal point
  var percent = "%";
  var currency = "$";  // use dollar sign for currency

	/*	Examples
		formatNumber(3, "$0.00")
		$3.00
		formatNumber(3.14159265, "##0.####")
		3.1416

		formatNumber(3.14, "0.0###%")
		314.0%

		formatNumber(314159, ",##0.####")
		314,159

		formatNumber(31415962, "$,##0.00")
		$31,415,962.00

		formatNumber(cat43, "0.####%")
		null

		formatNumber(0.5, "#.00##")
		0.50

		formatNumber(0.5, "0.00##")
		0.50

		formatNumber(0.5, "00.00##")
		00.50

		formatNumber(4.44444, "0.00")
		4.44

		formatNumber(5.55555, "0.00")
		5.56

		formatNumber(9.99999, "0.00")
		10.00
	*/

    if (number - 0 != number) return number;  // if number is NaN return the number
	var useSeparator = format.indexOf(separator) != -1;  // use separators in number
    var usePercent = format.indexOf(percent) != -1;  // convert output to percentage
    var useCurrency = format.indexOf(currency) != -1;  // use currency format
    var isNegative = (number < 0);
    number = Math.abs (number);
    if (usePercent) number *= 100;
    format = strip(format, separator + percent + currency);  // remove key characters
    number = "" + number;  // convert number input to string

     // split input value into LHS and RHS using decpoint as divider
    var dec = number.indexOf(decpoint) != -1;
    var nleftEnd = (dec) ? number.substring(0, number.indexOf(".")) : number;
    var nrightEnd = (dec) ? number.substring(number.indexOf(".") + 1) : "";

     // split format string into LHS and RHS using decpoint as divider
    dec = format.indexOf(decpoint) != -1;
    var sleftEnd = (dec) ? format.substring(0, format.indexOf(".")) : format;
    var srightEnd = (dec) ? format.substring(format.indexOf(".") + 1) : "";

     // adjust decimal places by cropping or adding zeros to LHS of number
    if (srightEnd.length < nrightEnd.length) {
      var nextChar = nrightEnd.charAt(srightEnd.length) - 0;
      nrightEnd = nrightEnd.substring(0, srightEnd.length);
      if (nextChar >= 5) nrightEnd = "" + ((nrightEnd - 0) + 1);  // round up

 // patch provided by Patti Marcoux 1999/08/06
      while (srightEnd.length > nrightEnd.length) {
        nrightEnd = "0" + nrightEnd;
      }

      if (srightEnd.length < nrightEnd.length) {
        nrightEnd = nrightEnd.substring(1);
        nleftEnd = (nleftEnd - 0) + 1;
      }
    } else {
      for (var i=nrightEnd.length; srightEnd.length > nrightEnd.length; i++) {
        if (srightEnd.charAt(i) == "0") nrightEnd += "0";  // append zero to RHS of number
        else break;
      }
    }

     // adjust leading zeros
    sleftEnd = strip(sleftEnd, "#");  // remove hashes from LHS of format
    while (sleftEnd.length > nleftEnd.length) {
      nleftEnd = "0" + nleftEnd;  // prepend zero to LHS of number
    }

    if (useSeparator) nleftEnd = separate(nleftEnd, separator);  // add separator
    var output = nleftEnd + ((nrightEnd != "") ? "." + nrightEnd : "");  // combine parts
    output = ((useCurrency) ? currency : "") + output + ((usePercent) ? percent : "");
    if (isNegative) {
      // patch suggested by Tom Denn 25/4/2001
      output = (useCurrency) ? "(" + output + ")" : "-" + output;
    }
    return output;
  }

  function strip(input, chars) {  // strip all characters in 'chars' from input
    var output = "";  // initialise output string
    for (var i=0; i < input.length; i++)
      if (chars.indexOf(input.charAt(i)) == -1)
        output += input.charAt(i);
    return output;
  }

  function separate(input, separator) {  // format input using 'separator' to mark 000's
    input = "" + input;
    var output = "";  // initialise output string
    for (var i=0; i < input.length; i++) {
      if (i != 0 && (input.length - i) % 3 == 0) output += separator;
      output += input.charAt(i);
    }
    return output;
  }

function chkRequiredField (theField, theLabelID) {
	if (theField.value.length <= 0) document.getElementById(theLabelID).innerHTML = "*R"; 
	else document.getElementById(theLabelID).innerHTML = "";
}
		
function showQuestionWindow (buttons, question, postBackValue, postBackFunction, showExclaim) {
	var strExclaim = "";
	if (showExclaim) {
		if (showExclaim == true) strExclaim = "&exclaim=true";
	}
	window.showModalDialog('question.aspx?buttons=' + buttons + '&question=' + question + '&pbval=' + postBackValue + strExclaim, postBackFunction, "dialogHeight: 250px; dialogWidth: 400px; dialogTop: px; dialogLeft: px; edge: Raised; center: Yes; help: No; scroll: No; resizable: No; status: No;");
	//window.showModalDialog('question.aspx?buttons=' + buttons + '&question=' + question + '&pbval=' + postBackValue, postBackFunction, "dialogHeight: 600px; dialogWidth: 800px; dialogTop: px; dialogLeft: px; edge: Raised; center: Yes; help: No; scroll: Yes; resizable: Yes; status: No;");
}

function setCursorToEnd (control) {
  if (control.createTextRange) {
    var range = control.createTextRange();
    range.collapse(false);
    range.select();
  }
  else if (control.setSelectionRange) {
    control.focus();
    var length = control.value.length;
    control.setSelectionRange(length, length);
  }
}

function setCursorToStart (control) {
  if (control.createTextRange) {
    var range = control.createTextRange();
    range.collapse(true);
    range.select();
  }
  else if (control.setSelectionRange) {
    control.focus();
    control.setSelectionRange(0, 0);
  }
}



/*******************************************************************************
FILE: RegExpValidate.js

AUTHOR: Karen Gayda

DATE: 06/11/2000

EMAIL: KGayda@yahoo.com

DESCRIPTION: This file contains a library of validation functions
  using javascript regular expressions.  Library also contains functions that re-
  format fields for display or for storage.
  

  VALIDATION FUNCTIONS:

  validateCurrency - checks for valid currency format including $ - supplies $ if not found
  validateTime - checks for valid 12 hour time
  validateState -  checks for valid state abbreviation  
  validateSSN - checks format of social security number
  validateUSPhone - checks format of US phone number
  validateNumeric - checks for valid numeric value
  validateInteger - checks for valid integer value
  validateNotEmpty - checks for blank form field
  validateUSZip - checks for valid US zip code
  validateUSDate - checks for valid date in US format
  validateValue - checks a string against supplied pattern
  
  FORMAT FUNCTIONS:
  
  rightTrim - removes trailing spaces from a string
  leftTrim - removes leading spaces from a string
  trimAll - removes leading and trailing spaces from a string
  removeCurrency - removes currency formatting characters (), $ 
  addCurrency - inserts currency formatting characters
  removeCommas - removes comma separators from a number
  addCommas - adds comma separators to a number
  removeCharacters - removes characters from a string that match passed pattern
*******************************************************************************/


function validateCurrency( strValue, allowNegative)  {
/************************************************
DESCRIPTION: Validates that a string contains a 
  valid currency format. 
  
 PARAMETERS:
   strValue - String to be tested for validity
   allowNegative - defaults to true if not passed
   
RETURNS:
   True if valid, otherwise false.
*************************************************/
  var negOK = true;
  if (typeof(allowNegative) != 'undefined') negOK = allowNegative;
  if (negOK) strValue = strValue.replace(/-/g, "")
  var strValue = (strValue.indexOf("$") != -1) ? strValue : "$" + strValue;
  var objRegExp = /(^\$\d{1,3}(,\d{3})*\.\d{2}$)|(^\(\$\d{1,3}(,\d{3})*\.\d{2}\)$)/;

  return objRegExp.test( strValue );
}

function validateTime ( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains a 
  valid 12 hour time format. Seconds are optional.
  
 PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.

REMARKS: Returns True for time formats such as:
  HH:MM or HH:MM:SS or HH:MM:SS.mmm (where the
  .mmm is milliseconds as used in SQL Server 
  datetime datatype.  Also, the .mmm portion will 
  accept 1 to 3 digits after the period)
*************************************************/
  var objRegExp = /^([1-9]|1[0-2]):[0-5]\d(:[0-5]\d(\.\d{1,3})?)?$/;

  return objRegExp.test( strValue );

}

function validateState (strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains a 
  valid state abbreviation. 
  
 PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
*************************************************/

var objRegExp = /^(AK|AL|AR|AZ|CA|CO|CT|DC|DE|FL|GA|HI|IA|ID|IL|IN|KS|KY|LA|MA|MD|ME|MI|MN|MO|MS|MT|NB|NC|ND|NH|NJ|NM|NV|NY|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VA|VT|WA|WI|WV|WY)$/i; 

  return objRegExp.test(strValue);
}

function validateSSN( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains a 
  valid social security number. 
  
 PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
*************************************************/
var objRegExp  = /^\d{3}\-\d{2}\-\d{4}$/;
 
  //check for valid SSN
  return objRegExp.test(strValue);

}


function validateUSPhone( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains valid
  US phone pattern. 
  Ex. (999) 999-9999 or (999)999-9999
  
PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
*************************************************/
  var objRegExp  = /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/;
 
  //check for valid us phone with or without space between 
  //area code
  return objRegExp.test(strValue); 
}

function  validateNumeric( strValue ) {
/******************************************************************************
DESCRIPTION: Validates that a string contains only valid numbers.

PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
******************************************************************************/
  var objRegExp  =  /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/; 
 
  //check for numeric characters 
  return objRegExp.test(strValue);
}

function validateInteger( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only 
    valid integer number.
    
PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
******************************************************************************/
  var objRegExp  = /(^-?\d\d*$)/;
 
  //check for integer characters
  return objRegExp.test(strValue);
}

function validateNotEmpty( strValue ) {
/************************************************
DESCRIPTION: Validates that a string is not all
  blank (whitespace) characters.
    
PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
*************************************************/
   var strTemp = strValue;
   strTemp = trimAll(strTemp);
   if(strTemp.length > 0){
     return true;
   }  
   return false;
}

function validateUSZip( strValue ) {
/************************************************
DESCRIPTION: Validates that a string a United
  States zip code in 5 digit format or zip+4
  format. 99999 or 99999-9999
    
PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.

*************************************************/
var objRegExp  = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
 
  //check for valid US Zipcode
  return objRegExp.test(strValue);
}

function validateUSDate( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only 
    valid dates with 2 digit month, 2 digit day, 
    4 digit year. Date separator can be ., -, or /.
    Uses combination of regular expressions and 
    string parsing to validate date.
    Ex. mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy
    
PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
   
REMARKS:
   Avoids some of the limitations of the Date.parse()
   method such as the date separator character.
*************************************************/
  var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2,4}$/
 
  //check to see if in correct format
  if(!objRegExp.test(strValue))
    return false; //doesn't match pattern, bad date
  else{
    var arrayDate = strValue.split(RegExp.$1); //split date into month, day, year
	var intDay = parseInt(arrayDate[1],10); 
	var intYear = parseInt(arrayDate[2],10);
    var intMonth = parseInt(arrayDate[0],10);
	
	//check for valid month
	if(intMonth > 12 || intMonth < 1) {
		return false;
	}
	
    //create a lookup for months not equal to Feb.
    var arrayLookup = { '01' : 31,'03' : 31, '04' : 30,'05' : 31,'06' : 30,'07' : 31,
                        '08' : 31,'09' : 30,'10' : 31,'11' : 30,'12' : 31}
  
    //check if month value and day value agree
    if(arrayLookup[arrayDate[0]] != null) {
      if(intDay <= arrayLookup[arrayDate[0]] && intDay != 0)
        return true; //found in lookup table, good date
    }
		
    //check for February
	var booLeapYear = (intYear % 4 == 0 && (intYear % 100 != 0 || intYear % 400 == 0));
    if( ((booLeapYear && intDay <= 29) || (!booLeapYear && intDay <=28)) && intDay !=0)
      return true; //Feb. had valid number of days
  }
  return false; //any other values, bad date
}

function validateValue( strValue, strMatchPattern ) {
/************************************************
DESCRIPTION: Validates that a string a matches
  a valid regular expression value.
    
PARAMETERS:
   strValue - String to be tested for validity
   strMatchPattern - String containing a valid
      regular expression match pattern.
      
RETURNS:
   True if valid, otherwise false.
*************************************************/
var objRegExp = new RegExp( strMatchPattern);
 
 //check if string matches pattern
 return objRegExp.test(strValue);
}


function rightTrim( strValue ) {
/************************************************
DESCRIPTION: Trims trailing whitespace chars.
    
PARAMETERS:
   strValue - String to be trimmed.  
      
RETURNS:
   Source string with right whitespaces removed.
*************************************************/
var objRegExp = /^([\w\W]*)(\b\s*)$/;
 
      if(objRegExp.test(strValue)) {
       //remove trailing a whitespace characters
       strValue = strValue.replace(objRegExp, '$1');
    }
  return strValue;
}

function leftTrim( strValue ) {
/************************************************
DESCRIPTION: Trims leading whitespace chars.
    
PARAMETERS:
   strValue - String to be trimmed
   
RETURNS:
   Source string with left whitespaces removed.
*************************************************/
var objRegExp = /^(\s*)(\b[\w\W]*)$/;
 
      if(objRegExp.test(strValue)) {
       //remove leading a whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}

function trimAll( strValue ) {
/************************************************
DESCRIPTION: Removes leading and trailing spaces.

PARAMETERS: Source string from which spaces will
  be removed;

RETURNS: Source string with whitespaces removed.
*************************************************/ 
 var objRegExp = /^(\s*)$/;

    //check for all spaces
    if(objRegExp.test(strValue)) {
       strValue = strValue.replace(objRegExp, '');
       if( strValue.length == 0)
          return strValue;
    }
    
   //check for leading & trailing spaces
   objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
   if(objRegExp.test(strValue)) {
       //remove leading and trailing whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}

function removeCurrency( strValue ) {
/************************************************
DESCRIPTION: Removes currency formatting from 
  source string.
  
PARAMETERS: 
  strValue - Source string from which currency formatting
     will be removed;

RETURNS: Source string with commas removed.
*************************************************/
  var objRegExp = /\(/;
  var strMinus = '';
 
  //check if negative
  if(objRegExp.test(strValue)){
    strMinus = '-';
  }
  
  objRegExp = /\)|\(|[,]/g;
  strValue = strValue.replace(objRegExp,'');
  if(strValue.indexOf('$') >= 0){
    strValue = strValue.substring(1, strValue.length);
  }
  return strMinus + strValue;
}

function addCurrency( strValue ) {
/************************************************
DESCRIPTION: Formats a number as currency.

PARAMETERS: 
  strValue - Source string to be formatted

REMARKS: Assumes number passed is a valid 
  numeric value in the rounded to 2 decimal 
  places.  If not, returns original value.
*************************************************/
  var objRegExp = /-?[0-9]+\.[0-9]{2}$/;
   
    if( objRegExp.test(strValue)) {
      objRegExp.compile('^-');
      strValue = addCommas(strValue);
      if (objRegExp.test(strValue)){
        strValue = '($' + strValue.replace(objRegExp,'') + ')';
      }
      else {
        strValue = '$' + strValue;
      }
      return  strValue;
    }
    else
      return strValue;
}

function removeCommas( strValue ) {
/************************************************
DESCRIPTION: Removes commas from source string.

PARAMETERS: 
  strValue - Source string from which commas will 
    be removed;

RETURNS: Source string with commas removed.
*************************************************/
  var objRegExp = /,/g; //search for commas globally
 
  //replace all matches with empty strings
  return strValue.replace(objRegExp,'');
}

function addCommas( strValue ) {
/************************************************
DESCRIPTION: Inserts commas into numeric string.

PARAMETERS: 
  strValue - source string containing commas.
  
RETURNS: String modified with comma grouping if
  source was all numeric, otherwise source is 
  returned.
  
REMARKS: Used with integers or numbers with
  2 or less decimal places.
*************************************************/
  var objRegExp  = new RegExp('(-?[0-9]+)([0-9]{3})'); 

    //check for match to search criteria
    while(objRegExp.test(strValue)) {
       //replace original string with first group match, 
       //a comma, then second group match
       strValue = strValue.replace(objRegExp, '$1,$2');
    }
  return strValue;
}

function removeCharacters( strValue, strMatchPattern ) {
/************************************************
DESCRIPTION: Removes characters from a source string
  based upon matches of the supplied pattern.

PARAMETERS: 
  strValue - source string containing number.
  
RETURNS: String modified with characters
  matching search pattern removed
  
USAGE:  strNoSpaces = removeCharacters( ' sfdf  dfd', 
                                '\s*')
*************************************************/
 var objRegExp =  new RegExp( strMatchPattern, 'gi' );
 
 //replace passed pattern matches with blanks
  return strValue.replace(objRegExp,'');
}

 var selRowOverColor = "cornflowerblue";
 var selRowSelectedColor = "cornflowerblue";
 //document.write ("<input type='hidden' id='selRowitemIdentifier' value=''>");
 function selRowMouseover (theRowObject) {
	rowcolor=theRowObject.style.backgroundColor;
	theRowObject.style.backgroundColor=selRowOverColor;
	theRowObject.style.cursor = "hand";
 }
 function selRowMouseout (theRowObject) {
	theRowObject.style.backgroundColor=rowcolor;
 }
 /*
 function selRowclick (theRowObject, itemIdentifier) {
	document.getElementById("selRowitemIdentifier").value = itemIdentifier;
 	theRowObject.style.backgroundColor=selRowSelectedColor;
 	rowcolor=theRowObject.style.backgroundColor;
}
*/

function objectExists(strObjectName) {
	itExists = true;
	try {
		obj = eval(strObjectName);
		if (!obj) itExists = false;
	}
	catch (e) {
		itExists = false;
	}
	return itExists;
}


function KeyDownHandler(btn)
{
    // process only the Enter key
    if (event.keyCode == 13)
    {
        // cancel the default submit
        event.returnValue=false;
        event.cancel = true;
        // submit the form by programmatically clicking the specified button
        btn.click();
    }
}

function ignoreDirtyPage() {
/*
	Overrides the check for Dirty page function in the base page
	for a single postback
*/
	var ctlIgnoreDirtyPage = document.getElementsByName("BP_bIgnoreDirtyPage")[0];
	if (ctlIgnoreDirtyPage) ctlIgnoreDirtyPage.value=true;
}






// ---------------------------
// Legal
// ---------------------------
// CastleBusyBox Control
// Castle Rock Software, LLC
// by Mark Wagner
// http://www.crsw.com
//
// Version: 1.2
//
// Copyright 2004, 2005 Castle Rock Software, LLC
// No warranty express or implied.

// ---------------------------
// General Notes
// ---------------------------
// The BusyBox javascript has been written so the BusyBox javascript
// control can be used with or without the Castle.BusyBox .NET control.

// ---------------------------
// Constructor
// ---------------------------
// BusyBox class constructor
// Arguments:
//   id - id of the IFrame tag to use.
//   varName - name of the variable this instance of the busy box is assigned to.
//   imageCount - number of image in the animation sequence.
//   imageNamePrefix - name prefix for each image.
//   imageNameSuffix - name suffix for each image.
//   imageDelay - number of milliseconds to display each image.
//   width - defines the width of the busy box (required for Netscape and Firefox)
//   height - defines the height of the busy box (required for Netscape and Firefox)
//   url - (optional) url to the page containing the custom busy box layout.
//
//   This example uses the default busy box layout defined internally (in the javascript).
//   var busyBox = new BusyBox("BusyBox1", "busyBox", 4, "gears_ani_", ".gif", 125, 147, 206)
//
//   This example uses a custom busy box layout defined in the BusyBox.aspx file.
//   var busyBox = new BusyBox("BusyBox1", "busyBox", 4, "gears_ani_", ".gif", 125, 147, 206, "BusyBox.aspx")
//
function BusyBox(id, varName, imageCount, imageNamePrefix, imageNameSuffix, imageDelay, width, height, url)
{
	// Initialize object
	this.id = id;
	this.ImageCount = imageCount;
	this.CurrentImageIndex = 0;
	this.ImageWidth = 0;
	this.ImageHeight = 0;
	this.ImageNamePrefix = imageNamePrefix;
	this.ImageNameSuffix = imageNameSuffix;
	this.ImageDelay = imageDelay;
	this.DivID = "BusyBoxDiv";
	this.ImgID = "BusyBoxImg";
	this.Enabled = true;
	this.Width = width;
	this.Height = height;
	
	// Retain the name of the instantiated object variable so that we can animate 
	// using the setTimeout statement
	this.VarName = varName;
	
	// Allows us to stop the animation with clearTimeout(), should we ever want to
	this.timeout_id = null;
	
	// Cache (pre-load) images
	this.CacheImages();
	
	// Url to the page containing the busy box.
	this.BusyBoxUrl = url;
	
	// Get reference to the IFrame object
	this.IFrame = document.getElementById(this.id);
	
	// Hide the busy box
	this.Hide();
	
	if( this.BusyBoxUrl )
		// Load the busy box contents using a custom layout page.
		this.LoadUrl(this.BusyBoxUrl);
	else
		// Load the busy box contents using the internally defined layout.
		this.RenderContent();
	
	// If this browser does not support IFRAME tags then disable this control.  The
	// next version will implement the use of a DIV instead of the IFRAME tag; 
	// even though there are a couple minor issues with using DIV tags.
	if( !frames[this.id] )
		this.Enabled = false;
}

// --------------------------------
// Instance Methods
// --------------------------------

// GetIFrameDocument:
// Returns a reference to the document object in the IFrame.
BusyBox.prototype.GetIFrameDocument = function()
{
	var doc;
	
	if( this.IFrame.contentDocument )
		// For NS6
		doc = this.IFrame.contentDocument; 
	else if( this.IFrame.contentWindow ) 
		// For IE5.5 and IE6
		doc = this.IFrame.contentWindow.document;
	else if( this.IFrame.document )
		// For IE5
		doc = this.IFrame.document;
	else
// TODO: Confirm this should be the default
		doc = this.IFrame.document;
	
	return doc;
}

// LoadUrl:
// Changing the src attribute for an IFrame tag causes each new page to be 
// added to the browsers history object.  This causes undesired results for 
// the user when they click the back button.  Instead, we can use the 
// document.location.replace() method to correctly load our busy box 
// page into our IFrame.
//
// Arguments:
//		url - url to the busy box page.
BusyBox.prototype.LoadUrl = function(url)
{
	// Get a reference to the document object in the IFrame
	var IFrameDoc = this.GetIFrameDocument();
	
	// Load the url using the replace method.  This will prevent the browsers 
	// history object from being updated with the new busybox url; thus allowing 
	// the back button to function as desired for the user.
	IFrameDoc.location.replace(url);
}

// RenderContent:
// This method is used when the default busy box layout is used; not a custom 
// layout.  This method is called when the url argument for the constructor is null.
BusyBox.prototype.RenderContent = function()
{
	// Get the IFrame document object
	var doc = this.GetIFrameDocument();
	
	var style = " style='BORDER: navy 3px solid; POSITION: absolute;' ";
	
	doc.open();
	doc.writeln("<body ondragstart='return false;' style='Margin: 0px; Background-Color: white'>");
	doc.writeln("   <div id='" + this.DivID + "' align=center " + style + ">");
	doc.writeln("      <img id='" + this.ImgID + "' src=''>");
	doc.writeln("      <br><h3>Processing</h3>");
	doc.writeln("   </div>");
	doc.writeln("</body>");
	doc.close();
}

// Resize:
// Resizes the busy box IFrame by setting its width and height attributes
// to the size of its contents.
BusyBox.prototype.Resize = function()
{
	// Resize the busy box IFrame.
	if( BusyBox.IsBrowserIE() )
	{
		// Set the width by looking at its contents
		var div = frames[this.id].document.getElementById(this.DivID);
		this.IFrame.style.width = div.offsetWidth;
		this.IFrame.style.height = div.offsetHeight;
	}
	else
	{
		// Set the width to the value specified.
		this.IFrame.style.width = this.Width;
		this.IFrame.style.height = this.Height;
	}
}

// Center:
// Centers the busy box IFrame on the page regardless of the browsers
// scroll position.  This ensures the busy box is presented to the user
// in a visible location in the window.
BusyBox.prototype.Center = function()
{
	if( !this.IFrame )
		return;
	
	// Center the BusyBox in the window regardless of the scroll positions
	var objLeft = (document.body.clientWidth - this.IFrame.offsetWidth) / 2;
	var objTop = (document.body.clientHeight - this.IFrame.offsetHeight) / 2;
	objLeft = objLeft + document.body.scrollLeft;
	objTop = objTop + document.body.scrollTop;
	
	// Position object
	this.IFrame.style.position = "absolute";
	this.IFrame.style.top = objTop;
	this.IFrame.style.left = objLeft;
}

// CacheImages:
// Pre-loads the images from the server and stores a reference to each
// image.  This allows the images to be presented to the user quickly
// for smooth image animation.
BusyBox.prototype.CacheImages = function()
{
	// Instantiate the array to store the image references
	this.Images = new Array(this.ImageCount);
	
	// Load all the images to cache into the aniframes array
	for(var i = 0; i < this.ImageCount; i++)
	{
		this.Images[i] = new Image();
		this.Images[i].src = this.ImageNamePrefix + i + this.ImageNameSuffix;
	}
}

// IsAnimating:
// Returns a boolean value representing the state of the animation.
BusyBox.prototype.IsAnimating = function()
{
	if( this.timeout_id == null)
		return false;
	else
		return true;
}

// IsVisible:
// Returns a boolean value representing the visibility state for the busy box.
BusyBox.prototype.IsVisible = function()
{
	var ifrm = document.getElementById(this.id);
	
	if( ifrm.style.visibility == "visible" && ifrm.style.width > 0 )
		return true;
	else
		return false;
}

// Animate:
// Performs the animation process.  This is accomplished by showing the "current" 
// image in the animation sequence process; and then submitting a timed statement
// to execute in x number of milliseconds.
BusyBox.prototype.Animate = function()
{
	// Assign the current image sequence to display
	if( frames[this.id] )
		// browser supports frames
		frames[this.id].document.getElementById(this.ImgID).src = this.Images[this.CurrentImageIndex].src;
	else
		// browser does not support frames
		document.getElementById(this.ImgID).src = this.Images[this.CurrentImageIndex].src;
	
	// Auto re-center and re-size the busy box.  This will force the busy box to 
	// always appear in the center of the window even if the user scrolls.
	this.Resize();
	this.Center();
	
	// Increment the current image index
	this.CurrentImageIndex = (this.CurrentImageIndex + 1)%this.ImageCount;
	
	// Display the next image in (imageDelay value) milliseconds (i.e. 125)
	this.timeout_id = setTimeout(this.VarName + ".Animate();", this.ImageDelay);
}

// StartAnimation:
// Starts the animation process.
BusyBox.prototype.StartAnimate = function()
{
	if( this.IsAnimating() )
		return;
	
	this.Animate();
}

// StopAnimation:
// Stops the animation process.
BusyBox.prototype.StopAnimate = function()
{
	clearTimeout(this.timeout_id);
	this.timeout_id = null;
}

// Hide:
// Hides the busy box making it invisible to the user.
BusyBox.prototype.Hide = function()
{	
	this.StopAnimate();
	
	// Hide the busy box.
	this.IFrame.style.visibility = "hidden";
	this.IFrame.style.width = 0;
	this.IFrame.style.height = 0;
}

// Show:
// This function displays the busy box to the user.  This function centers the 
// busy dialog box, makes it visible, and starts the animation.  This function 
// will typically be called by the body event.
//
// Example:
//		<body onbeforeunload="busyBox.Show();" >
BusyBox.prototype.Show = function(Title, Message)
{
	if( !this.Enabled )
		return;
		
	if( this.IsAnimating() || this.IsVisible() )
		return;	
	
	if (Title) {
		var bbTitle = frames[this.id].document.getElementById("BusyBoxTitle");
		bbTitle.innerHTML = Title;
	}
	if (Message) {
		var bbMessage = frames[this.id].document.getElementById("BusyBoxMessage");
		bbMessage.innerHTML = Message;
	}

	this.Resize();
	this.Center();
	
	// Set the busy box to be visible and make sure it is on top of all other controls.	
	this.IFrame.style.visibility = "visible";
	this.IFrame.style.zIndex = "999999";
	

	// Start the animation
	this.StartAnimate();
}

// --------------------------------
// Class Methods
// --------------------------------

// IsBrowserIE:
// Returns true if the executing browser it a Microsoft Internet Explorer browser.
BusyBox.IsBrowserIE = function()
{
	try
	{ return (window.navigator.userAgent.indexOf("MSIE ") > 0); }
	catch(x)
	{ return false; }
}

// IsBrowserNS:
// Returns true if the executing browser it a Netscape browser.
BusyBox.IsBrowserNS = function()
{
	try
	{ return (window.navigator.userAgent.indexOf("Netscape") > 0); }
	catch(x)
	{ return false; }
}

// IsBrowserFirefox:
// Returns true if the executing browser it a Firefox browser.
BusyBox.IsBrowserFirefox = function()
{
	try
	{ return (window.navigator.userAgent.indexOf("Firefox") > 0); }
	catch(x)
	{ return false; }
}
 