

// ********************************************************************************************
// Global Variables
// ********************************************************************************************
// ---------------------------------
// General
// ---------------------------------
var _PageDirtyConfirmMsg    = "Your changes have not been saved.  Click 'OK' to continue (the unsaved changes will be lost) or click 'Cancel' to go back and save your changes.";
var cancelMessageBox = false;
var displayMsg = false;
var timerDelay;
var timerTimeout;
var _error_Messages = new Array();
// ---------------------------------
// Style Names
// ---------------------------------
var _hoverRow_css           = 'hover';
// ---------------------------------
// Cookies
// ---------------------------------
var _cookie_name_eCommerce = "eCommerce";
var _cookie_PersonId = "PersonId";
var _cookie_OrderId = "OrderId";
var _cookie_CustomerKey = "CustomerKey";
var _domain = "";
// ---------------------------------
// Message box styles
// ---------------------------------
var _messagebox_green           = "MessageBoxGreen";
var _messagebox_yellow          = "MessageBoxYellow";
// ---------------------------------
// Admin Variables for lightboxes
// ---------------------------------
var _admin_form_id              = "";
var _admin_fade_div_id          = "";

////////////////////////////////////////////////////////////////////////////////////
//This is a function that will detect a browser 
//if has the right version of IE FF Safari
//and will redirect to BrowserValidation if they don't 
//have the right version of said browsers
//-Zach Teschner
//-7/16/08
/////////////////////////////////////////////////////////////////////////////////////
function DetectValidBrowser()
{
    //__logError('Hit JS', '', '', 2, 0,  false);

    var BrowserDetect = 
    {
        init: function () 
        {
            this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
            this.version = this.searchVersion(navigator.userAgent)
            || this.searchVersion(navigator.appVersion)
            || "an unknown version";
            this.OS = this.searchString(this.dataOS) || "an unknown OS";
        },
        searchString: function (data) 
        {
            for (var i=0;i<data.length;i++)    
            {
                var dataString = data[i].string;
                var dataProp = data[i].prop;
                this.versionSearchString = data[i].versionSearch || data[i].identity;
                if (dataString) 
                {
                    if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
                }
            else if (dataProp)
                return data[i].identity;
            }
        },
        searchVersion: function (dataString) 
        {
            var index = dataString.indexOf(this.versionSearchString);
            if (index == -1) return;
            return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
        },
        dataBrowser: [
            {              
                string: navigator.userAgent,
                subString: "OmniWeb",
                versionSearch: "OmniWeb/",
                identity: "OmniWeb"
            },
            {
                string: navigator.vendor,
                subString: "Apple",
                identity: "Safari"
            },
            {
                prop: window.opera,
                identity: "Opera"
            },
            {
                string: navigator.vendor,
                subString: "iCab",
                identity: "iCab"
            },
            {
                string: navigator.vendor,
                subString: "KDE",
                identity: "Konqueror"
            },
            {
                string: navigator.userAgent,
                subString: "Firefox",
                identity: "Firefox"
            },
            {
                string: navigator.vendor,
                subString: "Camino",
                identity: "Camino"
            },
            {           // for newer Netscapes (6+)
                string: navigator.userAgent,
                subString: "Netscape",
                identity: "Netscape"
            },
            {
                string: navigator.userAgent,
                subString: "MSIE",
                identity: "Explorer",
                versionSearch: "MSIE"
            },
            {
                string: navigator.userAgent,
                subString: "Gecko",
                identity: "Mozilla",
                versionSearch: "rv"
            },
            {   // for older Netscapes (4-)
                string: navigator.userAgent,
                subString: "Mozilla",
                identity: "Netscape",
                versionSearch: "Mozilla"
            },
            {
                string: navigator.vendor,
                subString: "Google",
                identity: "Chrome"
            }
        ],
    dataOS : 
        [
            {
                string: navigator.platform,
                subString: "Win",
                identity: "Windows"
            },
            {
                string: navigator.platform,
                subString: "Mac",
                identity: "Mac"
            },
            {
                string: navigator.platform,
                subString: "Linux",
                identity: "Linux"
            }
        ]
    };
    
    BrowserDetect.init();
    
    //Check allowed browsers
    
    //We were originally detecting if Safari version was greater than 2.  BrowserDetect.version
    //actually returns the webkit version.  Browser version 2.0 = webkit version 412
    
    if (!((BrowserDetect.browser == 'Firefox' && parseFloat(BrowserDetect.version) > 2) 
        || (BrowserDetect.browser == 'Explorer' && parseFloat(BrowserDetect.version) >= 6)
        || (BrowserDetect.browser == 'Safari' && parseFloat(BrowserDetect.version) >= 412)))
    {
        //Redirect
        window.location = 'BrowserValidation.aspx';
    }
}

// ---------------------------------
// Naviagtional
// ---------------------------------
/********************************************************************************************
	Navigation between tabs section  TODO: change old addresses as rewrite progresses
********************************************************************************************/
// ---------------------------------
// Open Window 
// Paramters:
//  url     =    string of source url
//  name    =    string title 
//  attributes = string of attributes for window
// Returns: Open Window
// ---------------------------------
function Open(url,name,attributes)
{
	if(url.length <= 0 )
	{
		alert("Please request a valid page.");
		return false;
	}
	
	win = window.open(url,name,attributes);
	return win;
}
// ---------------------------------
// Common location for opening a window 
// Parameters:
//  page       =    string of page name
//  querstring =    string
//  stepsToRoot  =  string of way to get to root of directory
// Returns: Nothing
// ---------------------------------
function Go(page,querystring,stepsToRoot)
{ 
    // Check parameters
	if(querystring == null) 
	    querystring = "";
	if(stepsToRoot == null) 
	    stepsToRoot = "";
    
    // Initialize variables			
    
    // Check all iframe layers for main_navigation_iframe
    var iframe = document.getElementById("main_navigation_iframe"); 
    if(iframe == null)
    {
		iframe = window.parent.document.getElementById("main_navigation_iframe");
		if(iframe == null)
		{
			iframe = window.parent.parent.document.getElementById("main_navigation_iframe");
		}
    }
              
    // set standard attributes for opening a window
    var _attributes = "top=100,left=100,height=500,width=750,location=no,toolbar=no,scrollbars=yes,resizable=yes";
   
    //check for the iframe, the existence of the function and finally call the function
    if((iframe) && (iframe.IsDirty) && (iframe.IsDirty()))
    { 
		if(!confirm(_PageDirtyConfirmMsg))
			return;
    }
    else
    {  
        if (parent.window.frames['main_navigation_iframe'] != null)
        {
		if(parent.window.frames['main_navigation_iframe'].IsDirty && parent.window.frames['main_navigation_iframe'].IsDirty())
			if(!confirm(_PageDirtyConfirmMsg))
				return;
	    }
    }  
	if(iframe)
	{
		switch(page)
		{
			default:
				alert("A valid page name needs to be passed.  The value: '" + page + "' - was passed.");
				break;
		}
	}else{
		alert("Go could not find the main navigational window.");
	}
}

