// ********************************************************************************************
// 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.";
// ---------------------------------
// Cookies
// ---------------------------------
var _cookie_name_eCommerce = "eCommerce";
var _cookie_PersonId = "PersonId";
var _cookie_OrderId = "OrderId";
var _cookie_CustomerKey = "CustomerKey";
var _domain = "";
// ---------------------------------
// 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() : "");
}
//---------------------------------------------------------//
//Deletes the cookie value when a grid item is selected	   //
//---------------------------------------------------------//
function DeleteCookie(name,path,domain) 
{
    if (GetCookie(name)) 
        document.cookie = name + "=" + ( ( path ) ? ";path=" + path : "") +
            ( ( domain ) ? ";domain=" + domain : "" ) + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
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() : "");
}
//---------------------------------------------------------//
//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  //
//  Note: This functionality is now handles in Prototype.js
//---------------------------------------------------------//
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(!isNaN(val))
        ret = parseInt(val,10);
    
	return ret;
}
//----------------------------------------------------------//
//	SafeBool:	    										//
//	bool													//
//----------------------------------------------------------//
function SafeBool(val)
{  
    if (data && typeof(data) == 'boolean')
        return data;
    else if (data && (data.toUpperCase() == 'TRUE' || data.toUpperCase() == '1' || data.toUpperCase() == 'YES' || data.toUpperCase() == 'ON'))
        return true;
    else
        return false;
}
// ---------------------------------
// ---------------------------------
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;
}
// ---------------------------------
//  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.host;
}

// **************************************************
// 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;
}
// ---------------------------------------------
// returns a function that is a delagate of an object
// ---------------------------------------------
function delegate(instance, method) 
{
    return function() { return method.apply(instance, arguments);}
}

function Get_RadComboBox_Value(id)
{
    var radControl = $find(id);
    value = radControl.get_value();
    if (value == null)
        value = "";
    return value;
}

function GetSecurityCookieKeyValue(key)
{
    //_cookie_name_eCommerce

    var value = GetCookie(_cookie_name_eCommerce);
    var key_val = GetCookieKeyValue(value,key);
    
    if(key_val && key_val!="")
        return key_val
     else
        return "0";
}

function Toggle_Button_Class(el)
{
    if (el.className == "popup_button")
        el.className = "popup_button_hover";
    else
        el.className = "popup_button";
}