// ---------------------------------
// This function converts currency to Float data types
// ---------------------------------
function ParseCurrency(controlId) 
{
	var tempValue;
	var floatVal = 0;
	var ctl = document.getElementById(controlId);	
	
	if(ctl != null){
		var value = GetValue(ctl);
		floatVal = ParseCurrencyValue(value);
	}
	
	return floatVal;
}
function ParseCurrencyValue(value)
{
    if (value.indexOf("$") > -1)
    {
		value = value.substring(1, value.length);
	}
	// Strip out the commas
	var result = value.replace(/,/g,"");
	if(result == "")
		result = "0";
	
	var strNew_Result = "";
	for(var i=0;i<result.length;i++)
	{
		if((result.charCodeAt(i) >= 48
			&& result.charCodeAt(i) <= 57)
			|| result.charCodeAt(i) == 46
			|| result.charCodeAt(i) == 45)
		{
			strNew_Result += result.charAt(i);
		}
	};
	floatVal = parseFloat(result);
	return floatVal;
}
// ---------------------------------	
// Handles formating of currency, normally onBlur
// ---------------------------------
function SetDollarAmount(value) 
{ 
	var dec;
	var end;
	var beg;
	var tempValue;
	value = "" + value;

	//strip out all characters other that numbers and periods
	value = value.replace(/[^0-9/\.]/g,"");//   [^0-9\.]  // ^ means not; 0-9 means numbers zero through nine; \. means period; [] means inspect the individual characters and compare each to the regex; /g means keep searching through the whole string; / is the traditional character delimiter

	// Strip out the commas
	value = value.replace(/,/g,"");
	
	// Strip out the dollar signs
	value = value.replace(/\$/g,"");
	dec = value.indexOf(".");
	
	end = ((dec > -1) ? "" + value.substring(dec, value.length) : ".00");
	comma = value.indexOf(",");
	
	beg = ((dec > -1) ? "" + value.substring(0, dec) : value);
	end = ((dec > -1) ? "" + value.substring(dec + 1,value.length) : "00");

	// Strip out the decimal points
	beg = beg.replace(/\./g,"");
	end = end.replace(/\./g,"");

	if (beg.length == 0){
		beg = "0";
	}

		// If the parsed value is bigger than tha allowable value for the ParseInt function
		// Then do not parse the value.
	tempValue = "" + parseInt(beg);

	if (tempValue <= 999999999999999){
			value = "" + parseInt(beg);
	}
	else{
			value = beg;
	}
	
	if ((CheckNumber(value) == 0) || (CheckNumber(end) == 0)){
			value="$0.00";
	} 
	else {
		// Make sure the end is the right size
		switch (end.length) {
			case 2:
				// size is correct
				break;
			case 1:
				end = end + "0";
				break;
			case 0:
				end = "00";
				break;
			default:
				// more than two decimal places. remove extra
				end = end.substring(0,2);
		}
   		end = "." + end;
	
		// Now put the commas back in
		var temp1 = "";
		var temp2 = "";

		var count = 0;
		for (var k = value.length-1; k >= 0; k--){
			var oneChar = value.charAt(k);
			if (count == 3){
				temp1 += ",";
				temp1 += oneChar;
				count = 1;
				continue;
			}
			else{
				temp1 += oneChar;
				count ++;
	   		}
		}
		for (var k = temp1.length-1; k >= 0; k--){
			var oneChar = temp1.charAt(k);
			temp2 += oneChar;
		}
		value = "$" + temp2 + end;
	}
	return value;
}

// ---------------------------------
// Round decimals
// ---------------------------------
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)
}

// ---------------------------------
// padding zero's
// ---------------------------------
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
}
//----------------------------------------------------------//
// Gets the control of the Id and handles if the control is //
//  not found.                                              //
// Parameters:                                              //
//  string id of the control                                //
//  (optional) bool on if to notify on failure              //
//----------------------------------------------------------//
function Get(id, useAlert)
{
    var ctrl = document.getElementById(id);
    if (ctrl)
        return ctrl;
    else if (useAlert != null)
        //Notify client
        AddError('Javascript Error: Control not found on page. Control Id: ' + id);
}
//----------------------------------------------------------//
// Gets the control of the Id and then calls the GetValue   //
// function to complete the task.                           // 
//----------------------------------------------------------//
function GetValueById(id)
{
	var ctl = document.getElementById(id);
	return GetValue(ctl);
}

//----------------------------------------------------------//
//Validates the value of a contol to accomodate DropDowns   //
//which have different object structure                     //
//----------------------------------------------------------//
function GetValue(ctl)
{
    // Check valid ctl
	if(ctl == null){
		return "";
	}

	// Check dropdown
	if (ctl.type == "select-one")
	{
		var itmSelected = ctl.options.selectedIndex;
		return ctl.options[itmSelected].value;	
	}
	// Check if Span
	else if(ctl.tagName == 'SPAN')
	{
	    return ctl.innerText;
	}
	// Default
	else 
	{
		if(ctl.value.length == 0)
		{
			return "";
		}
		else
		{
			return ctl.value;
		}
	}
}

// ---------------------------------
// check to see if the data is a valid currency number
// ---------------------------------
function CheckNumber(data) 
{       
	var valid = "0123456789.$,";     // are valid numbers or a "."
	var ok = 1; var checktemp;
	for (var i=0; i < data.length; i++){
		checktemp = "" + data.substring(i, i+1);
		if (valid.indexOf(checktemp) == "-1") return 0; 
	}
	return 1;
}
//---------------------------------------------------------//
//Returns the record selected in the grid				   //
//---------------------------------------------------------//
function RecordReturn(returnValue)
{	window.parent.returnValue = returnValue;
	window.close();	
}

//---------------------------------------------------------//
//Sets the cookie value when a grid item is selected	   //
//---------------------------------------------------------//
function SetCookie(name,value,expires,domain){	
	path = "/";
	if(expires != null){
		var d = new Date(expires);
		expires = d.toGMTString();
	}
	if(domain == null) domain = _domain;	//use the global "_domain"
	document.cookie = name.toLowerCase() + "=" + escape(value) +
    ((expires) ? "; expires=" + expires : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain.toLowerCase() : "");
}

//----------------------------------------------------------
//Sets the various cookie values
//----------------------------------------------------------
function SetSecurityCookie(personId,customerKey,orderId,expires,domain){	
	path = "/";
	if(expires != null){
		var d = new Date(expires);
		expires = d.toGMTString();
	}
	if(domain == null) domain = _domain;	//use the global "_domain"
	document.cookie = _cookie_name_eCommerce.toLowerCase() + "=" + 
	("&" + _cookie_PersonId.toLowerCase() + "=" + personId) +
	("&" + _cookie_CustomerKey.toLowerCase() + "=" + customerKey) +
	("&" + _cookie_OrderId.toLowerCase() + "=" + orderId) +
    ((expires) ? "; expires=" + expires : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain.toLowerCase() : "");
}

//----------------------------------------------------------
//Clears the cookie
//----------------------------------------------------------
function Logout(ck)
{
    SetCookie('', '', '', '');
    SetSecurityCookie('', ck, '', '', '');
    
    var ctrl = document.getElementById('hdnVirtualDirectory');
    var virtualDirectory = '';
    
    if(ctrl)
        virtualDirectory = ctrl.value;
    
    var url = GetWebRoot() + virtualDirectory + '/Shopping.aspx';
    
    window.open(url, '_self');
}

/** Old Admin Logout functionality (replaced with the Logout function above
function AdminLogout(ck)
{
    SetCookie('', '', '', '');
    SetSecurityCookie('', ck, '', '', '');
    //window.open(GetWebRoot() + '/eCommerce/Shopping.aspx','_self');
    //window.open('/eCommerce/Shopping.aspx','_self');
}
*/

//----------------------------------------------------------
//Returns a certain value of the cookie
//----------------------------------------------------------
function GetSecurityCookieKeyValue(key)
{
    //_cookie_name_eCommerce
//    var cookie = new String(document.cookie);
//    var temp;
    
//    var pairs = cookie.split(';');
    
//    for(var j=0; j<pairs.length; j++)
//    {
//        if(pairs[j].indexOf(name.toLowerCase())>0)
//        {
//            pair = SafeTrim(pairs[j]);
//            
//            if (pair.length > name.length)
//            {
//                pair = new String(pair.substring(name.length + 1));
//                
//                var a = temp.split("&");
//		
//                for(var i=0; i<a.length; i++)
//                {
//		            var s = a[i];
//		            var b = s.split("=");

//		            if(b[0].toString().toLowerCase() == key.toLowerCase())
//		                return b[1];
//	              }
//            }
//        }
//    }

    var value = GetCookie(_cookie_name_eCommerce);
    var key_val = GetCookieKeyValue(value,key);
    
    if(key_val && key_val!="")
        return key_val
     else
        return "0";
}
//---------------------------------------------------------//
//Gets the cookie value of the named crumb             	   //
//---------------------------------------------------------//
function GetCookie(name) 
{
	var cookie = new String(document.cookie);

	if(cookie.indexOf(name.toLowerCase()) < 0)
	{
		return "";
	}
	else
	{
		var a = cookie.split("; ");
		
		for(var i=0; i<a.length; i++)
		{
			var s = a[i];
			var b = s.split("=",1);
            
			if(b[0].toString().toLowerCase() == name.toLowerCase())
			{
				return s.slice(s.indexOf('=',0)+1,s.length);
			}
		}
	}
	return "";
}
//---------------------------------------------------------//
//Gets the key value from a cookie name value pair         //
//---------------------------------------------------------//
function GetCookieKeyValue(value,key)
{
    if(value && key && value!="" && key!="")
    {
        var a = value.split("&");

        for(var i=0; i<a.length; i++)
        {
            var s = a[i];
            var b = s.split("=");

            if(b[0].toString().toLowerCase() == key.toLowerCase())
                return b[1];
          }
    }
    
    return "";
}
//---------------------------------------------------------//
//	Encodes a URL										   //
//---------------------------------------------------------//
function URLEncode(url){
	if(url==null){
		return "";
	}
	
	var s = new String("");
	if(window.encodeURIComponent){
		s = window.encodeURIComponent(url)
	}else{
		if(window.escape){
			s = window.escape(url);
		}else{
			s = url;
		}
	}
		//remove any single quotes (apostrophes)
	return s.replace("'","%27");
}

//---------------------------------------------------------//
//	Hides an object by turning off visibility and display  //
//---------------------------------------------------------//
function Hide(id){
	var el = document.getElementById(id);
	if(el){
		el.style.display = "none";
		el.style.visibility = "hidden";
	}
}

// ---------------------------------
// Show element
// ---------------------------------
function Show(id){
	var el = document.getElementById(id);
	if(el){
		el.style.display = "block";
		el.style.visibility = "visible";
	}
}
// ---------------------------------
// Enables an object on the page if exists    
// ---------------------------------
function Enable(id){
	var el = document.getElementById(id);
	if(el){
		el.disabled = false;
	}
}

// ---------------------------------
// Disables an object on the page if exists 
// ---------------------------------
function Disable(id){
	var el = document.getElementById(id);
	if(el){
		el.disabled = true;
	}
}
//---------------------------------------------------------//
//	Parses for a Query String Parameter					   //
//---------------------------------------------------------//
function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
  alert('Query Variable ' + variable + ' not found');
}
//----------------------------------------------------------//
//	PreventPostBack: prevents an event from bubbling		//
//				in essence, this prevents a postback		//
//----------------------------------------------------------//
function PreventPostBack(event)
{
    if (event && event.preventDefault) 
    {
        event.preventDefault();
        event.stopPropagation();
    } 
    else 
    {
      window.event.returnValue = false;
      window.event.cancelBubble = true;
    }
}

//----------------------------------------------------------//
//	IsValidEmail: validates an email address with following	//
//	bool			rule: one_char@one_char.one_char		//
//----------------------------------------------------------//
function IsValidEmail(email_address)
{
	//USE SAME REGEX AS IN HANDLERS.UTILITY.ISVALIDEMAIL()
	if(email_address.match(/^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/))
		return true;
	else
		return false;
}
// ---------------------------------
// ---------------------------------
function Spell_Checker_By_Control_Array(oControls)
{
	var myWord = new ActiveXObject('word.Application');
	if(myWord)
	{
		//Initialize Word
		myWord.WindowState = 2;
		myWord.Application.visible = true;
		var myDoc = myWord.Documents.Add();
		
		//loop through all of the controls in the array.
		if(oControls)
		{
			for (var i=0; i<oControls.length; i++)
			{
				myDoc.Content = oControls[i].value;
				myDoc.CheckSpelling();
				oControls[i].value = myDoc.Content;
			}
		}
		else
			alert("There are no controls on which to check spelling.");

		//Cleanup Word			
		myDoc.Close(0);
		myWord.Quit(0);
	}
	else
		alert('Unable to open Microsoft Word.  It must be installed to run spell check.');
}
// ---------------------------------
// ---------------------------------
function IsValidDate(dateStr)
{
	// Checks for the following valid date formats:
	// MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
	// Also separates date into month, day, and year variables
	
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;
	
	// To require a 4 digit year entry, use this line instead:
	// var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
	
	var matchArray = dateStr.match(datePat); // is the format ok?
	if (matchArray == null) //alert("Date is not in a valid format.")
		return false;

	month = matchArray[1]; // parse date into variables
	day = matchArray[3];
	year = matchArray[4];
	if (month < 1 || month > 12) //alert("Month must be between 1 and 12.");
		return false;

	if (day < 1 || day > 31) //alert("Day must be between 1 and 31.");
		return false;

	if ((month==4 || month==6 || month==9 || month==11) && day==31) //alert("Month "+month+" doesn't have 31 days!")
		return false

	if (month == 2)
	{ 	// check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day>29 || (day==29 && !isleap)) //alert("February " + year + " doesn't have " + day + " days!");
			return false;
	}
	return true;  // date is valid
}
//----------------------------------------------------------//
//	IsValidAreaCode:										//
//	bool													//
//----------------------------------------------------------//
function IsValidAreaCode(val)
{
	var IsValid = true;
	var moneyRegex=/\d{3}/;
	
	if (!areacodeRegex.test(val) || val.length>3)
	{
		IsValid = false
	
	}	
	
	return IsValid;
}
//----------------------------------------------------------//
//	IsValidPhoneRoot:										//
//	bool													//
//----------------------------------------------------------//
function IsValidPhoneRoot(val)
{
	var moneyRegex=/^(?!\d[1]{2}|[5]{3})([2-9]\d{2})([. -]*)\d{4}$/;
	return moneyRegex.test(val);
}
//----------------------------------------------------------
//	IsValidFullPhone:
//  Examples (where n is a number between 0-9)
//      Matches:
//      (nnn)nnn-nnnn
//      (nnn) nnn-nnnn
//      (nnn)nnn nnnn
//      (nnn)nnn.nnnn
//      (nnn) nnn.nnnn
//      nnnnnnnnnn
//      nnn nnn nnnn
//      nnn-nnn-nnnn
//      nnn-nnn nnnn
//      nnn nnnn
//      nnnnnnn
//      nnn-nnnn
//      Not Matches:
//      (nn) nnn.nnnn
//      (nnn)  nnn-nnnn
//      nn-nnnnn
//      nnn-nn
//      (nn)nnnnn
//	Returns:
//      bool
//----------------------------------------------------------
function IsValidFullPhone(val)
{
   
	var phoneRegex = /^((\(\d{3}\)(\s?)?|\d{3}([ .-])?)?)?(\d{3})([. -])?(\d{4})$/;
	return phoneRegex.test(val);
}
//----------------------------------------------------------//
//	IsValidMoney:											//
//	bool													//
//----------------------------------------------------------//
function IsValidMoney(val)
{
	var moneyRegex=/^\$?[0-9\,]+(\.\d{2})?$/;
	return moneyRegex.test(String(val).replace(/^\s+|\s+$/g, ""));
}
//----------------------------------------------------------//
//	SafeTrim:	    										//
//	bool													//
//----------------------------------------------------------//
function SafeTrim(str)
{  
    str += '';
    
	while(str.charAt(0) == (" ") )
	{  
		str = str.substring(1);
	}
	while(str.charAt(str.length-1) == " " )
	{  
		str = str.substring(0,str.length-1);
	}
	return str;
}
//----------------------------------------------------------//
//	SafeInt:	    										//
//	bool													//
//----------------------------------------------------------//
function SafeInt(val)
{  
    var ret = 0;
    
    if(!val || val=='')
        val = 0;
    
    if(!isNaN(parseInt(val)))
        ret = parseInt(val);
    
	return ret;
}
//----------------------------------------------------------//
//	SafeBool:	    										//
//	bool													//
//----------------------------------------------------------//
function SafeBool(val)
{  
    var ret = new Boolean(val);

    if(val && val.length > 0 && val.toLowerCase() == 'false')
        ret = false;

	return ret;
}
// ---------------------------------
// ---------------------------------
function IsDateLaterThanToday(dateStr)
{
    var result = false;
    
    var now = new Date();
    var now_day = parseInt(now.getDate());
    var now_month = parseInt(now.getMonth()) + 1; //getMonth returns 0 to 11 instead of 1 to 12
    var now_year = parseInt(now.getFullYear());
	
    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?

    var dt_month = parseInt(matchArray[1]); // parse date into variables
    var dt_day = parseInt(matchArray[3]);
    var dt_year = parseInt(matchArray[4]);
            
    if ((dt_year > now_year) || 
        ((dt_year == now_year) && (dt_month > now_month)) ||
        ((dt_year == now_year) && (dt_month == now_month) && (dt_day > now_day)))
    {
        result = true;
    }
    
    return result;
}
// ---------------------------------
// ---------------------------------
function Is1stDateLaterThan2ndDate(dateStr1, dateStr2)
{
    //alert("inside Is1stDateLaterThan2ndDate");
    
    var result = false;
    
    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
    var matchArray1 = dateStr1.match(datePat); // is the format ok?

    var dt_month1 = parseInt(matchArray1[1]); // parse date into variables
    var dt_day1 = parseInt(matchArray1[3]);
    var dt_year1 = parseInt(matchArray1[4]);

    var matchArray2 = dateStr2.match(datePat); // is the format ok?

    var dt_month2 = parseInt(matchArray2[1]); // parse date into variables
    var dt_day2 = parseInt(matchArray2[3]);
    var dt_year2 = parseInt(matchArray2[4]);

    if ((dt_year1 > dt_year2) || 
        ((dt_year1 == dt_year2) && (dt_month1 > dt_month2)) ||
        ((dt_year1 == dt_year2) && (dt_month1 == dt_month2) && (dt_day1 > dt_day2)))
    {
        result = true;
    }
    
    return result;
}
// ---------------------------------
// Checks if it is numeric including decimal point
// ---------------------------------
function IsNumeric(sText)
{
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;


	for (i = 0; i < sText.length && IsNumber == true; i++) 
	{ 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) 
		{
			IsNumber = false;
		}
	}
	return IsNumber;
}
// ---------------------------------
// Checks if it is numeric values only
// ---------------------------------
function IsOnlyNumeric(sText)
{
    var ValidChars = "0123456789";
	var IsNumber=true;
	var Char;


	for (i = 0; i < sText.length && IsNumber == true; i++) 
	{ 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) 
		{
			IsNumber = false;
		}
	}
	return IsNumber;
}
//***********************************
// Hover Table Functions
//***********************************
function SetHover(ctrl,turnOn,isSelectable) {
    if (ctrl == null)
    {
        ctrl = window.event.srcElement;
        while(ctrl)
        {
            //Check if row is found or if it has gone to far
            if ((ctrl.tagName == 'TR') || (ctrl.tagName == 'BODY'))
                break;
            else
                ctrl = ctrl.parentElement;
        }
    }    
    
    if (ctrl)
    {
        if (turnOn) {
            if (isSelectable)
                ctrl.previousClass = ctrl.className;
            ctrl.className = _hoverRow_css;
        } else {
            //Check if it has been set to hide
            if (ctrl.className == 'Hide')
                return false;
            if ((isSelectable) && (ctrl.previousClass))
                ctrl.className = ctrl.previousClass;
            else
                ctrl.className = '';
        }
    }
    return false;
}
// ---------------------------------
//  Description:
//      Gets the value of the checked radio button from the RadioButtonList in .Net
//  Returns: string
// ---------------------------------
function getValueFromRadioButtonList(ctrlId){
    var ctrl = document.getElementById(ctrlId);
    if (ctrl) {
         for(var i=0; i<ctrl.cells.length; i++) {
            var rb = document.getElementById(ctrlId + '_' + i);
            if (rb) {
                if (rb.checked)
                    return rb.value;
            }
         }
     }
     return "";   
}
// ---------------------------------
// ---------------------------------
function trim(stringToTrim) {
    if(stringToTrim == null)
        return "";
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
// **************************************************
// Error Dispaly Functions
// **************************************************
// -------------------------
// Elements
// -------------------------
var _errors_ErrorDiv_Id             = '_divErrorPanel';
var _errors_HeaderDiv_Id            = '_divErrorLabel';
var _errors_HeaderImg_Id            = '_imgErrorLabel';
var _errors_DetailDiv_Id            = '_divErrorDetail';
var _errors_DetailTbl_Id            = '_tblErrorTable';
// -------------------------
// CssStyles
// -------------------------
var _errors_cssHeader_expand        = 'ErrorPanel_expand';
var _errors_cssHeader_collapse      = 'ErrorPanel_collapse';
var _errors_cssHeader               = 'ErrorPanel_header';
var _errors_cssHeaderImg            = 'ErrorPanel_header_img';
var _errors_cssDetail               = 'ErrorPanel_detail';
// -------------------------
// Images location
// -------------------------
var _errors_imgMinus_Id             = '/Impact/Impact05/Images/minus.bmp';
var _errors_imgPlus_Id              = '/Impact/Impact05/Images/plus.bmp';
var _errors_imgDel_Id               = '/Impact/Impact05/Images/Red_X.gif';
var _errors_imgFlag_Id              = '/Impact/Impact05/Images/RedFlag.gif';
// -------------------------
// Objects
// -------------------------
var _container_cssAttributeName     = 'cssName';
var _container_className            = null;
var _errorCollection                = new Array();
function ErrorObject(msg, isWarn, isRemove, ctrlId)
{
    this.errorId                    = _errorCollection.length;
    this.msg                        = msg;
    this.isWarning                  = isWarn || false;
    this.isRemovable                = isRemove || true;
    this.errorCtrlId                = ctrlId || '';
}
// -------------------------
// Public: Add Error to collection
// Parameters:
//  msg = string of message to display
//  isWarning(optional) = boolean of if the error is a warning
//  isRemovable(optional) = boolean if the item can be removed from the panel
//  ctrlId(optional) = string of the control id to set focus for error message
//  allowDuplicate(optional) = boolean of if the message already exist in the errror collection
// Returns : int of error id created.
// -------------------------
function AddError(msg, isWarning, isRemovable, ctrlId, allowDuplicate)
{
    //Check Parameters
    if (allowDuplicate == null)
        allowDuplicate = true;
    if ((msg == null) || (msg.length == 0))
        return;

    //Check if duplicate messages are
    if ((allowDuplicate == false) && (_Errors_CheckExists(msg)))
        return 0;
        
    //Create new Error Object
    var err = new ErrorObject(msg, isWarning, isRemovable, ctrlId);
    
    //Add Error to collection
    _errorCollection.push(err); 
    
    //Return the new error Id
    return err.errorId;
}
// -------------------------
// Public: Add mulitiple errors to collection displays with default attributes
// Parameters:
//  msgs = array of string messages to display or delimiter string of messages
//  delimiter(optional) = string of delimiter used to split string into array
// Returns : count of errors added
// -------------------------
function AddErrors(msgs, delimiter)
{
    //Check Parameters
    if ((msgs == null) || (msgs.length == 0))
        return 0;
    if ((delimeter != null) && (delimeter.length == 0))
    {
        var msg_array = new Array();
        msg_array = msgs.split(delimiter);
        msgs = new Array();
        msgs = msg_array;
    }
    else
    {
        if (msgs.contstructor.toString().indexOf('Array') == -1)
            return 0;
    }
     
    //counter
    var count = 0;    
        
    //Loop the errors array
    for(var index=0; index<msgs.length; index++)
    {    
        //get msg entry
        var msg = msgs[index];
        
        //Call the add Error function
        AddError(msg);
        
        //increment counter
        count++;
    }
    //Return the new error Id
    return count;
}
// -------------------------
// Public: Removes Error Object from Array collection by ErrorId 
// Parameters : int of the error id in the collection
// Returns: None
// -------------------------
function RemoveError(errorId)
{
    //Validate parameters
    if (errorId == null)
        return;
        
    //temp array
    var arry = new Array();
    
    //Traverse error collection array
    for (var i=0; i<_errorCollection.length; i++)
    {
        //Check if ther passed errorId is not the current error object
        if ( _errorCollection[i].errorId != errorId )
        {
            //Keep the entry
            arry[arry.length] = _errorCollection[i];
        }
    }
    
    //Set the error collection the temp array
    _errorCollection = arry;
}
// -------------------------
// Public: Creates new array for the Error Collection
// Parameters : None
// Returns: None
// -------------------------
function ClearErrors()
{
    _errorCollection = new Array();
}
// -------------------------
// Public: Call point for creating the display errors div on the page
// -------------------------
function DisplayErrors(container_id)
{  
    //Verify Container Div exists and grab the control
    container = document.getElementById(container_id);
    if(container)
    {
        //Check if the container's style class is set
        if (_container_className == null)
        {
            _container_className = eval('container.' +_container_cssAttributeName);
            if (_container_className == null)
                _container_className = '';
        }
        
        //Set container style to default style
        container.className = _container_className;
        
        //Get the error message control
        var errorCtrl = document.getElementById(_errors_DetailDiv_Id);
        
        //Check if the error panel has already been built
        if (errorCtrl == null)
        {
            //
            //Build the error panel
            _BuildErrorsPanel(container);
        }
        
        //Display the errors
        if (_errorCollection.length != 0)
        {
            //Build the error message display
            _BuildErrorMessageDisplay();      
        }
    }
}
// -------------------------
// Private: Build the error div and error header label div 
// -------------------------
function _BuildErrorsPanel(container)
{
    if (container != null)
    {
        //Create Elements
        var divError = document.createElement('DIV');
        var divHeader = document.createElement('DIV');
        var img = document.createElement('IMG');
        var span = document.createElement('SPAN');
        var divDetail = document.createElement('DIV');
        
        //Assign Div Error attributes
        divError.id = _errors_ErrorDiv_Id;
        divError.name = _errors_ErrorDiv_Id;
        divError.className = _errors_cssHeader_expand;
        container.appendChild(divError);
        
        //Assign Div header Attributes
        divHeader.id = _errors_HeaderDiv_Id;
        divHeader.name = _errors_HeaderDiv_Id;
        divHeader.className = _errors_cssHeader;
        divHeader.attachEvent('onclick',_ErrorDetailToggleVisible);
        divError.appendChild(divHeader);
        
        //Assign Img header Attributes
        img.id = _errors_HeaderImg_Id;
        img.name = _errors_HeaderImg_Id;
        img.src = GetWebRoot() + _errors_imgMinus_Id;
        img.className = _errors_cssHeaderImg;
        divHeader.appendChild(img);
        
        //Assign span Header Attributes
        span.className = _errors_cssHeader;
        span.innerText = 'Errors Found';
        divHeader.appendChild(span);
        
        //Assign Div Detail Attributes
        divDetail.id = _errors_DetailDiv_Id;
        divDetail.name = _errors_DetailDiv_Id;
        divDetail.className = _errors_cssDetail;
        divError.appendChild(divDetail);
    }
}
// -------------------------
// Private: Toggle the visibility of the detail section and change the
//  CssStyle of the label control
// -------------------------
function _ErrorDetailToggleVisible ()
{
    //Get Elements
    var detail  = Get(_errors_DetailDiv_Id);
    var error = Get(_errors_ErrorDiv_Id);
    var img = Get(_errors_HeaderImg_Id);
    
    //Handle Toggle Logic
    if (img.src == (GetWebRoot() + _errors_imgMinus_Id))
    {   
        //Collapse 
        img.src = GetWebRoot() + _errors_imgPlus_Id;
        error.className = _errors_cssHeader_collapse;
        detail.className = 'Hide';
    }
    else
    {
        //expand
        img.src = GetWebRoot() + _errors_imgMinus_Id;
        error.className = _errors_cssHeader_expand;
        detail.className = _errors_cssDetail;
    }
}
// -------------------------
// Private: Build the table to display the errors from the
//  error collection object
// -------------------------
function _BuildErrorMessageDisplay()
{
    //Clean up by removing existing table first (if exists).
    var detaildiv = Get(_errors_DetailDiv_Id);
    var tbl = Get(_errors_DetailTbl_Id);
    if ((detaildiv) && (tbl))
        //Remove table from DIV
        detaildiv.removeChild(tbl);
    
    //Create Table
    var tbl = document.createElement('TABLE');
    
    //Set Table Parameters
    tbl.id = _errors_DetailTbl_Id;
    tbl.name = _errors_DetailTbl_Id;
    
    //Creat Tbody element for rows
    var tbody = document.createElement('TBODY');
    
    //Attach tbody to tbl
    tbl.appendChild(tbody);
    
    //Loop through the error collection creating rows
    for(var i=0; i<_errorCollection.length; i++)
    {
        //Use error object
        var errObj = _errorCollection[i];
        
        //Create row
        var row = document.createElement('TR');
        
        //Create remove cell
        var cell = document.createElement('TD');
        
        //Check if remove is allowed
        if (errObj.isRemovable)
        {
            //Add img to remove
            var img = document.createElement('IMG');
            
            //Set img source url
            img.src = _errors_imgDel_Id;
            
            //Set errorId (used for removal of row)
            img.errorId = errObj.errorId;
            
            //Add remove event
            img.attachEvent('onclick',_RemoveErrorRow_onclick);
            
            //Add Img to Cell
            cell.appendChild(img);
        }
        else
        {
            //Add empty space
            cell.innerText = ' ';
        }
        
        //Append Cell to Row
        row.appendChild(cell);
        
        //Create Text Cell
        var cell = document.createElement('TD');
        
        //Create Text Node
        var txt = document.createTextNode(errObj.msg);
        
        //Add Msg Text to Cell
        cell.appendChild(txt);
        
        //Check if ctrl Id was passed
        if (errObj.errorCtrlId != '')
        {
            //Create img
            var img = document.createElement('IMG');
            
            //Set img source url
            img.src = _errors_imgFlag_Id;
            
            //Set error control Id attribute
            img.errorCtrl = errObj.errorCtrlId;
            
            //Add Img click event
            img.attachEvent('onclick',_Errors_SetFocus);
            
            //Add img to Cell
            cell.appendChild(img);
        }
        
        //Append Cell to Row
        row.appendChild(cell);
        
        //Append Row to tbl
        tbl.firstChild.appendChild(row);
        //tbody.appendChild(row);
    }
    
    //Add table to div
    var detaildiv = Get(_errors_DetailDiv_Id);
    if (detaildiv)
    {
        //Append table
        detaildiv.appendChild(tbl);
    }  
}
// -------------------------
// Event handler for the remove row on click event handler
// Parameters : None
// Returns : None
// -------------------------
function _RemoveErrorRow_onclick()
{
    //Get Source Event and element
    var e = window.event;
    if (e)
    {
        var src = e.srcElement;
    }
    
    //Check if src exists
    if (src)
    {
        //Get error id
        var errorID = src.errorId;
        
        //Get parent row of img
        var row = null;
        
        //Travel up the heirercy of parents to find row (TR)
        while (row == null)
        {
            //Check if parent exists
            if (src.parentElement)
            {
                //Set the src to parent
                src = src.parentElement;
                
                //Check if the src is the row
                if (src.tagName == 'TR')
                    //Set row 
                    row = src;
            }
            else
            {
                //Return case where something wrong happened.
                // just exit the function
                return;
            }    
        }
        
        //Get tbl
        var tbl = Get(_errors_DetailTbl_Id);
        
        //Check if tbl is found
        if ((tbl) && (row))
        {
            tbl.deleteRow(row.rowIndex);
        }
        
        //Remove Item from error collection
        RemoveError(errorID);
        
        //Check if error collection is empty
        if ((_errorCollection.length == 0) && (tbl))
        {
            //Destroy Error Panel
            var errdiv = Get(_errors_ErrorDiv_Id);
            if (errdiv)
            {
                //Get container div
                if (errdiv.parentElement) 
                {
                    //Set parent to container object
                    var parentDiv = errdiv.parentElement;
                    
                    //Remove error panel from container
                    parentDiv.removeChild(errdiv);
                    
                    //Hide child
                    parentDiv.className = 'Hide';
                }
            }
        }
    }    
}
// -------------------------
// Event handler for the set focus click event
// Parameters : Id of ctrl
// Returns : None
// -------------------------
function _Errors_SetFocus()
{
    //Get Source Event and element
    var e = window.event;
    if (e)
    {
        var src = e.srcElement;
    }
    
    //Check if src exists
    if (src)
    {
        //Get error control id
        var ctrlId = src.errorCtrl;
        
        //Get control
        var ctrl = Get(ctrlId);
        
        //Check variable
        if (ctrl)
        {
            //Set control's focus
            ctrl.focus();
        }
    }
}
// -------------------------
// Checks the error collection to see if the passed message already exists
// Parameters : 
//  msg = string of message to check
// Returns : boolean
// -------------------------
function _Errors_CheckExists(msg)
{
    if (msg)
    {
        for(var i=0; i<_errorCollection.length; i++)
        {
            if (msg == _errorCollection[i].msg)
                return true;
        }
    }
    return false;
}
// -------------------------
// Get Root
// Returns:
//  String of basic web root
// -------------------------
function GetWebRoot()
{
    return 'http://' + document.location.hostname;
}

// **************************************************
// Help Dispaly Functions
// **************************************************
// -------------------------
// CssStyles
// -------------------------
var _help_cssMessage            = 'Help_Message_Panel';
// -------------------------
// Objects
// -------------------------
var _help_Message_Suffix        = '_help';
// -------------------------
// Display div with message inside of it
// Parameters:
//  ctrl = control that is going to used for display reference
//  msg = string of message to show
// Returns:
//  nothing
// -------------------------
function Display_Help(ctrl, msg)
{
    //Check parameters
    if ((ctrl == null) || (msg == null) || (msg.length = 0))
        return null;
    
    //Get refence control id
    var ctrlId = ctrl.id;
    
    //Get Reference Control Screen Location
    var refLocation = _findPosition(ctrl);
    
    //Call the build display function
    var div = _buildFloatingDiv(ctrlId + _help_Message_Suffix, msg,refLocation.left,refLocation.top);
    
    if (div)
    {
        //Add to control
        if (ctrl.parentElement)
            ctrl.parentElement.appendChild(div);
    }
}
// -------------------------
// Removes the help box when leaving the help control
// Parameters: None
// Returns: Nothing
// -------------------------
function Hide_Help()
{
    //Get div control
    var src = window.event.srcElement;
    if (src)
    {
        //Get Parent
        if (src.parentElement)
            var parent = src.parentElement;
        if (parent)
        {
            //Remove child
            parent.removeChild(src);
        }
    }
}
// -------------------------
// Build a floating display div
// Parameters:
//  id = string for Id of message div
//  msg = string for innerText
//  left = left location for div
//  top = top location for div
// Returns: 
//  object of ctrl created
// -------------------------
function _buildFloatingDiv(id, msg, left, top)
{
    //Check parameters
    if ((id == null) || (msg == null) || (left == null) || (top == null))
        return null;
   
    //Create div
    var divMessage = document.createElement('DIV');
    
    //Assign Div Parameters
    divMessage.className = _help_cssMessage;
    divMessage.style.left = left;
    divMessage.style.top = top;
    divMessage.innerText = msg;
    divMessage.attachEvent('onmouseout',Hide_Help);
    
    //Check for length
    (msg.length < 50 )? divMessage.style.width = 'auto': divMessage.style.width = '150px';
    
    return divMessage;
}
// -------------------------
// Find the position of the control passed
// Parameters:
//  ctrl = Control object
// Returns:
//  object with left and top attributes, null otherwise
// -------------------------
function _findPosition(ctrl)
{
    if (ctrl)
    {
	    var curleft = 0;
	    var curtop = 0;
	    //window width
	    var wndwidth = document.body.offsetWidth;
	    if (ctrl.offsetParent)
	    {
		    curleft = ctrl.offsetLeft;
		    curtop = ctrl.offsetTop;
		    
		    //Recursive - uses an assignment instead of a comparison operator
		    while (ctrl = ctrl.offsetParent)        
		    {
			    curleft += ctrl.offsetLeft;
			    curtop += ctrl.offsetTop;
		    }
	    }
	    
	    //Ensure the message won't scroll out of window width
	    if ((wndwidth - curleft) < 200)
	    {
	        curleft = curleft - (200 - (wndwidth - curleft));
	    }
	    
	    //Create return object
	    var obj =new Object();
	    obj.left = curleft;
	    obj.top = curtop;
	    return obj;
	}
	return null;
}
// -------------------------
// Test something to see if it is an Array
// Parameters:
//  obj = object to test
// Returns:
//  boolean true or false
// -------------------------
function isArray(obj)
{
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}
// -------------------------
// Test something to see if it is an Object
// Parameters:
//  obj = object to test
// Returns:
//  boolean true or false
// -------------------------
function isObject(obj)
{
   if (obj.constructor.toString().indexOf("Object") == -1)
        return false;
   else
        return true;
}
// -------------------------
// initObjects is a wrapper function that allows you to run the init function of any all the objects within a global object
// this allows for dynamic object creation. There is no need to pass special params or created special functions to each new
// creation of an object, simply enough you can create an object: new myObject(); then you can create a JSON list of parameters
// {param1: "...", param2: "...", ....}
// now you can dynamically create the parameters also (JSON amazingness)
// the nice thing is the name of the params doesn't matter the only thing that is required is that they are in the same order as
// they need to be for the init function.
// The example below shows how it works, NOTE ****: the objects you create can be the same object or entirely different ones
// they can also be the same object with entirely different set of parameters ... NICE... so in essence you can do everything 
// through this one entry point for any object.

//ex:
/*
    var myGlobalObj = ne Object();
    
    myGlobalObj.myObj = 
        new someObject(
            {
                param1: "hi",
                param2: 3,
                param3: "..."
            }
    );
    
    myGlobalObj.anotherMyObject = 
        new someObject(
            {
                param1: "hi",
                param2: 3,
                param3: "...",
                a: 4,
                c: 5,
                WHAT: "abcdefg"
            }
    );
    
    myGlobalObj.yetAnotherMyObject = 
        new someObject(
            {
                param1: null,
                param2: null,
                param3: "...",
                a: 4,
                c: 5,
                WHAT: "abcdefg",
                is: "going",
                on: "whit this object???"
            }
    
    
    ...
    
    function someObject(paramsx)
    {
        this.params = paramsx  //notice this.params and the actual parameters being passed can NOT have the same name, hence the paramsx
        ...
        ...
        ..
        
        this.init(someIDx, someNumberx, someThingx, anotherParam, yetAnotherParam, oneMoreParam, someOtherParam, finalyTheLastParam)
        {
            this.someID = someIDx;
            this.someName = someNamex;
            this.someThing = someThingx;
       }
       
   }
   
   
   so when we call initObjects:
   
   <body onload="initObjects(myGlobalObj);">
   
   it will loop through the myGlobalObj and run the init() function with the params you set when you created the object:
    
    {
        param1: "hi",
        param2: 3,
        param3: "..."
    }

   notice that all 3 objects above have totaly different parameters some even have more than other but!!! they are the SAME OBJECT! ? ? what....
   well:
    the myObj Object's init function will set 3 variables someIDx, someNumberx, someThingx and ignore the rest.
    anotherMyObject will set most of the params and ignore th rest
    yetAnotherMyObject will set the first 3 params to null (in essence not even setting them) but yet it will se all the rest
    
    dynamics at its finest.
    
    One last note, you can pass more parameters than the init function can take, although they wont do anything unless you reference them manualy
    but if you want to pass a style object, you can pass them on the creation of the object and still have a reference to them later via the this.params.style:
    
    {
        param1: "hi",
        param2: 3,
        param3: "...",
        
        style:
        {
            height: '100px',
            width: '50px'
        }
    }

*/
// Parameters:
//  Objs = the Global Object
// Returns:
//  Void
// -------------------------
function initObjects(Objs)
{
    for(var x in Objs)
    {
        var newargs = new Array();    // blank array to hold the current objects parameters
        if(Objs[x] != null)
        {
            for (var y in Objs[x].params)
            {
                newargs.push(Objs[x].params[y]); // add the current objects parameters to the array 1 at a time
            }

            newargs.push(x); // lastly add the object "NAME" to the params
            var currObj = Objs[x]; // copy the reference to the object NOTE: this does not copy the actual object itself it's a local map of where to go to get to the object
            currObj.init.apply(currObj, newargs); // apply the parameters set in our JSON object to the currecnt object we are working on
        }
        else
        {
            _errorCollection.push("Error initiating "+x); // if an error occurs save it!
        }
    }
} 

/* Displays a message box */
function MessageBox(msg,delay,interval,style)
{
    //if style is not set, use yellow
    if (style == null)
        style = _messagebox_yellow;
    
    //if delay is not set, do it imediately
    if (delay == null)
        delay = 0;
    
    //if interval is not set, use five seconds
    if (interval == null)
        interval = 5000;
        
    while (msg.indexOf("'") >= 0)
    {
        msg = msg.replace(/'/,"\"");
    }
    
    if (delay > 0)
    {
        clearTimeout(timerDelay);    
        timerDelay = setTimeout("FinishMessageBox('" + msg + "'," + interval +",'" + style + "')",delay);
    }
    else
        FinishMessageBox(msg,interval,style);
}

function FinishMessageBox(msg,interval,style)
{
    if (cancelMessageBox == false)
    {
        var div = Get('divMessageBox');
        
        //try to get the parent's message box div
        if (!(div))
            div = window.parent.document.getElementById('divMessageBox');
    
        if (div)
        {
            var divBody = Get('divMessageBoxBody');
            
            if (!(divBody))
                divBody = window.parent.document.getElementById('divMessageBoxBody');
        
            if (interval > 0)
                divBody.innerHTML = msg + "<br><br> Closing automatically in " + (interval/1000) + " seconds...";
            else
                divBody.innerHTML = msg;
        
            div.className = style;
        
            if (interval > 0)
            {
                clearTimeout(timerTimeout);
                timerTimeout = setTimeout("CloseMessageBox()",interval);
            }
        }
        else
            alert('Message Box div not found!');
    }
    else
        cancelMessageBox = false;
}

/* Closes message box */
function CloseMessageBox(evt)
{
    //** firefox fires the onmouse event when the mouse is over the popup, this checks to see if the element that fired the close is the popup itself
    var toEl = (evt) ? evt.relatedTarget : (window.event)?event.toElement:null;
    var div = $('divMessageBox');
    
    if (!(div))
        div = window.parent.document.getElementById('divMessageBox');
    
    if(!(toEl && Element.descendantOf(toEl,div)))
    {
        div.className = "hide";
        cancelMessageBox = false;
    }
}

function CancelMessageBox()
{
    clearTimeout(timerDelay);
}
// -------------------------
// Tracks Packages for Ups Only
// Parameters: trackingNumber
// Returns: Brings up a new instance of IE and FireFox then goes to Ups Tracking Site. Needs Tested in Safari.
// -------------------------
function OpenUpsTracking(trackingNumber)
{
    if ( (trackingNumber == '' || trackingNumber == null || trackingNumber.length < 13 || trackingNumber.length > 24) )
        {
//            _error_Messages.push("Please put in a valid tracking number and that there are between 13 and 24 characters.");
            MessageBox("Please ensure that the tracking number is valid and that there are between 13 and 24 characters.",0,0,_messagebox_yellow);
            return;
        } 
//    if(_error_Messages.length > 0)
//            {
//                alert(_error_Messages.join("\n"));  //display all errors, each on their own line
//                _error_Messages = new Array();      //clear the array so we don't get duplicate error messages
//                return false;
//            } 
    var url = ("http://wwwapps.ups.com/etracking/tracking.cgi?InquiryNumber1=" + URLEncode(trackingNumber) + "&TypeOfInquiryNumber=T&AcceptUPSLicenseAgreement=yes&submit=Track");
    Open(url);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Warning:
//This is a get function that will get the actual page width
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function pageWidth() 
{
    return window.innerWidth != null? window.innerWidth: document.body != null? document.body.clientWidth:null;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Warning:
//This is a get function that will get the actual page height
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function pageHeight() 
{
    return window.innerHeight != null? window.innerHeight: document.documentElement != null? document.documentElement.clientHeight:null;
}

//** Browser detection code, only practical for detecting if ie6 is running or not
//** D.lozano 7/2/08
//Client engine detection as found on MooTools, My Object Oriented Javascript Tools. Copyright (c) 2006-2007 Valerio Proietti, <http://mad4milk.net>, MIT Style License.
var Client = {
	Engine: {'name': 'unknown', 'version': ''},
	Platform: {},
	Features: {}
};
//Client.Features
Client.Features.xhr = !!(window.XMLHttpRequest);
Client.Features.xpath = !!(document.evaluate);

//Client.Engine
if (window.opera) Client.Engine.name = 'opera';
else if (window.ActiveXObject) Client.Engine = {'name': 'ie', 'version': (Client.Features.xhr) ? 7 : 6};
else if (!navigator.taintEnabled) Client.Engine = {'name': 'webkit', 'version': (Client.Features.xpath) ? 420 : 419};
else if (document.getBoxObjectFor != null) Client.Engine.name = 'gecko';
Client.Engine[Client.Engine.name] = Client.Engine[Client.Engine.name + Client.Engine.version] = true;

//Client.Platform
Client.Platform.name = navigator.platform.match(/(mac)|(win)|(linux)|(nix)/i) || ['Other'];
Client.Platform.name = Client.Platform.name[0].toLowerCase();
Client.Platform[Client.Platform.name] = true;
// end Client detection -------------------------------- //

// -------------------------
// Coss browser function to get the scroll top and left in pixels
// Parameters: none
// Returns: array of scroll values
// D.Lozano
// 7/8/2008
// -------------------------
function getScrollXY() 
{
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) 
  {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } 
  else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) 
  {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } 
  else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) 
  {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

// -------------------------
// Function to preload images on the page
// Parameters: imageList - comma seperated list of image locations (src)
// Returns: nothing
// D.Lozano
// 8/18/2008
// -------------------------
function PreLoadImages(imageList)
{
    var imageListArray = imageList.split(',');
    var images = new Array();
    var i = 0;
    
    for(i=0;i<imageListArray.length;i++)
    {
        images[i] = new Image();
        images[i].src = imageListArray[i];
    }
}

//***********************************
// Scroll Table Functions
// This function accepts 4 parameters: DIV.ID, TABLE.ID, ROW.ID and if there is a header 
//  row or not (true or false)
// This function automatically scrolls to a specific table row in a DIV
// If the table has cellpadding or cellspacing then this fucntion will not work correctly
// NOTE: make sure horz scroll bars are not visible, otherwise the last visible row will be covered
//***********************************
function ScrollToRow(div,table,row,hasHeader)
{
	var oDiv = document.getElementById(div);
	var oTable = document.getElementById(table);
	var oRow = document.getElementById(row);

	//** Test if the objects exist, if not ignore command
	if(oDiv && oTable && oRow)
	{
		var r = oRow.rowIndex;
		var h = oDiv.clientHeight;
		var i = 0;
		var n = 0;

		for(i=0;i<r+1;i++)
		{
			n += oTable.rows[i].offsetHeight;
		}

		if(n < h)
		{
			oDiv.scrollTop = 0;
		}
		else
		{
			oDiv.scrollTop = n - ((hasHeader) ? (oRow.offsetHeight * 2) : (oRow.offsetHeight)); //If there is a header, subtract 2 rows otherwise, just one
		}
	}
	else
	{
	    alert("The elements necessary for the 'ScrollToRow' function to perform are missing.");
	}
}

//***********************************
// InitAdminPage function
// This function accepts two parameters which are the name of your form and the name
//   name of your fade div
// This function sets window event handlers for onresize and onscroll.
//***********************************
function InitAdminPage(frmname, fadectrl)
{
    _admin_fade_div_id = fadectrl;
    _admin_form_id = frmname;
    
    window.onresize = calcFade;
    window.onscroll = calcFade;
    
    calcFade();
}

//***********************************
// calcFade function
// This function accepts two parameters which are the name of your form and the name
//   name of your fade div
// This function automatically sizes the fade div for the lightbox to the size of the window
//   including the scrollable areas.
//***********************************
function calcFade()
{
    var fade = document.getElementById(_admin_fade_div_id);
    var frm = document.getElementById(_admin_form_id);
    var sz = document.body.parentNode;
    
    if(fade && frm && sz)
    {
        fade.style.left = "-" + frm.offsetLeft + "px";
        fade.style.top = "-" + frm.offsetTop + "px";
    
        fade.style.width = sz.scrollWidth + "px";
        fade.style.height = sz.scrollHeight + "px";
    }
}
function __logError(detail, stackTrace, debug, customerKey, personId,  displayMsg)
{   
    var params = "detail=" + detail + "&stackTrace=" + stackTrace + "&debug=" + debug + "&customerKey=" + _customerKey + "&personId=" + personId;  
    new Ajax.Request('eCommerce.asmx/Log_Error',
        {
            method:'post',
            parameters: params,
            onComplete: function(logTransport)
            {
                if(logTransport.status == 200)
                {
                    var response = ((logTransport.responseXML.text) ? logTransport.responseXML.text : logTransport.responseXML.lastChild.textContent);
                    if(displayMsg) alert(detail);
                }
                else
                {
                     alert("Log Error onComplete Failed: " + logTransport.status + '(' + detail + ')');
                }
            },
            onFailure: function(logTransport) { alert("Log Error Ajax Failed: "+ logTransport.status  + '(' + detail + ')'); }
         });
    }