/************************************************************************************
 * File: P21Javascript.js                                                           
 *                                                                                  
 * Primary Javascript file for B2BSeller. All other Javascript not standard for all 
 * hosted sites should be included in customer specific Javascript files and        
 * configured for use in Site Administrator tool.                                   
 ***********************************************************************************/

/************************************************************************************
*Set Focus on Forms
************************************************************************************/
function setFocusOnForms(){
	try {
	document.Quick_Order_LSide.txtItemID0.focus();
	}
	catch (e) {
		try {
		document.Product_Search_LSide.txtSearchText.focus();
		}
		catch (e) {
			try {
			document.Logon_LSide.txtEmail.focus();
			}
			catch (e) {
				try{
				document.Product_Search_Header.txtSearchText.focus();
				}
				catch (e) {
					try {
					document.Logon_Header.txtEmail.focus();
					}
					catch (e) {
					}
				}
			}
		}
	}
}

/************************************************************************************
*Javascript Form Validation Functions
************************************************************************************/
//Error message 
var errmsg;

function validateMyForm(frmTemp){
	var bReturn = true;
	var intLoop;
	var e;

	//Initialize error message to blank string
	errmsg = '';
	for(var intLoop = 0; intLoop < frmTemp.length; intLoop++){
		e = frmTemp.elements[intLoop]
		if(e.phone){
			bReturn = validatePhoneNumber(e) && bReturn;
		}
		else if(e.email){
			bReturn = validateEmailAddress(e) && bReturn;
		}
		else if(e.name=='validateDecimal'){
			bReturn = validateDecimal(e, frmTemp) && bReturn;
		}
	}
	if(!bReturn){
		alert(errmsg);
	}
	return bReturn;
}

function validatePhoneNumber(e){
	var bValid = true;
	var regX = /^(([1]|(\+\d{1,3}))(\.| |\-)?)?((\(\d{2,3}\))|\d{2,3})(\.| |\-)?\d{3}(\.| |\-)?\d{4}$/;
		
	if (!regX.test(e.value)){
		bValid = false;
		errmsg += 'Please enter a valid phone number\n - International numbers must begin with a "+"\n';
	}
	return bValid;
}

function validateEmailAddress(e){
	var bValid = true;
	var regX =  /^\w(\.?\w)*@\w(\.?[-\w])*\.[a-z]{2,4}$/;
	
	if (!regX.test(e.value)){
		bValid = false;
		errmsg += 'Please enter a valid email address\n';
	}
	return bValid;
}

function validateDecimal(e, frmTemp){
	var arrFields = e.value.split(',')
	var bValid = true;
	var regX =   /^(\d+)?(.\d+)?$/;
	var myField
	for(var i=0;i<arrFields.length;i++){ 
		myField = document.forms[frmTemp.name].elements[arrFields[i]];
		if (!regX.test(myField.value)){
			bValid = false;
			errmsg += 'Please enter a valid numeric value for ' + myField.id + '\n';
		}
	}
	return bValid;
}


/************************************************************************************
 * Reset QOP Function                                                              
 ***********************************************************************************/
function resetQOP(QOPForm, intCount){
	var itemid;
	var qty;
	for (var i=0;i<intCount;i++){
        	itemid = QOPForm.elements["txtItemID" + i].value = '';
	       	qty = QOPForm.elements["txtQuantity" + i].value='';

	}
} 
            

/************************************************************************************
 * AR Payment FUNCTIONS                                                                
 ***********************************************************************************/

function allDigits(str)
{
	return inValidCharSet(str,"0123456789");

}

function inValidCharSet(str,charset)
{
	var result = true;
        // Note: doesn't use regular expressions to avoid early Mac browser bugs
        for (var i=0;i<str.length;i++){
        	if (charset.indexOf(str.substr(i, 1)) < 0)
	        {
        		result = false;
	        	break;
        	}
	}
       	return result;
	
}

function validDate(formField)
        {
        var result = true;
        var elems = formField.value.split("/");
        result = (elems.length == 3); // should be three components
        if (result)
        {
	        var month = parseInt(elems[0],10);
        	var day = parseInt(elems[1],10);
        	var year = parseInt(elems[2],10);
        	result = allDigits(elems[0]) && (month > 0) && (month < 13) &&
        	allDigits(elems[1]) && (day > 0) && (day < 32) &&
        	allDigits(elems[2]) && ((elems[2].length == 2) || (elems[2].length == 4));
        }
        if (!result)
        {
        	alert('Date must be in format MM/DD/YYYY or MM/DD/YY');
	        formField.focus();
        }
        return result;
}



function reqdatechange()
{
	if(validDate(document.Shopping_Cart_Content.hdrreqdate)){
   		for(i=0; i<document.Shopping_Cart_Content.elements.length; i++){
			var e = document.Shopping_Cart_Content.elements[i];
			if (e.name.indexOf("reqdate")==0){
				e.value=document.Shopping_Cart_Content.hdrreqdate.value;
			}			
		}
       	}
}


function totalChanged(){
	//alert("totalChanged");
	var totalAmt = document.My_Account_Open_AR_List_Content.txtTotalAmt.value.replace(",","");
	
    if (totalAmt.replace(/^\s+|\s+$/g, '').length == 0) {
        // If the totalAmt given was empty (after being trimmed), just assume the user meant zero.
        totalAmt = "0";
    }

	if (isNaN(totalAmt)){
		alert("You must enter a number.");
		document.My_Account_Open_AR_List_Content.txtTotalAmt.value = document.My_Account_Open_AR_List_Content.TotalPaymentAmount.value;
	}
	else {
        //
        // Ignore negative amounts entered here -- all amounts entered by the user are positive amounts
        //
        totalAmt = twoDecimals(Math.abs(parseFloat(totalAmt)))
        var aTotalAmountApplied = parseFloat(document.My_Account_Open_AR_List_Content.TotalAmountApplied.value.replace(",",""));
        var aTotalPaymentAmount = parseFloat(document.My_Account_Open_AR_List_Content.TotalPaymentAmount.value.replace(",",""));
    	if (parseFloat(totalAmt) - aTotalAmountApplied < 0) {
            //
            //  The newly-entered total amount to be applied is not enough to cover all the 
            //  individual invoice allocations that the user already has specified.
            //  If they confirm this intent, we'll clear their allocations and set the
            //  TotalPaymentAmount to what they have entered.
            //
            var bConfirm = confirm("This change will reduce the Total Amount to Apply to be less than the total amount you have allocated.  Continuing with this change will cause all payment amounts on invoices to revert back to '0'.  Continue with this change?");
    		if (bConfirm == true) {
                //
                //  Clear the invoice allocations and update the running sum values in DOM.
                //
    			var i;				
    			for(i = 0; i < document.My_Account_Open_AR_List_Content.elements.length; i++){
    				var anElement = document.My_Account_Open_AR_List_Content.elements[i];
    				if (anElement.name.indexOf("txtPayment") == 0){
    					anElement.value="0.00";
    				}
    				else {
                        if (anElement.name.indexOf("txtPrevious") == 0) {
                            anElement.value="0.00";
                        }
                    }
    			}
                //
                //    TotalAmountApplied - Set to zero (based on the user's confirmation).
                //
                aTotalAmountApplied = 0
                document.My_Account_Open_AR_List_Content.TotalAmountApplied.value = twoDecimals(aTotalAmountApplied);
                //
                //    TotalPaymentAmount - Set to the newly-entered (and confirmed) value.
                //
                aTotalPaymentAmount = parseFloat(totalAmt)
                document.My_Account_Open_AR_List_Content.TotalPaymentAmount.value = twoDecimals(aTotalPaymentAmount);
                document.My_Account_Open_AR_List_Content.txtTotalAmt.value = document.My_Account_Open_AR_List_Content.TotalPaymentAmount.value;
                //
                //    AmountLeftToApply  - Calculated as the difference between TotalPaymentAmount and 
                //                         TotalAmountApplied.
                //
                document.My_Account_Open_AR_List_Content.AmountLeftToApply.value = twoDecimals(aTotalPaymentAmount - aTotalAmountApplied);
                var oAmtLeft = document.getElementById("divAmtLeft");
                if (oAmtLeft.firstChild != null) {
                    oAmtLeft.firstChild.nodeValue = "$" + document.My_Account_Open_AR_List_Content.AmountLeftToApply.value;
                }
                //
                //  With all amounts updated, submit this form to clear allocations possibly made
                //  on other pages and to return to first page.
                //
    			document.My_Account_Open_AR_List_Content.RowID.value = "0";
    			document.My_Account_Open_AR_List_Content.Action.value = "ClearSession";
    			document.My_Account_Open_AR_List_Content.submit();
    		}
    		else {
                //
                //  The user did NOT confirm.  Set the total payment amount back to what it was before
                //  they changed it and carry on.
                //
    			document.My_Account_Open_AR_List_Content.txtTotalAmt.value = twoDecimals(aTotalPaymentAmount);
    		}
    	}
    	else {
            //
            //  The newly-entered total amount is acceptable.  It simply adjusts the amount for the user to 
            //  allocate without putting into jeopardy any of their existing allocations.  We must update
            //  the running sum values in DOM.
            //
            //
            //    TotalAmountApplied - remains unchanged
            //
            document.My_Account_Open_AR_List_Content.TotalAmountApplied.value = twoDecimals(aTotalAmountApplied);
            //
            //    TotalPaymentAmount - Set to the newly-entered value.
            //
            aTotalPaymentAmount = parseFloat(totalAmt)
            document.My_Account_Open_AR_List_Content.TotalPaymentAmount.value = twoDecimals(aTotalPaymentAmount);
            document.My_Account_Open_AR_List_Content.txtTotalAmt.value = document.My_Account_Open_AR_List_Content.TotalPaymentAmount.value;
            //
            //    AmountLeftToApply  - Calculated as the difference between TotalPaymentAmount and 
            //                         TotalAmountApplied.
            //
            document.My_Account_Open_AR_List_Content.AmountLeftToApply.value = twoDecimals(aTotalPaymentAmount - aTotalAmountApplied);
            var oAmtLeft = document.getElementById("divAmtLeft");
            if (oAmtLeft.firstChild != null) {
                oAmtLeft.firstChild.nodeValue = "$" + document.My_Account_Open_AR_List_Content.AmountLeftToApply.value;
            }
    	}
    }
}

function paymentChanged(PmtAmt, PrevAmt, MaxAmt){
	// alert("paymentChanged");
	var paymentAmt = PmtAmt.value.replace(",","");
	var previousAmt = PrevAmt.value.replace(",","");
	var maxAmt = MaxAmt.value.replace(",","");
		
    // If the paymentAmt given was empty (after being trimmed), just assume the user meant zero.
    if (paymentAmt.replace(/^\s+|\s+$/g, '').length == 0) {
        paymentAmt = "0";
    }

	if (isNaN(paymentAmt)) {
		alert("You must enter a number.");
		PmtAmt.value = PrevAmt.value
	}
	else {
        if (Math.abs(parseFloat(paymentAmt)) > Math.abs(parseFloat(maxAmt))) {
            //
            //  You may not use more of your invoice than it's total invoice amount.
            //  We set the payment amount to the invoice's total balance due and warn
            //  you that we have done so.
            //
            paymentAmt = maxAmt;
            if ((document.getElementById("OverpaymentMessage").firstChild != null) && (document.getElementById("OverpaymentMessage").firstChild.nodeValue.length > 0)) {
                alert(document.getElementById("OverpaymentMessage").firstChild.nodeValue);
            }
        }
        else {
            //  We accept the line item payment as entered.
            //
            //  NOTE:  The invoice may be a credit or ordinary (debit) invoice.  Since users only enter
            //         positive amounts, we choose the sign of payment amounts based on the net due of the
            //         invoice.
            //
            if (parseFloat(maxAmt) > 0) {
                paymentAmt = twoDecimals(Math.abs(parseFloat(paymentAmt)))
            }
            else {
                paymentAmt = twoDecimals(-1 * Math.abs(parseFloat(paymentAmt)))
            }
        }
        //
        //  Calculate the change of this payment to the totals for the entire list at the 
        //  top of the page and update the running sum values in DOM.
        //
        var aTotalAmountApplied = parseFloat(document.My_Account_Open_AR_List_Content.TotalAmountApplied.value.replace(",",""));
        var aTotalPaymentAmount = parseFloat(document.My_Account_Open_AR_List_Content.txtTotalAmt.value.replace(",",""));
        //
        //    TotalAmountApplied - Adjust by the difference of the payment currently 
        //                         appearing in this line and the payment amount that used
        //                         appear in this line (the last accepted value).
        //
        var difference = parseFloat(paymentAmt) - parseFloat(previousAmt);
        aTotalAmountApplied = aTotalAmountApplied + difference;
        document.My_Account_Open_AR_List_Content.TotalAmountApplied.value = twoDecimals(aTotalAmountApplied);
        //
        //    TotalPaymentAmount - We only change this if the amount already applied drives
        //                         it HIGHER.  This because we allow the user to set this
        //                         amount themselves and use these screens to allocate that
        //                         payment across many invoices.
        //
        if (aTotalAmountApplied > aTotalPaymentAmount) {
            aTotalPaymentAmount = aTotalAmountApplied;
        }
        document.My_Account_Open_AR_List_Content.TotalPaymentAmount.value = twoDecimals(aTotalPaymentAmount);
        document.My_Account_Open_AR_List_Content.txtTotalAmt.value = document.My_Account_Open_AR_List_Content.TotalPaymentAmount.value;
        //
        //    AmountLeftToApply  - Calculated as the difference between TotalPaymentAmount and 
        //                         TotalAmountApplied.
        //
        document.My_Account_Open_AR_List_Content.AmountLeftToApply.value = twoDecimals(aTotalPaymentAmount - aTotalAmountApplied);
        var oAmtLeft = document.getElementById("divAmtLeft");
        if (oAmtLeft.firstChild != null) {
            oAmtLeft.firstChild.nodeValue = "$" + document.My_Account_Open_AR_List_Content.AmountLeftToApply.value;
        }
        //  
        //  Update the DOM values for the line (remembering that the amount showing does not require a negative sign).
        //
        PrevAmt.value = twoDecimals(parseFloat(paymentAmt));
        PmtAmt.value = twoDecimals(Math.abs(parseFloat(paymentAmt)));
    }
}            
 
function checkTotal(For,By,Start,End,CompleteAR){
    document.My_Account_Open_AR_List_Content.Action.value = "MakePayment";
    document.My_Account_Open_AR_List_Content.submit();
}

function setRedirect(url){
	document.My_Account_Open_AR_List_Content.Redirect.value = url;
	document.My_Account_Open_AR_List_Content.Action.value = "Redirect";
	document.My_Account_Open_AR_List_Content.submit();
}

function twoDecimals(n) {
   var s = "" + Math.round(n * 100) / 100
   var i = s.indexOf('.')
   if (i < 0) return s + ".00"
   var t = s.substring(0, i + 1) + s.substring(i + 1, i + 3)
   if (i + 2 == s.length) t += "0"
   return t
}

/************************************************************************************
 * UTILITY FUNCTIONS                                                                
 ***********************************************************************************/
    
function openWindow(url, title, width, height, scrollbars, resizable, toolbar, menubar){
		var	properties = "width=" + width + "," + "height=" + height + ",left="+((screen.width/2)-width/2)+",top="+((screen.height/2)-height/2)+",scrollbars="+scrollbars+",resizable="+resizable+",toolbar="+toolbar+",menubar="+menubar;
		NFW = window.open(url,title,properties)     
		NFW.focus()   
		//window.onunload = function(){NFW.close()}
}

function popupImage(sImgSrc) {
  if (sImgSrc.substring(0,9)=='customer/') { sImgSrc = '../../' + sImgSrc; }
  window.open("SystemFolders/p21customerpages/PopupImage.html?"+sImgSrc,"PopupImage","resizable=0,location=0,height=250,width=250");
}
		
function locationSelect(page, sel) {
  // navigate page to the 'page' + select element's selected option value
  // ex. locationSelect('default.aspx?page=page name','SelectElementID')
  var s = document.getElementById(sel);
  if (s!=null) { location.href = page + s.options[s.selectedIndex].value; }
}

function checkValue(btnName) {

    var isNetscape = false;
    var isIE = false;
    var isW3Dom = false;
    var isIEMac = false;
    var isWhoKnows = false
    var df = document.forms[0];
    var theButtonPressed;

    if (document.layers) {// NS 4
        isNetscape = true;
    }
    else if (document.all) { // IE
        isIE = true;
    }
    else if (document.getElementById) { // w3 DOM standard for Opera, NS 6,Konqueror
        isW3Dom = true;
    }
    else {
        isWhoKnows = true;
    }

    if (isNetscape) {
        theButtonPressed = evt.which;
    }
    else if(isIE) {
        theButtonPressed = window.event.keyCode;
    }
    else if (isW3Dom) {
        theButtonPressed = evt.keyCode;
    } 
    else {
        alert("Please hit the submit button to process form");
        theButtonPressed = 0;
    }
    
    if(theButtonPressed == 13){
        document.Form1.ButtonPressed.value = btnName;
//				document.Form1.submit();
    }
    else {
        document.Form1.ButtonPressed.value = '';
    }
}

function shipChange(ddown){
	if(ddown.selectedIndex == 0){
		document.Form1._ctl3_txtAddr1.readonly = false;
		document.Form1._ctl3_txtAddr2.readonly = false;
		document.Form1._ctl3_txtCity.readonly = false;
		document.Form1._ctl3_txtState.readonly = false;
		document.Form1._ctl3_txtZip.readonly = false;
		document.Form1._ctl3_txtCountry.readonly = false;
	}
	else{
		document.Form1._ctl3_txtAddr1.readonly = true;
		document.Form1._ctl3_txtAddr2.readonly = true;
		document.Form1._ctl3_txtCity.readonly = true;
		document.Form1._ctl3_txtState.readonly = true;
		document.Form1._ctl3_txtZip.readonly = true;
		document.Form1._ctl3_txtCountry.readonly = true;
	}
}

function billChange(ddown){
	if(ddown.selectedIndex.value == 0){
		document.Form1._ctl3_txtCreditCardName.readonly = false;
		document.Form1._ctl3_txtCreditCardNumber.readonly = false;
		document.Form1._ctl3_txtCreditCardMonth.readonly = false;
		document.Form1._ctl3_txtCreditCardYear.readonly = false;
	}
	else{
		document.Form1.txtCreditCardName.readonly = true;
		document.Form1.txtCreditCardNumber.readonly = true;
		document.Form1.txtCreditCardMonth.readonly = true;
		document.Form1.txtCreditCardYear.readonly = true;
	}
}


/************************************************************************************
 * CALENDAR FUNCTIONS       
 *
 * Replace "myForm" and "myDateField" with the name of your form and input field.
 * Window options set the width, height, and X/Y position of the calendar window 
 * with title bar on,all other options (toolbars, etc.) are disabled by default.
 *
 * <A HREF="javascript:doNothing()" onClick="setDateField(document.myForm.myDateField);top.newWin = window.open('calendar.html','cal','dependent=yes,width=210,height=230,screenX=200,screenY=300,titlebar=yes')">
 * <IMG SRC="calendar.gif" BORDER=0></A><font size=1>Popup Calendar</font>
 * 
 * Required Files:
 *
 *  calendar.js   - contains all JavaScript functions to make the calendar work
 * 
 *  calendar.html - frameset document (not required if you call the showCalendar()
 *                  function.  However, calling showCalendar() directly causes
 *                  the Java Virtual Machine (JVM) to start which slows down the
 *                  loading of the calendar.)
 *
 *  calendar.gif  - image that looks like a little calendar                                                        *
 ***********************************************************************************/


function initializeCalendar() {

    // DATE FORMAT OPTIONS:
    //
    // dd   = 1 or 2-digit Day
    // DD   = 2-digit Day
    // mm   = 1 or 2-digit Month
    // MM   = 2-digit Month
    // yy   = 2-digit Year
    // YY   = 4-digit Year
    // yyyy = 4-digit Year
    // month   = Month name in lowercase letters
    // Month   = Month name in initial caps
    // MONTH   = Month name in captital letters
    // mon     = 3-letter month abbreviation in lowercase letters
    // Mon     = 3-letter month abbreviation in initial caps
    // MON     = 3-letter month abbreviation in uppercase letters
    // weekday = name of week in lowercase letters
    // Weekday = name of week in initial caps
    // WEEKDAY = name of week in uppercase letters
    // wkdy    = 3-letter weekday abbreviation in lowercase letters
    // Wkdy    = 3-letter weekday abbreviation in initial caps
    // WKDY    = 3-letter weekday abbreviation in uppercase letters
    //
    // Examples:
    //
    // calDateFormat = "mm/dd/yy";
    // calDateFormat = "Weekday, Month dd, yyyy";
    // calDateFormat = "wkdy, mon dd, yyyy";
    // calDateFormat = "DD.MM.YY";     // FORMAT UNSUPPORTED BY JAVASCRIPT -- REQUIRES CUSTOM PARSING
    //
    
    calDateFormat    = "MM/DD/YY";
    
    
    // CALENDAR COLORS
    topBackground    = "#D2DDC8";         // BG COLOR OF THE TOP FRAME
    bottomBackground = "#D2DDC8";         // BG COLOR OF THE BOTTOM FRAME
    tableBGColor     = "black";         // BG COLOR OF THE BOTTOM FRAME'S TABLE
    cellColor        = "lightgrey";     // TABLE CELL BG COLOR OF THE DATE CELLS IN THE BOTTOM FRAME
    headingCellColor = "510367";         // TABLE CELL BG COLOR OF THE WEEKDAY ABBREVIATIONS
    headingTextColor = "white";         // TEXT COLOR OF THE WEEKDAY ABBREVIATIONS
    dateColor        = "510367";          // TEXT COLOR OF THE LISTED DATES (1-28+)
    focusColor       = "#ff0000";       // TEXT COLOR OF THE SELECTED DATE (OR CURRENT DATE)
    hoverColor       = "darkred";       // TEXT COLOR OF A LINK WHEN YOU HOVER OVER IT
    fontStyle        = "12pt arial, helvetica";           // TEXT STYLE FOR DATES
    headingFontStyle = "bold 12pt arial, helvetica";      // TEXT STYLE FOR WEEKDAY ABBREVIATIONS
    
    // FORMATTING PREFERENCES
    bottomBorder  = false;        // TRUE/FALSE (WHETHER TO DISPLAY BOTTOM CALENDAR BORDER)
    tableBorder   = 0;            // SIZE OF CALENDAR TABLE BORDER (BOTTOM FRAME) 0=none
    
    
    // DETERMINE BROWSER BRAND
    isNav = false;
    isIE  = false;
    
    // ASSUME IT'S EITHER NETSCAPE OR MSIE
    if (navigator.appName == "Netscape") {
     isNav = true;
    }
    else {
     isIE = true;
    }
    
    // GET CURRENTLY SELECTED LANGUAGE
    selectedLanguage = navigator.language;
    
    // PRE-BUILD PORTIONS OF THE CALENDAR WHEN THIS JS LIBRARY LOADS INTO THE BROWSER
    buildCalParts();

} //end initializeCalendar()

function getCalendar(inputfield) {
    setDateField(inputfield);
    showCalendar(inputfield);
    //top.newWin = window.open('MQCalendar.html','cal','dependant=yes, width=210, height=230, left=600,top=350,titlebar=yes');
}

function showCalendar(dateField) {

    // SET INITIAL VALUE OF THE DATE FIELD AND CREATE TOP AND BOTTOM FRAMES
    setDateField(dateField);

    // USE THE JAVASCRIPT-GENERATED DOCUMENTS (calDocTop, calDocBottom) IN THE FRAMESET
    calDocFrameset = 
        "<HTML><HEAD><TITLE>Calendar</TITLE></HEAD>\n" +
        "<FRAMESET ROWS='70,*' FRAMEBORDER='0'>\n" +
        "  <FRAME NAME='topCalFrame' SRC='javascript:parent.opener.calDocTop' SCROLLING='no'>\n" +
        "  <FRAME NAME='bottomCalFrame' SRC='javascript:parent.opener.calDocBottom' SCROLLING='no'>\n" +
        "</FRAMESET>\n";

    // DISPLAY THE CALENDAR IN A NEW POPUP WINDOW
    //top.newWin = window.open("javascript:parent.opener.calDocFrameset", "calWin", winPrefs);
    top.newWin = window.open("javascript:parent.opener.calDocFrameset", 'cal','dependant=yes, width=210, height=230, left=600,top=350,titlebar=yes');
    top.newWin.focus();
    
}

function setDateField(dateField) {

    // ASSIGN THE INCOMING FIELD OBJECT TO A GLOBAL VARIABLE
    calDateField = dateField;

    // GET THE VALUE OF THE INCOMING FIELD
    inDate = dateField.value;

    // SET calDate TO THE DATE IN THE INCOMING FIELD OR DEFAULT TO TODAY'S DATE
    setInitialDate();

    // THE CALENDAR FRAMESET DOCUMENTS ARE CREATED BY JAVASCRIPT FUNCTIONS
    calDocTop    = buildTopCalFrame();
    calDocBottom = buildBottomCalFrame();
}

function setInitialDate() {
   
    // CREATE A NEW DATE OBJECT (WILL GENERALLY PARSE CORRECT DATE EXCEPT WHEN "." IS USED AS A DELIMITER)
    // (THIS ROUTINE DOES *NOT* CATCH ALL DATE FORMATS, IF YOU NEED TO PARSE A CUSTOM DATE FORMAT, DO IT HERE)
    calDate = new Date(inDate);

    // IF THE INCOMING DATE IS INVALID, USE THE CURRENT DATE
    if (isNaN(calDate)) {
        // ADD CUSTOM DATE PARSING HERE
        // IF IT FAILS, SIMPLY CREATE A NEW DATE OBJECT WHICH DEFAULTS TO THE CURRENT DATE
        calDate = new Date();
    }

    // KEEP TRACK OF THE CURRENT DAY VALUE
    calDay  = calDate.getDate();

    // SET DAY VALUE TO 1... TO AVOID JAVASCRIPT DATE CALCULATION ANOMALIES
    // (IF THE MONTH CHANGES TO FEB AND THE DAY IS 30, THE MONTH WOULD CHANGE TO MARCH
    //  AND THE DAY WOULD CHANGE TO 2.  SETTING THE DAY TO 1 WILL PREVENT THAT)
    calDate.setDate(1);
}

function buildTopCalFrame() {

    // CREATE THE TOP FRAME OF THE CALENDAR
    var calDoc =
        "<HTML>" +
        "<HEAD>" +
        "</HEAD>" +
        "<BODY BGCOLOR='" + topBackground + "'>" +
        "<FORM NAME='calControl' onSubmit='return false;'>" +
        "<CENTER>" +
        "<TABLE CELLPADDING=0 CELLSPACING=1 BORDER=0>" +
        "<TR><TD COLSPAN=7>" +
        "<CENTER>" +
        getMonthSelect() +
        "<INPUT NAME='year' VALUE='" + calDate.getFullYear() + "'TYPE=TEXT SIZE=4 MAXLENGTH=4 onChange='parent.opener.setYear()'>" +
        "</CENTER>" +
        "</TD>" +
        "</TR>" +
        "<TR>" +
        "<TD COLSPAN=7>" +
        "<INPUT " +
        "TYPE=BUTTON NAME='previousYear' VALUE='<<'    onClick='parent.opener.setPreviousYear()'><INPUT " +
        "TYPE=BUTTON NAME='previousMonth' VALUE=' < '   onClick='parent.opener.setPreviousMonth()'><INPUT " +
        "TYPE=BUTTON NAME='today' VALUE='Today' onClick='parent.opener.setToday()'><INPUT " +
        "TYPE=BUTTON NAME='nextMonth' VALUE=' > '   onClick='parent.opener.setNextMonth()'><INPUT " +
        "TYPE=BUTTON NAME='nextYear' VALUE='>>'    onClick='parent.opener.setNextYear()'>" +
        "</TD>" +
        "</TR>" +
        "</TABLE>" +
        "</CENTER>" +
        "</FORM>" +
        "</BODY>" +
        "</HTML>";

    return calDoc;
}

function buildBottomCalFrame() {       

    // START CALENDAR DOCUMENT
    var calDoc = calendarBegin;

    // GET MONTH, AND YEAR FROM GLOBAL CALENDAR DATE
    month   = calDate.getMonth();
    year    = calDate.getFullYear();


    // GET GLOBALLY-TRACKED DAY VALUE (PREVENTS JAVASCRIPT DATE ANOMALIES)
    day     = calDay;

    var i   = 0;

    // DETERMINE THE NUMBER OF DAYS IN THE CURRENT MONTH
    var days = getDaysInMonth();

    // IF GLOBAL DAY VALUE IS > THAN DAYS IN MONTH, HIGHLIGHT LAST DAY IN MONTH
    if (day > days) {
        day = days;
    }

    // DETERMINE WHAT DAY OF THE WEEK THE CALENDAR STARTS ON
    var firstOfMonth = new Date (year, month, 1);

    // GET THE DAY OF THE WEEK THE FIRST DAY OF THE MONTH FALLS ON
    var startingPos  = firstOfMonth.getDay();
    days += startingPos;

    // KEEP TRACK OF THE COLUMNS, START A NEW ROW AFTER EVERY 7 COLUMNS
    var columnCount = 0;

    // MAKE BEGINNING NON-DATE CELLS BLANK
    for (i = 0; i < startingPos; i++) {

        calDoc += blankCell;
	columnCount++;
    }

    // SET VALUES FOR DAYS OF THE MONTH
    var currentDay = 0;
    var dayType    = "weekday";

    // DATE CELLS CONTAIN A NUMBER
    for (i = startingPos; i < days; i++) {

	var paddingChar = "&nbsp;";

        // ADJUST SPACING SO THAT ALL LINKS HAVE RELATIVELY EQUAL WIDTHS
        if (i-startingPos+1 < 10) {
            padding = "&nbsp;&nbsp;";
        }
        else {
            padding = "&nbsp;";
        }

        // GET THE DAY CURRENTLY BEING WRITTEN
        currentDay = i-startingPos+1;

        // SET THE TYPE OF DAY, THE focusDay GENERALLY APPEARS AS A DIFFERENT COLOR
        if (currentDay == day) {
            dayType = "focusDay";
        }
        else {
            dayType = "weekDay";
        }

        // ADD THE DAY TO THE CALENDAR STRING
        calDoc += "<TD align=center bgcolor='" + cellColor + "'>" +
                  "<a class='" + dayType + "' href='javascript:parent.opener.returnDate(" + 
                  currentDay + ")'>" + padding + currentDay + paddingChar + "</a></TD>";

        columnCount++;

        // START A NEW ROW WHEN NECESSARY
        if (columnCount % 7 == 0) {
            calDoc += "</TR><TR>";
        }
    }

    // MAKE REMAINING NON-DATE CELLS BLANK
    for (i=days; i<42; i++)  {

        calDoc += blankCell;
	columnCount++;

        // START A NEW ROW WHEN NECESSARY
        if (columnCount % 7 == 0) {
            calDoc += "</TR>";
            if (i<41) {
                calDoc += "<TR>";
            }
        }
    }

    // FINISH THE NEW CALENDAR PAGE
    calDoc += calendarEnd;

    // RETURN THE COMPLETED CALENDAR PAGE
    return calDoc;
}

function writeCalendar() {

    // CREATE THE NEW CALENDAR FOR THE SELECTED MONTH & YEAR
    calDocBottom = buildBottomCalFrame();

    // WRITE THE NEW CALENDAR TO THE BOTTOM FRAME
    top.newWin.frames['bottomCalFrame'].document.open();
    top.newWin.frames['bottomCalFrame'].document.write(calDocBottom);
    top.newWin.frames['bottomCalFrame'].document.close();
}

function setToday() {

    // SET GLOBAL DATE TO TODAY'S DATE
    calDate = new Date();

    // SET DAY MONTH AND YEAR TO TODAY'S DATE
    var month = calDate.getMonth();
    var year  = calDate.getFullYear();

    // SET MONTH IN DROP-DOWN LIST
    top.newWin.frames['topCalFrame'].document.calControl.month.selectedIndex = month;

    // SET YEAR VALUE
    top.newWin.frames['topCalFrame'].document.calControl.year.value = year;
    inDate = "";
    setInitialDate();

    // DISPLAY THE NEW CALENDAR
    writeCalendar();
}

function setYear() {

    // GET THE NEW YEAR VALUE
    var year  = top.newWin.frames['topCalFrame'].document.calControl.year.value;

    // IF IT'S A FOUR-DIGIT YEAR THEN CHANGE THE CALENDAR
    if (isFourDigitYear(year)) {
        calDate.setFullYear(year);
        writeCalendar();
    }
    else {
        // HIGHLIGHT THE YEAR IF THE YEAR IS NOT FOUR DIGITS IN LENGTH
        top.newWin.frames['topCalFrame'].document.calControl.year.focus();
        top.newWin.frames['topCalFrame'].document.calControl.year.select();
    }
}

function setCurrentMonth() {

    // GET THE NEWLY SELECTED MONTH AND CHANGE THE CALENDAR ACCORDINGLY
    var month = top.newWin.frames['topCalFrame'].document.calControl.month.selectedIndex;

    calDate.setMonth(month);
    writeCalendar();
}

function setPreviousYear() {

    var year  = top.newWin.frames['topCalFrame'].document.calControl.year.value;

    if (isFourDigitYear(year) && year > 1000) {
        year--;
        calDate.setFullYear(year);
        top.newWin.frames['topCalFrame'].document.calControl.year.value = year;
        writeCalendar();
    }
}

function setPreviousMonth() {

    var year  = top.newWin.frames['topCalFrame'].document.calControl.year.value;
    if (isFourDigitYear(year)) {
        var month = top.newWin.frames['topCalFrame'].document.calControl.month.selectedIndex;

        // IF MONTH IS JANUARY, SET MONTH TO DECEMBER AND DECREMENT THE YEAR
        if (month == 0) {
            month = 11;
            if (year > 1000) {
                year--;
                calDate.setFullYear(year);
                top.newWin.frames['topCalFrame'].document.calControl.year.value = year;
            }
        }
        else {
            month--;
        }
        calDate.setMonth(month);
        top.newWin.frames['topCalFrame'].document.calControl.month.selectedIndex = month;
        writeCalendar();
    }
}

function setNextMonth() {

    var year = top.newWin.frames['topCalFrame'].document.calControl.year.value;

    if (isFourDigitYear(year)) {
        var month = top.newWin.frames['topCalFrame'].document.calControl.month.selectedIndex;

        // IF MONTH IS DECEMBER, SET MONTH TO JANUARY AND INCREMENT THE YEAR
        if (month == 11) {
            month = 0;
            year++;
            calDate.setFullYear(year);
            top.newWin.frames['topCalFrame'].document.calControl.year.value = year;
        }
        else {
            month++;
        }
        calDate.setMonth(month);
        top.newWin.frames['topCalFrame'].document.calControl.month.selectedIndex = month;
        writeCalendar();
    }
}

function setNextYear() {

    var year  = top.newWin.frames['topCalFrame'].document.calControl.year.value;
    if (isFourDigitYear(year)) {
        year++;
        calDate.setFullYear(year);
        top.newWin.frames['topCalFrame'].document.calControl.year.value = year;
        writeCalendar();
    }
}

function getDaysInMonth()  {

    var days;
    var month = calDate.getMonth()+1;
    var year  = calDate.getFullYear();

    // RETURN 31 DAYS
    if (month==1 || month==3 || month==5 || month==7 || month==8 ||
        month==10 || month==12)  {
        days=31;
    }
    // RETURN 30 DAYS
    else if (month==4 || month==6 || month==9 || month==11) {
        days=30;
    }
    // RETURN 29 DAYS
    else if (month==2)  {
        if (isLeapYear(year)) {
            days=29;
        }
        // RETURN 28 DAYS
        else {
            days=28;
        }
    }
    return (days);
}

function isLeapYear (Year) {

    if (((Year % 4)==0) && ((Year % 100)!=0) || ((Year % 400)==0)) {
        return (true);
    }
    else {
        return (false);
    }
}

function isFourDigitYear(year) {

    if (year.length != 4) {
        top.newWin.frames['topCalFrame'].document.calControl.year.value = calDate.getFullYear();
        top.newWin.frames['topCalFrame'].document.calControl.year.select();
        top.newWin.frames['topCalFrame'].document.calControl.year.focus();
    }
    else {
        return true;
    }
}

function getMonthSelect() {

    // BROWSER LANGUAGE CHECK DONE PREVIOUSLY (navigator.language())
    // FIRST TWO CHARACTERS OF LANGUAGE STRING SPECIFIES THE LANGUAGE
    // (THE LAST THREE OPTIONAL CHARACTERS SPECIFY THE LANGUAGE SUBTYPE)
    // SET THE NAMES OF THE MONTH TO THE PROPER LANGUAGE (DEFAULT TO ENGLISH)

    // IF FRENCH
    if (selectedLanguage == "fr") {
        monthArray = new Array('Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin',
                               'Juillet', 'Aout', 'Septembre', 'Octobre', 'Novembre', 'Décembre');
    }
    // IF GERMAN
    else if (selectedLanguage == "de") {
        monthArray = new Array('Januar', 'Februar', 'März', 'April', 'Mai', 'Juni',
                               'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember');
    }
    // IF SPANISH
    else if (selectedLanguage == "es") {
        monthArray = new Array('Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio',
                               'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre');
    }
    // DEFAULT TO ENGLISH
    else {
        monthArray = new Array('January', 'February', 'March', 'April', 'May', 'June',
                               'July', 'August', 'September', 'October', 'November', 'December');
    }

    // DETERMINE MONTH TO SET AS DEFAULT
    var activeMonth = calDate.getMonth();

    // START HTML SELECT LIST ELEMENT
    monthSelect = "<SELECT NAME='month' onChange='parent.opener.setCurrentMonth()'>";

    // LOOP THROUGH MONTH ARRAY
    for (i in monthArray) {
        
        // SHOW THE CORRECT MONTH IN THE SELECT LIST
        if (i == activeMonth) {
            monthSelect += "<OPTION SELECTED>" + monthArray[i] + "\n";
        }
        else {
            monthSelect += "<OPTION>" + monthArray[i] + "\n";
        }
    }
    monthSelect += "</SELECT>";

    // RETURN A STRING VALUE WHICH CONTAINS A SELECT LIST OF ALL 12 MONTHS
    return monthSelect;
}

function createWeekdayList() {

    // IF FRENCH
    if (selectedLanguage == "fr") {
        weekdayList  = new Array('Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi');
        weekdayArray = new Array('Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa');
    }
    // IF GERMAN
    else if (selectedLanguage == "de") {
        weekdayList  = new Array('Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag');
        weekdayArray = new Array('So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa');
    }
    // IF SPANISH
    else if (selectedLanguage == "es") {
        weekdayList  = new Array('Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado')
        weekdayArray = new Array('Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa');
    }
    else {
        weekdayList  = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
        weekdayArray = new Array('Su','Mo','Tu','We','Th','Fr','Sa');
    }

    // START HTML TO HOLD WEEKDAY NAMES IN TABLE FORMAT
    var weekdays = "<TR BGCOLOR='" + headingCellColor + "'>";

    // LOOP THROUGH WEEKDAY ARRAY
    for (i in weekdayArray) {

        weekdays += "<TD class='heading' align=center>" + weekdayArray[i] + "</TD>";
    }
    weekdays += "</TR>";

    // RETURN TABLE ROW OF WEEKDAY ABBREVIATIONS TO DISPLAY ABOVE THE CALENDAR
    return weekdays;
}

function buildCalParts() {

    // GENERATE WEEKDAY HEADERS FOR THE CALENDAR
    weekdays = createWeekdayList();

    // BUILD THE BLANK CELL ROWS
    blankCell = "<TD align=center bgcolor='" + cellColor + "'>&nbsp;&nbsp;&nbsp;</TD>";

    // BUILD THE TOP PORTION OF THE CALENDAR PAGE USING CSS TO CONTROL SOME DISPLAY ELEMENTS
    calendarBegin =
        "<HTML>" +
        "<HEAD>" +
        // STYLESHEET DEFINES APPEARANCE OF CALENDAR
        "<STYLE type='text/css'>" +
        "<!--" +
        "TD.heading { text-decoration: none; color:" + headingTextColor + "; font: " + headingFontStyle + "; }" +
        "A.focusDay:link { color: " + focusColor + "; text-decoration: none; font: " + fontStyle + "; }" +
        "A.focusDay:hover { color: " + focusColor + "; text-decoration: none; font: " + fontStyle + "; }" +
        "A.weekday:link { color: " + dateColor + "; text-decoration: none; font: " + fontStyle + "; }" +
        "A.weekday:hover { color: " + hoverColor + "; text-decoration: none; font: " + fontStyle + "; }" +
        "A.focusDay:visited { color: " + focusColor + "; text-decoration: none; font: " + fontStyle + "; }" +
        "A.weekday:visited { color: " + dateColor + "; text-decoration: none; font: " + fontStyle + "; }" +
        "-->" +
        "</STYLE>" +
        "</HEAD>" +
        "<BODY BGCOLOR='" + bottomBackground + "'" +
        "<CENTER>";

        // NAVIGATOR NEEDS A TABLE CONTAINER TO DISPLAY THE TABLE OUTLINES PROPERLY
        if (isNav) {
            calendarBegin += 
                "<TABLE CELLPADDING=0 CELLSPACING=1 BORDER=" + tableBorder + " ALIGN=CENTER BGCOLOR='" + tableBGColor + "'><TR><TD>";
        }

        // BUILD WEEKDAY HEADINGS
        calendarBegin +=
            "<TABLE CELLPADDING=0 CELLSPACING=1 BORDER=" + tableBorder + " ALIGN=CENTER BGCOLOR='" + tableBGColor + "'>" +
            weekdays +
            "<TR>";


    // BUILD THE BOTTOM PORTION OF THE CALENDAR PAGE
    calendarEnd = "";

        // WHETHER OR NOT TO DISPLAY A THICK LINE BELOW THE CALENDAR
        if (bottomBorder) {
            calendarEnd += "<TR></TR>";
        }

        // NAVIGATOR NEEDS A TABLE CONTAINER TO DISPLAY THE BORDERS PROPERLY
        if (isNav) {
            calendarEnd += "</TD></TR></TABLE>";
        }

        // END THE TABLE AND HTML DOCUMENT
        calendarEnd +=
            "</TABLE>" +
            "</CENTER>" +
            "</BODY>" +
            "</HTML>";
}

function jsReplace(inString, find, replace) {

    // REPLACE ALL INSTANCES OF find WITH replace
    // inString: the string you want to convert
    // find:     the value to search for
    // replace:  the value to substitute

    var outString = "";

    if (!inString) {
        return "";
    }

    // REPLACE ALL INSTANCES OF find WITH replace
    if (inString.indexOf(find) != -1) {
        // SEPARATE THE STRING INTO AN ARRAY OF STRINGS USING THE VALUE IN find
        t = inString.split(find);

        // JOIN ALL ELEMENTS OF THE ARRAY, SEPARATED BY THE VALUE IN replace
        return (t.join(replace));
    }
    else {
        return inString;
    }
}

function doNothing() {
}

function makeTwoDigit(inValue) {

    var numVal = parseInt(inValue, 10);

    // VALUE IS LESS THAN TWO DIGITS IN LENGTH
    if (numVal < 10) {

        // ADD A LEADING ZERO TO THE VALUE AND RETURN IT
        return("0" + numVal);
    }
    else {
        return numVal;
    }
}

function returnDate(inDay)
{

    // inDay = THE DAY THE USER CLICKED ON
    calDate.setDate(inDay);

    // SET THE DATE RETURNED TO THE USER
    var day           = calDate.getDate();
    var month         = calDate.getMonth()+1;
    var year          = calDate.getFullYear();
    var monthString   = monthArray[calDate.getMonth()];
    var monthAbbrev   = monthString.substring(0,3);
    var weekday       = weekdayList[calDate.getDay()];
    var weekdayAbbrev = weekday.substring(0,3);

    outDate = calDateFormat;

    // RETURN TWO DIGIT DAY
    if (calDateFormat.indexOf("DD") != -1) {
        day = makeTwoDigit(day);
        outDate = jsReplace(outDate, "DD", day);
    }
    // RETURN ONE OR TWO DIGIT DAY
    else if (calDateFormat.indexOf("dd") != -1) {
        outDate = jsReplace(outDate, "dd", day);
    }

    // RETURN TWO DIGIT MONTH
    if (calDateFormat.indexOf("MM") != -1) {
        month = makeTwoDigit(month);
        outDate = jsReplace(outDate, "MM", month);
    }
    // RETURN ONE OR TWO DIGIT MONTH
    else if (calDateFormat.indexOf("mm") != -1) {
        outDate = jsReplace(outDate, "mm", month);
    }

    // RETURN FOUR-DIGIT YEAR
    if (calDateFormat.indexOf("yyyy") != -1) {
        outDate = jsReplace(outDate, "yyyy", year);
    }
    // RETURN TWO-DIGIT YEAR
    else if (calDateFormat.indexOf("yy") != -1) {
        var yearString = "" + year;
        var yearString = yearString.substring(2,4);
        outDate = jsReplace(outDate, "yy", yearString);
    }
    // RETURN FOUR-DIGIT YEAR
    else if (calDateFormat.indexOf("YY") != -1) {
        outDate = jsReplace(outDate, "YY", year);
    }

    // RETURN DAY OF MONTH (Initial Caps)
    if (calDateFormat.indexOf("Month") != -1) {
        outDate = jsReplace(outDate, "Month", monthString);
    }
    // RETURN DAY OF MONTH (lowercase letters)
    else if (calDateFormat.indexOf("month") != -1) {
        outDate = jsReplace(outDate, "month", monthString.toLowerCase());
    }
    // RETURN DAY OF MONTH (UPPERCASE LETTERS)
    else if (calDateFormat.indexOf("MONTH") != -1) {
        outDate = jsReplace(outDate, "MONTH", monthString.toUpperCase());
    }

    // RETURN DAY OF MONTH 3-DAY ABBREVIATION (Initial Caps)
    if (calDateFormat.indexOf("Mon") != -1) {
        outDate = jsReplace(outDate, "Mon", monthAbbrev);
    }
    // RETURN DAY OF MONTH 3-DAY ABBREVIATION (lowercase letters)
    else if (calDateFormat.indexOf("mon") != -1) {
        outDate = jsReplace(outDate, "mon", monthAbbrev.toLowerCase());
    }
    // RETURN DAY OF MONTH 3-DAY ABBREVIATION (UPPERCASE LETTERS)
    else if (calDateFormat.indexOf("MON") != -1) {
        outDate = jsReplace(outDate, "MON", monthAbbrev.toUpperCase());
    }

    // RETURN WEEKDAY (Initial Caps)
    if (calDateFormat.indexOf("Weekday") != -1) {
        outDate = jsReplace(outDate, "Weekday", weekday);
    }
    // RETURN WEEKDAY (lowercase letters)
    else if (calDateFormat.indexOf("weekday") != -1) {
        outDate = jsReplace(outDate, "weekday", weekday.toLowerCase());
    }
    // RETURN WEEKDAY (UPPERCASE LETTERS)
    else if (calDateFormat.indexOf("WEEKDAY") != -1) {
        outDate = jsReplace(outDate, "WEEKDAY", weekday.toUpperCase());
    }

    // RETURN WEEKDAY 3-DAY ABBREVIATION (Initial Caps)
    if (calDateFormat.indexOf("Wkdy") != -1) {
        outDate = jsReplace(outDate, "Wkdy", weekdayAbbrev);
    }
    // RETURN WEEKDAY 3-DAY ABBREVIATION (lowercase letters)
    else if (calDateFormat.indexOf("wkdy") != -1) {
        outDate = jsReplace(outDate, "wkdy", weekdayAbbrev.toLowerCase());
    }
    // RETURN WEEKDAY 3-DAY ABBREVIATION (UPPERCASE LETTERS)
    else if (calDateFormat.indexOf("WKDY") != -1) {
        outDate = jsReplace(outDate, "WKDY", weekdayAbbrev.toUpperCase());
    }

    // SET THE VALUE OF THE FIELD THAT WAS PASSED TO THE CALENDAR
    calDateField.value = outDate;

    // GIVE FOCUS BACK TO THE DATE FIELD
    calDateField.focus();

    // CLOSE THE CALENDAR WINDOW
    top.newWin.close()
}

//CALL FUNCTION WHEN SCRIPT IS LOADED TO INITIALIZE THE CALENDAR
initializeCalendar();

/************************************************************************************
 * CUSTOM FUNCTIONS                                                                
 ***********************************************************************************/

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function KeyPressed()
{
  if (event.keyCode == 13) 
  {        
	event.cancelBubble = true;
	event.keyCode=9;
	event.returnValue = true;
  }
}

// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download. Instead,
// please just point to my URL to ensure the most up-to-date versions
// of the files. Thanks.
// ===================================================================


// ------------------------------------------------------------------
// These functions use the same 'format' strings as the 
// java.text.SimpleDateFormat class, with minor exceptions.
// The format string consists of the following abbreviations:
// 
// Field        | Full Form          | Short Form
// -------------+--------------------+-----------------------
// Year         | yyyy (4 digits)    | yy (2 digits), y (2 or 4 digits)
// Month        | MMM (name or abbr.)| MM (2 digits), M (1 or 2 digits)
// Day of Month | dd (2 digits)      | d (1 or 2 digits)
// Hour (1-12)  | hh (2 digits)      | h (1 or 2 digits)
// Hour (0-23)  | HH (2 digits)      | H (1 or 2 digits)
// Hour (0-11)  | KK (2 digits)      | K (1 or 2 digits)
// Hour (1-24)  | kk (2 digits)      | k (1 or 2 digits)
// Minute       | mm (2 digits)      | m (1 or 2 digits)
// Second       | ss (2 digits)      | s (1 or 2 digits)
// AM/PM        | a                  |
//
// NOTE THE DIFFERENCE BETWEEN MM and mm! Month=MM, not mm!
// Examples:
//  "MMM d, y" matches: January 01, 2000
//                      Dec 1, 1900
//                      Nov 20, 00
//  "M/d/yy"   matches: 01/20/00
//                      9/2/00
//  "MMM dd, yyyy hh:mm:ssa" matches: "January 01, 2000 12:30:45AM"
// ------------------------------------------------------------------

var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
function LZ(x) {return(x<0||x>9?"":"0")+x}

// ------------------------------------------------------------------
// isDate ( date_string, format_string )
// Returns true if date string matches format of format string and
// is a valid date. Else returns false.
// It is recommended that you trim whitespace around the value before
// passing it to this function, as whitespace is NOT ignored!
// ------------------------------------------------------------------
function isDate(val,format) {
	var date=getDateFromFormat(val,format);
	if (date==0) { return false; }
	return true;
	}

// -------------------------------------------------------------------
// compareDates(date1,date1format,date2,date2format)
//   Compare two date strings to see which is greater.
//   Returns:
//   1 if date1 is greater than date2
//   0 if date2 is greater than date1 of if they are the same
//  -1 if either of the dates is in an invalid format
// -------------------------------------------------------------------
function compareDates(date1,dateformat1,date2,dateformat2) {
	var d1=getDateFromFormat(date1,dateformat1);
	var d2=getDateFromFormat(date2,dateformat2);
	if (d1==0 || d2==0) {
		return -1;
		}
	else if (d1 > d2) {
		return 1;
		}
	return 0;
	}

// ------------------------------------------------------------------
// formatDate (date_object, format)
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
function formatDate(date,format) {
	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=LZ(M);
	value["MMM"]=MONTH_NAMES[M-1];
	value["d"]=d;
	value["dd"]=LZ(d);
	value["H"]=H;
	value["HH"]=LZ(H);
	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=LZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H+1;
	value["KK"]=LZ(value["K"]);
	value["kk"]=LZ(value["k"]);
	if (H > 11) { value["a"]="PM"; }
	else { value["a"]="AM"; }
	value["m"]=m;
	value["mm"]=LZ(m);
	value["s"]=s;
	value["ss"]=LZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}
	return result;
	}
	
// ------------------------------------------------------------------
// Utility functions for parsing in getDateFromFormat()
// ------------------------------------------------------------------
function _isInteger(val) {
	var digits="1234567890";
	for (var i=0; i < val.length; i++) {
		if (digits.indexOf(val.charAt(i))==-1) { return false; }
		}
	return true;
	}
function _getInt(str,i,minlength,maxlength) {
	for (var x=maxlength; x>=minlength; x--) {
		var token=str.substring(i,i+x);
		if (token.length < minlength) { return null; }
		if (_isInteger(token)) { return token; }
		}
	return null;
	}
	
// ------------------------------------------------------------------
// getDateFromFormat( date_string , format_string )
//
// This function takes a date string and a format string. It matches
// If the date string matches the format string, it returns the 
// getTime() of the date. If it does not match, it returns 0.
// ------------------------------------------------------------------
function getDateFromFormat(val,format) {
	val=val+"";
	format=format+"";
	var i_val=0;
	var i_format=0;
	var c="";
	var token="";
	var token2="";
	var x,y;
	var now=new Date();
	var year=now.getYear();
	var month=now.getMonth()+1;
	var date=now.getDate();
	var hh=now.getHours();
	var mm=now.getMinutes();
	var ss=now.getSeconds();
	var ampm="";
	
	while (i_format < format.length) {
		// Get next token from format string
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		// Extract contents of value based on format token
		if (token=="yyyy" || token=="yy" || token=="y") {
			if (token=="yyyy") { x=4;y=4; }
			if (token=="yy")   { x=2;y=2; }
			if (token=="y")    { x=2;y=4; }
			year=_getInt(val,i_val,x,y);
			if (year==null) { return 0; }
			i_val += year.length;
			if (year.length==2) {
				if (year > 70) { year=1900+(year-0); }
				else { year=2000+(year-0); }
				}
			}
		else if (token=="MMM"){
			month=0;
			for (var i=0; i<MONTH_NAMES.length; i++) {
				var month_name=MONTH_NAMES[i];
				if (val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()) {
					month=i+1;
					if (month>12) { month -= 12; }
					i_val += month_name.length;
					break;
					}
				}
			if ((month < 1)||(month>12)){return 0;}
			}
		else if (token=="MM"||token=="M") {
			month=_getInt(val,i_val,token.length,2);
			if(month==null||(month<1)||(month>12)){return 0;}
			i_val+=month.length;}
		else if (token=="dd"||token=="d") {
			date=_getInt(val,i_val,token.length,2);
			if(date==null||(date<1)||(date>31)){return 0;}
			i_val+=date.length;}
		else if (token=="hh"||token=="h") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>12)){return 0;}
			i_val+=hh.length;}
		else if (token=="HH"||token=="H") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>23)){return 0;}
			i_val+=hh.length;}
		else if (token=="KK"||token=="K") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>11)){return 0;}
			i_val+=hh.length;}
		else if (token=="kk"||token=="k") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>24)){return 0;}
			i_val+=hh.length;hh--;}
		else if (token=="mm"||token=="m") {
			mm=_getInt(val,i_val,token.length,2);
			if(mm==null||(mm<0)||(mm>59)){return 0;}
			i_val+=mm.length;}
		else if (token=="ss"||token=="s") {
			ss=_getInt(val,i_val,token.length,2);
			if(ss==null||(ss<0)||(ss>59)){return 0;}
			i_val+=ss.length;}
		else if (token=="a") {
			if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";}
			else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";}
			else {return 0;}
			i_val+=2;}
		else {
			if (val.substring(i_val,i_val+token.length)!=token) {return 0;}
			else {i_val+=token.length;}
			}
		}
	// If there are any trailing characters left in the value, it doesn't match
	if (i_val != val.length) { return 0; }
	// Is date valid for month?
	if (month==2) {
		// Check for leap year
		if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year
			if (date > 29){ return false; }
			}
		else { if (date > 28) { return false; } }
		}
	if ((month==4)||(month==6)||(month==9)||(month==11)) {
		if (date > 30) { return false; }
		}
	// Correct hours value
	if (hh<12 && ampm=="PM") { hh+=12; }
	else if (hh>11 && ampm=="AM") { hh-=12; }
	var newdate=new Date(year,month-1,date,hh,mm,ss);
	return newdate.getTime();
	}



function confirmUpload(form,val) {
     var answer = confirm(val)
     if (answer){
         return true;
     }
     else{
         return false;
     }

}

function openChild(file, window) {
  childWindow=open(file, window, 'resizable=no, scrollbars=1, width=610, height=580, left=212, top=50');
  if (childWindow.opener == null)
    childWindow.opener = self;
}

function openChildWithAttributes(file, window, attributes) {
  childWindow=open(file, window, attributes);
  if (childWindow.opener == null)
    childWindow.opener = self;
}

function updateQtyToOrder(checkboxID, item_id) {
  oElemOrigQty = document.getElementById("SelectItemToOrder_txtOrigQty" + item_id);
  oElemOrderQty = document.getElementById("SelectItemToOrder_txtQuantity" + item_id);
  if (oElemOrderQty != null) {
    if (oElemOrigQty != null) {
      if (checkboxID.checked)
        oElemOrderQty.value = oElemOrigQty.value;
      else
        oElemOrderQty.value = '';
    }
    else {
      if (checkboxID.checked)
        oElemOrderQty.value = 1;
      else
        oElemOrderQty.value = '';
    }
  }
}

function updateSelectedCheckBox(QuantityToOrderID, item_id) {
  if (document.getElementById)
    oElemCB = document.getElementById("SelectItemToOrder_item" + item_id);
  if (oElemCB != null) {
    if (QuantityToOrderID.value != '')
      oElemCB.checked = true;
    else
      oElemCB.checked = false;
  }
}

function updatePlacedOrder(iLines) {
  if (validateAllQtyToOrder(iLines)) {;
    if (confirm('Are you sure you want to submit this order?')) {
      if (document.getElementById)
        oElemCB = document.getElementById("PlacedOrder");
      if (oElemCB != null) {
        oElemCB.value = 'Y';
        return true;
      }
    }
  }
  return false;
}

function validateQtyToOrder(QuantityToOrderID, item_id) {
  if (document.getElementById) {
    oElemCB = document.getElementById("SelectItemToOrder_item" + item_id);
    oElemOrigQty = document.getElementById("SelectItemToOrder_txtOrigQty" + item_id);
  }
  if (oElemCB != null) {
    if ((QuantityToOrderID.value != '') && (QuantityToOrderID.value != 0) && (!isNaN(parseFloat(QuantityToOrderID.value)))) {
      oElemCB.checked = true;
      if (parseFloat(QuantityToOrderID.value) < parseFloat(oElemOrigQty.value)) {
        alert('Please enter a quantity greater than or equal to the quoted quantity.');
        QuantityToOrderID.focus();
        QuantityToOrderID.select();
        return;
      }
      QuantityToOrderID.value = parseFloat(QuantityToOrderID.value);
    } else {
      oElemCB.checked = false;
      QuantityToOrderID.value = '';
    }
  }
}

function validateAllQtyToOrder(iLines) {
  var bItemToAdd = false;
  for (var i = 0; i < iLines; i++) {
    oElem = document.getElementById("SelectItemToOrder_txtQuantity" + i);
    if (oElem != null) {
      if ((oElem.value != '') && (oElem.value != 0) && (!isNaN(parseFloat(oElem.value)))) {
        bItemToAdd = true;
        break;
      }
    }
  }
  if (!bItemToAdd) {
    alert('Please select at least one item before submiting order.');
    return false;
  } else
      return true;
}

function changeCssWidthRuleToContents(className) {
  var cssRules = new Array();
  var sContent = '.Content';
  var sContentWidth;
  var x;

  if (document.styleSheets[0].cssRules)
    cssRules = document.styleSheets[0].cssRules;
  else if (document.styleSheets[0].rules)
    cssRules = document.styleSheets[0].rules;

  for (x = 0; x < cssRules.length; x++) {
    if (cssRules[x].selectorText == sContent) {
      sContentWidth = cssRules[x].style.width;
    }
  }

  for (x = 0; x < cssRules.length; x++) {
    if (cssRules[x].selectorText == className) {
      cssRules[x].style.width = sContentWidth;
    }
  }
}

function CheckMaxRowsChars(textarea, iMaxRows, iMaxCharsPerRow, iMaxCharacters) {
  var lines = textarea.value.replace(/\r/g,'').split('\n');
  
  //Check if Max Rows reached
  if (iMaxRows && lines.length > iMaxRows) {
    for (var i = 0; i < lines.length; i++) {
      //Remove blank lines first
      if (lines[i] == '')
        textarea.value = lines.slice(0, i).concat(lines.slice(i + 1, lines.length)).join('\n');
    }

    //If number of rows are still > than max then just remove last line
    lines = textarea.value.replace(/\r/g,'').split('\n');
    if (lines.length > iMaxRows)
      textarea.value = lines.slice(0, iMaxRows).join('\n');
    alert('Only '+ iMaxRows + ' lines are allowed.'); 
  }

  //Check if max characters per row reached: Loop through all rows
  for (var i = 0; iMaxCharsPerRow && (i < lines.length); i++) {
    if (lines[i].length > iMaxCharsPerRow) {
      //Remove last charcter
      lines[i] = lines[i].substring(0, iMaxCharsPerRow);
      textarea.value = lines.join('\n');
      alert('Only ' + iMaxCharsPerRow + ' characters are allowed per row.');
    }
  }

  //Check if max characters reached
  if (iMaxCharacters) {
    lines = textarea.value.replace(/^\s+|\s+$/g, '');
    if (lines.length > iMaxCharacters) {
      //Remove everything after limit
      textarea.value = lines.substring(0, iMaxCharacters);
      alert('Only ' + iMaxCharacters + ' characters are allowed.');
    }
  }
  
}

function getElementById(id) {
  if (document.getElementById)
    return document.getElementById(id);
  if (document.all)
    return document.all[id];
}

if (!Number.toFixed) {
Number.prototype.toFixed=function(x) {
   var temp=this;
   temp=Math.round(temp*Math.pow(10,x))/Math.pow(10,x);
   return temp;
};
}

var ie = document.all;

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;
   
   }


function AppendZeros(number, length) {
    var str = '' + number;

    if (number == 0)
      str = '0.00';

    if (str.split('.')[1] == null)
      return str;

    while (str.split('.')[1].length < length) {
        str = str + '0';

    }
    return str;
}

function AppendZeros1(number, length) {
    var str = '' + number;

    if (number == 0)
      str = '0.00';

    if (str.split('.')[1] == null)
      str = str + '.00';

    while (str.split('.')[1].length < length) {
        str = str + '0';

    }
    return str;
}


function getObjInnerText (obj) { 
return (obj.innerText) ? obj.innerText 
: (obj.textContent) ? obj.textContent 
: ""; 
} 

function updateFreight(NewFreightAmount, replaceZeroFreight) {
  var TotalAmount, FreightAmount, iDecimalNumbers;

  if (NewFreightAmount == null)
    NewFreightAmount = 0.00;

  eFreightAmount = getElementById('FreightAmount');
  if (eFreightAmount == null)
    return;

  eInvoiceTotal = getElementById('InvoiceTotal');
  if (eInvoiceTotal == null)
    return;

  if (getObjInnerText(eFreightAmount).indexOf('.') < 0) {
    if (!IsNumeric(getObjInnerText(eFreightAmount))) {
      if (ie)
        eFreightAmount.innerText = '$0.00';
      else
        eFreightAmount.textContent = '$0.00';
    }
    else {
      if (ie)
        eFreightAmount.innerText = AppendZeros(getObjInnerText(eFreightAmount) + '.', 2);
      else
        eFreightAmount.textContent = AppendZeros(getObjInnerText(eFreightAmount) + '.', 2);
    }
  }

  if (getObjInnerText(eInvoiceTotal).indexOf('.') < 0) {
    if (ie)
      eInvoiceTotal.innerText = AppendZeros(getObjInnerText(eInvoiceTotal) + '.', 2);
    else
      eInvoiceTotal.textContent = AppendZeros(getObjInnerText(eInvoiceTotal) + '.', 2);
  }
    
  iDecimalNumbers = getObjInnerText(eInvoiceTotal).split('.')[1].length;
 
  FreightAmount = parseFloat(getObjInnerText(eFreightAmount).split('$')[1]);
  if (FreightAmount == null)
    FreightAmount = 0;

  TotalAmount = parseFloat(getObjInnerText(eInvoiceTotal).split('$')[1]);
  if (TotalAmount == null)
    TotalAmount = 0;

  TotalAmount = (TotalAmount.toFixed(iDecimalNumbers) - FreightAmount.toFixed(iDecimalNumbers)).toFixed(iDecimalNumbers);

  if (TotalAmount < 0)
    TotalAmount = 0;

  TotalAmount = (TotalAmount.toFixed(iDecimalNumbers) + parseFloat(NewFreightAmount).toFixed(iDecimalNumbers)).toFixed(iDecimalNumbers);

  if ((parseFloat(NewFreightAmount) <= 0) && (replaceZeroFreight.length > 0)) {
    if (ie)
      eFreightAmount.innerText = replaceZeroFreight;
    else
      eFreightAmount.textContent = replaceZeroFreight;
  }
  else {
    if (ie)
      eFreightAmount.innerText = '$' + AppendZeros(NewFreightAmount, iDecimalNumbers);
    else
      eFreightAmount.textContent = '$' + AppendZeros(NewFreightAmount, iDecimalNumbers);
  }

  if (ie)
    eInvoiceTotal.innerText = '$' + AppendZeros(TotalAmount, iDecimalNumbers);
  else
    eInvoiceTotal.textContent = '$' + AppendZeros(TotalAmount, iDecimalNumbers);
}

function printBabyprint(){
  var browser=navigator.appName;

  if ((browser=="Microsoft Internet Explorer")) {
    //document.execCommand('print', false, null); 
    window.print();
  }
  else {
    window.print();
  }
}

function setFonts()
   {
    var myRatio=parseInt((parseInt(parent.document.body.offsetWidth)/640)*100);
    myRatio=(myRatio > 100 ? myRatio : 100);
    document.styleSheets[document.styleSheets.length-1].rules[0].style.zoom=myRatio+"%";
   }

function trimAll(sString) 
{ 
  while (sString.substring(0,1) == ' ') 
    sString = sString.substring(1, sString.length); 
  
  while (sString.substring(sString.length-1, sString.length) == ' ') 
    sString = sString.substring(0,sString.length-1); 

  return sString; 
} 


function hideUPSFields()
{
  oElem = getElementById("UPSTable");
  if (oElem != null) {
    oElem.style.visibility = 'hidden';
    oElem.style.display = 'none';
  }
}

function viewUPSFields()
{
  oElem = getElementById("UPSTable");
  if (oElem != null) {
    oElem.style.visibility = 'visible';
    oElem.style.display = 'block';
  }
}

function AdminFreightSumbit(fAdminFreight)
{
  oAction = getElementById("action");
  oAction.value = "list";
  fAdminFreight.submit();
}

function RemoveShoppingCartItem(rcuid, sFormName)
{
  var eForm = document.getElementsByName(sFormName)[0];

  document.getElementById('rcuid').value = rcuid;
  eForm.action += "&Action=REMOVE";
  eForm.submit();
}

function pad(value, length) {
  value = String(value);
  length = parseInt(length) || 2;
  while (value.length < length)
    value = "0" + value;
  return value;
}

function setToday() {
  var today = new Date;

  today = pad( ( today.getMonth() + 1 ) ) + "/" +
          pad( ( today.getDate() ) ) + "/" +
          today.getFullYear();

  return today;
}

function setTomorrow() {
  var tomorrow = new Date;

  tomorrow.setDate(tomorrow.getDate() + 1);

  tomorrow = pad( ( tomorrow.getMonth() + 1 ) ) + "/" +
             pad( ( tomorrow.getDate() ) ) + "/" +
             tomorrow.getFullYear();

  return tomorrow;
}

function changeMonitorPerformance(elem)
{
  oMonitorPerformanceStartDate = getElementById("MonitorPerformanceStartDate");
  oddMonitorPerformanceStartHour = getElementById("ddMonitorPerformanceStartHour");
  oddMonitorPerformanceStartMinute = getElementById("ddMonitorPerformanceStartMinute");
  oddMonitorPerformanceStartAMPM = getElementById("ddMonitorPerformanceStartAMPM");

  oMonitorPerformanceEndDate = getElementById("MonitorPerformanceEndDate");
  oddMonitorPerformanceEndHour = getElementById("ddMonitorPerformanceEndHour");
  oddMonitorPerformanceEndMinute = getElementById("ddMonitorPerformanceEndMinute");
  oddMonitorPerformanceEndAMPM = getElementById("ddMonitorPerformanceEndAMPM");

  if (elem.checked) {
    oMonitorPerformanceStartDate.value = setToday();
    oMonitorPerformanceEndDate.value = setTomorrow();
    oddMonitorPerformanceStartHour.value = 12;
    oddMonitorPerformanceStartMinute.value = 0;
    oddMonitorPerformanceStartAMPM.value = 1;

    oddMonitorPerformanceEndHour.value = 12;
    oddMonitorPerformanceEndMinute.value = 0;
    oddMonitorPerformanceEndAMPM.value = 1;
  }
  else {
    oMonitorPerformanceStartDate.value = "";
    oMonitorPerformanceEndDate.value = "";

    oddMonitorPerformanceStartHour.value = 12;
    oddMonitorPerformanceStartMinute.value = 0;
    oddMonitorPerformanceStartAMPM.value = 1;

    oddMonitorPerformanceEndHour.value = 12;
    oddMonitorPerformanceEndMinute.value = 0;
    oddMonitorPerformanceEndAMPM.value = 1;
  }
}

function ShipMethodExceptionMessage(sSet)
{
  var sNoAutoAllocation;
  var eShipMethodOption;
  var eSpanAutoAlloc;

  eSpanAutoAlloc = document.getElementById('spanAutoAllocShipMethodMessage');

  if (eSpanAutoAlloc != null) {
    if (sSet == null) {
      eShipMethodOption = document.ShipBill_Information_Content.txtShipMethod[document.ShipBill_Information_Content.txtShipMethod.selectedIndex];
      if (eShipMethodOption != null) {
        sNoAutoAllocation = eShipMethodOption.getAttribute("NoAutoAllocation");
      }
    }
    else {
      sNoAutoAllocation = sSet;
    }

    if ((sNoAutoAllocation == 'Y') || (sNoAutoAllocation == 'TRUE')) {
      document.getElementById('spanAutoAllocShipMethodMessage').style.visibility = 'visible';
      document.getElementById('spanAutoAllocShipMethodMessage').style.display = 'block';
    }
    else {
      document.getElementById('spanAutoAllocShipMethodMessage').style.visibility = 'hidden';
      document.getElementById('spanAutoAllocShipMethodMessage').style.display = 'none';
    }
  }
}

function ShipMethodFreeFreightChange()
{
  var sShipMethodFreightCode;
  var sShipMethodFreeShippingOrder;
  var eShipMethodOption;
  var eDivFreeShippingDisplay;
  var eHdnFreeShippingOrder;

  eDivFreeShippingDisplay = document.getElementById('divFreeShippingDisplay');
  eHdnFreeShippingOrder = document.getElementById('hdnFreeShippingOrder');

  if (eDivFreeShippingDisplay != null) {
    eShipMethodOption = document.ShipBill_Information_Content.txtShipMethod[document.ShipBill_Information_Content.txtShipMethod.selectedIndex];
    if (eShipMethodOption != null) {
      sShipMethodFreightCode = eShipMethodOption.getAttribute("FreightCode");
      sShipMethodFreeShippingOrder = eShipMethodOption.getAttribute("FreeShipping");
    }

    if (sShipMethodFreightCode == document.getElementById('hdnFreightCode').value) {
      eDivFreeShippingDisplay.style.visibility = 'visible';
      eDivFreeShippingDisplay.style.display = 'block';
      eHdnFreeShippingOrder.value = sShipMethodFreeShippingOrder
    }
    else {
      eDivFreeShippingDisplay.style.visibility = 'hidden';
      eDivFreeShippingDisplay.style.display = 'none';
      eHdnFreeShippingOrder.value = sShipMethodFreeShippingOrder
    }
  }
}

function clearShopperListSearchValue()
{
  var oElem;
  
  oElem = document.frmSearch.SearchValue;
  
  if (oElem.value == 'Keyword')
    oElem.value = '';
  else
    oElem.select();
}

function leaveFocusShopperListSearchValue()
{
  var oElem;

  oElem = document.frmSearch.SearchValue;
  
  if (oElem.value == '')
    oElem.value = 'Keyword';  
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}


function setSLDAddToCheckBox(oldValue, newValue, sLineNumber)
{
  var oElem, oElem2;

  newValue = newValue.trim();

  oElem = document.getElementById("AddToCartCB" + sLineNumber);

  if (oElem.value != null) {
    if (newValue == '')
      oElem.checked = false;
    else if (isNaN(newValue)) {
      oElem2 = document.getElementById("txtShoppingListQuantity" + sLineNumber);
      if (oElem2 != null)
        oElem2.value = oldValue;
    }
    else if (newValue == '0')
      oElem.checked = false;
    else if (oldValue != newValue)
      oElem.checked = true;
  }  
}


function createStatesProvincesDDTXT(tdStatesDD, tdProvincesDD, tdStatesTXT, sHiddenState, sHiddenCountry, sAdditionalEvents, sAdditionalOnChange)  {
  createStatesProvincesDD(tdStatesDD, tdProvincesDD, sHiddenState, sAdditionalEvents, sAdditionalOnChange);
  createStateTXT(tdStatesTXT, sHiddenState, sAdditionalEvents, sAdditionalOnChange);
  displayDDStatesOrDDProvincesOrTxtStates(tdStatesDD, tdProvincesDD, tdStatesTXT, sHiddenState, sHiddenCountry)
}


function createStatesProvincesDD(tdStatesDD, tdProvincesDD, sHiddenState, sAdditionalEvents, sAdditionalOnChange) {
  ddStates(tdStatesDD, sHiddenState, sAdditionalEvents, sAdditionalOnChange);
  ddProvinces(tdProvincesDD, sHiddenState, sAdditionalEvents, sAdditionalOnChange);
}


function ddStates(tdStates, sHiddenState, sAdditionalEvents, sAdditionalOnChange) {
  var sStates, idStates, sSelection, sCurrentValue;

  idStates = tdStates.replace("td", "dd");
  sStates =  "<select name='" + idStates + "' id='" + idStates + "' class='ddStates' onchange=\"updateHiddenState(this.value, '" + sHiddenState + "');" + sAdditionalOnChange + "\"" + sAdditionalEvents + ">";

  sStates += "<option value=''>--Select a State--</option>";
  sStates += "<option value='AK'>Alaska</option>";
  sStates += "<option value='AL'>Alabama</option>";
  sStates += "<option value='AR'>Arkansas</option>";
  sStates += "<option value='AZ'>Arizona</option>";
  sStates += "<option value='CA'>California</option>";
  sStates += "<option value='CO'>Colorado</option>";
  sStates += "<option value='CT'>Connecticut</option>";
  sStates += "<option value='DC'>District of Columbia</option>";
  sStates += "<option value='DE'>Delaware</option>";
  sStates += "<option value='FL'>Florida</option>";
  sStates += "<option value='GA'>Georgia</option>";
  sStates += "<option value='HI'>Hawaii</option>";
  sStates += "<option value='IA'>Iowa</option>";
  sStates += "<option value='ID'>Idaho</option>";
  sStates += "<option value='IL'>Illinois</option>";
  sStates += "<option value='IN'>Indiana</option>";
  sStates += "<option value='KS'>Kansas</option>";
  sStates += "<option value='KY'>Kentucky</option>";
  sStates += "<option value='LA'>Louisiana</option>";
  sStates += "<option value='MA'>Massachusetts</option>";
  sStates += "<option value='MD'>Maryland</option>";
  sStates += "<option value='ME'>Maine</option>";
  sStates += "<option value='MI'>Michigan</option>";
  sStates += "<option value='MN'>Minnesota</option>";
  sStates += "<option value='MO'>Missouri</option>";
  sStates += "<option value='MS'>Mississippi</option>";
  sStates += "<option value='MT'>Montana</option>";
  sStates += "<option value='NC'>North Carolina</option>";
  sStates += "<option value='ND'>North Dakota</option>";
  sStates += "<option value='NE'>Nebraska</option>";
  sStates += "<option value='NH'>New Hampshire</option>";
  sStates += "<option value='NJ'>New Jersey</option>";
  sStates += "<option value='NM'>New Mexico</option>";
  sStates += "<option value='NV'>Nevada</option>";
  sStates += "<option value='NY'>New York</option>";
  sStates += "<option value='OH'>Ohio</option>";
  sStates += "<option value='OK'>Oklahoma</option>";
  sStates += "<option value='OR'>Oregon</option>";
  sStates += "<option value='PA'>Pennsylvania</option>";
  sStates += "<option value='PR'>Puerto Rico</option>";
  sStates += "<option value='RI'>Rhode Island</option>";
  sStates += "<option value='SC'>South Carolina</option>";
  sStates += "<option value='SD'>South Dakota</option>";
  sStates += "<option value='TN'>Tennessee</option>";
  sStates += "<option value='TX'>Texas</option>";
  sStates += "<option value='UT'>Utah</option>";
  sStates += "<option value='VA'>Virginia</option>";
  sStates += "<option value='VT'>Vermont</option>";
  sStates += "<option value='WA'>Washington</option>";
  sStates += "<option value='WI'>Wisconsin</option>";
  sStates += "<option value='WV'>West Virginia</option>";
  sStates += "<option value='WY'>Wyoming</option>";
  sStates += "<option value='AA'>Military Americas</option>";
  sStates += "<option value='AE'>Military Europe/ME/Canada</option>";
  sStates += "<option value='AP'>Military Pacific</option>";
  sStates += "</select>";

  document.getElementById(tdStates).innerHTML = sStates;
  oElem = document.getElementById(sHiddenState);

  if (oElem != null)
    sCurrentValue = oElem.value;
  else
    sCurrentValue = '';

  oElem = document.getElementById(idStates);

  for (i = 0;(i < oElem.options.length); i++) {
    if (oElem.options[i].value == sCurrentValue)
      oElem.options[i].selected = true;
  }

}


function ddProvinces(tdProvinces, sHiddenState, sAdditionalEvents, sAdditionalOnChange) {
  var sProvinces, idProvinces;

  idProvinces = tdProvinces.replace("td", "dd");

  sProvinces =  "<select name='" + idProvinces + "' id='" + idProvinces + "' class='ddProvinces' onchange='updateHiddenState(this.value, \"" + sHiddenState + "\");" + sAdditionalOnChange + "' " + sAdditionalEvents + ">";
  sProvinces += "<option value=''>--Select a Province--</option>";
  sProvinces += "<option value='AB'>Alberta</option>";
  sProvinces += "<option value='BC'>British Columbia</option>";
  sProvinces += "<option value='MB'>Manitoba</option>";
  sProvinces += "<option value='NB'>New Brunswick</option>";
  sProvinces += "<option value='NF'>Newfoundland</option>";
  sProvinces += "<option value='NT'>Northwest Territories</option>";
  sProvinces += "<option value='NS'>Nova Scotia</option>";
  sProvinces += "<option value='NU'>Nunavut</option>";
  sProvinces += "<option value='ON'>Ontario</option>";
  sProvinces += "<option value='PE'>Prince Edward Island</option>";
  sProvinces += "<option value='QC'>Quebec</option>";
  sProvinces += "<option value='SK'>Saskatchewan</option>";
  sProvinces += "<option value='YT'>Yukon Territory</option>";
  sProvinces += "</select>";

  document.getElementById(tdProvinces).innerHTML = sProvinces;

  oElem = document.getElementById(sHiddenState);

  if (oElem != null)
    sCurrentValue = oElem.value;
  else
    sCurrentValue = '';

  oElem = document.getElementById(idProvinces);

  for (i = 0;(i < oElem.options.length); i++) {
    if (oElem.options[i].value == sCurrentValue)
      oElem.options[i].selected = true;
  }

}


function createStateTXT(tdStates, sHiddenState, sAdditionalEvents, sAdditionalOnChange) {
  var sStates, idStates, sCurrentValue;

  oElem = document.getElementById(sHiddenState);

  if (oElem != null)
    sCurrentValue = oElem.value;
  else
    sCurrentValue = '';

  idStates = tdStates.replace("td", "TXT");

  sStates = "<input type='text' maxLength='2' id='" + idStates + "' name='" + idStates + "' class='TXTStates' onchange=\"updateHiddenState(this.value, '" + sHiddenState + "');" + sAdditionalOnChange + "\" value='" + sCurrentValue + "'" + sAdditionalEvents + " />";

  document.getElementById(tdStates).innerHTML = sStates;

}

function updateHiddenState(txtValue, sHiddenState) {
  oElem = document.getElementById(sHiddenState);
  if (oElem != null)
    oElem.value = txtValue;
}


function displayDDStatesOrDDProvincesOrTxtStates(tdStates, tdProvinces, txtStates, sHiddenState, sHiddenCountry, bOpener) {
  var bDDStatesDisplay, bDDProvincesDisplay, bTxtStateDisplay, sSelectedCountry, StateAsterisk;

  bDDStatesDisplay = false;
  bDDProvincesDisplay = false;
  bTxtStateDisplay = false;

  oElem = (bOpener) ? opener.document.getElementById(sHiddenState) : document.getElementById(sHiddenState);
  if (oElem != null)
    sSelectedState = oElem.value;
  else
    sSelectedState = '';

  oElem = (bOpener) ? opener.document.getElementById(sHiddenCountry) : document.getElementById(sHiddenCountry);
  if (oElem != null)
    sSelectedCountry = oElem.value;
  else
    sSelectedCountry = '';

  sSelectedCountry = sSelectedCountry.toUpperCase();

  if ((sSelectedCountry == 'UNITED STATES OF AMERICA') || (sSelectedCountry == 'USA') || (sSelectedCountry == 'UNITED STATES') || (sSelectedCountry == 'U.S.A.') || (sSelectedCountry == 'US') || (sSelectedCountry == 'AMERICA') || (sSelectedCountry == 'U.S.'))
    bDDStatesDisplay = true;
  else if (sSelectedCountry == 'CANADA')
    bDDProvincesDisplay = true;
  else
    bTxtStateDisplay = true;

  StateAsterisk = tdStates.replace("td","").replace("DD","Asterisk");
  if (bOpener) {
    if (! opener.document.getElementById(StateAsterisk))
      StateAsterisk = "divStateReq";
  }
  else {
    if (! document.getElementById(StateAsterisk))
      StateAsterisk = "divStateReq";
  }

  oElem = (bOpener) ? opener.document.getElementById(tdStates) : document.getElementById(tdStates);
  if (oElem != null) {
    if (bDDStatesDisplay) {
      oElem.style.visibility = 'visible';
      oElem.style.display = 'block';

      oElem = (bOpener) ? opener.document.getElementById(StateAsterisk) : document.getElementById(StateAsterisk);
      if (oElem != null) {
        oElem.style.visibility = 'visible';
        oElem.style.display = 'inline';
      }
    }
    else {
      oElem.style.visibility = 'hidden';
      oElem.style.display = 'none';
      oElem = (bOpener) ? opener.document.getElementById(tdStates.replace("td","dd")) : document.getElementById(tdStates.replace("td","dd"));
      if (oElem != null)
        oElem.value = '';
    }
  }

  oElem = (bOpener) ? opener.document.getElementById(tdProvinces) : document.getElementById(tdProvinces);
  if (oElem != null) {
    if (bDDProvincesDisplay) {
      oElem.style.visibility = 'visible';
      oElem.style.display = 'block';

      oElem = (bOpener) ? opener.document.getElementById(StateAsterisk) : document.getElementById(StateAsterisk);
      if (oElem != null) {
        oElem.style.visibility = 'visible';
        oElem.style.display = 'inline';
      }
    }
    else {
      oElem.style.visibility = 'hidden';
      oElem.style.display = 'none';
      oElem = (bOpener) ? opener.document.getElementById(tdProvinces.replace("td","dd")) : document.getElementById(tdProvinces.replace("td","dd"));
      if (oElem != null)
        oElem.value = '';
    }

  }

  oElem = (bOpener) ? opener.document.getElementById(txtStates) : document.getElementById(txtStates);
  if (oElem != null) {
    if (bTxtStateDisplay) {
      oElem.style.visibility = 'visible';
      oElem.style.display = 'block';

      oElem = (bOpener) ? opener.document.getElementById(StateAsterisk) : document.getElementById(StateAsterisk);
      if (oElem != null) {
        oElem.style.visibility = 'hidden';
        oElem.style.display = 'none';
      }
    }
    else {
      oElem.style.visibility = 'hidden';
      oElem.style.display = 'none';
      oElem = (bOpener) ? opener.document.getElementById(txtStates.replace("td","TXT")) : document.getElementById(txtStates.replace("td","TXT"));
      if (oElem != null)
        oElem.value = '';
    }
  } 
}


function createCountriesDD(tdCountriesDD, tdStatesDD, tdProvincesDD, tdStatesTXT, sHiddenCountry, sHiddenState, sAdditionalEvents, sAdditionalOnChange) 
{
  var  abbreviationForUS, canadaAndUSOnly;
  abbreviationForUS = GetSystemAttribute('P21SystemAttribute', 'ValueForUSInCountryDropDown')
  if (abbreviationForUS == '') 
  {
    abbreviationForUS = 'US'
  }
  canadaAndUSOnly = GetSystemAttribute('P21SystemAttribute', 'OnlyShowUSAndCanadaInCountryDropDown')
  if (canadaAndUSOnly == '') 
  {
    canadaAndUSOnly = 'N'
  }

  var idCountries, bCountryFound;

  idCountries = tdCountriesDD.replace("td","dd")

  if (tdStatesDD != null) 
    sCountries =  "<select name='" + idCountries + "' id='" + idCountries + "' class='ddCountries' onChange=\"checkSelectedCountry(this.value, '" + tdStatesDD + "', '" + tdProvincesDD + "', '" + tdStatesTXT + "', '" + sHiddenCountry + "', '" + sHiddenState + "');" + sAdditionalOnChange + "\"" + sAdditionalEvents + ">";
  else
    sCountries =  "<select name='" + idCountries + "' id='" + idCountries + "' class='ddCountries' onChange=\"checkSelectedCountry(this.value, '', '', '', '" + sHiddenCountry + "', '');\">";


  sCountries += "<option value='" + abbreviationForUS + "'>United States</option>";
  sCountries += "<option value='Canada'>Canada</option>";
  if (canadaAndUSOnly == 'N')
    sCountries += GetSessionSetting("CountryCodesNotUSOrCanada").replace("<![CDATA[","").replace("]]>","");

  sCountries += "</select>";

  oElem = document.getElementById(tdCountriesDD);
  oElem.innerHTML = sCountries;
  oElem.style.visibility = 'visible';
  oElem.style.display = 'block';


  oElem = document.getElementById(sHiddenCountry);
  if (oElem != null)
    sSelectedCountry = oElem.value;
  else
    sSelectedCountry = '';

  if (sSelectedCountry == '')
    sSelectedCountry = abbreviationForUS;

  oElem = document.getElementById(idCountries);

  bCountryFound = false;

  for (i = 0;(i < oElem.options.length); i++) {
    if (oElem.options[i].value == sSelectedCountry) {
      oElem.options[i].selected = true;
      bCountryFound = true;
    }
  }

  if (!bCountryFound) {
    sSelectedCountrytmp = sSelectedCountry.toUpperCase();

    if ((sSelectedCountrytmp == 'USA') || (sSelectedCountrytmp == 'U.S.A.') || (sSelectedCountrytmp == 'UNITED STATES') || (sSelectedCountrytmp == 'US') || (sSelectedCountrytmp == 'U.S.') || (sSelectedCountrytmp == 'AMERICA')) {
      for (i = 0;(i < oElem.options.length); i++) {
        if (oElem.options[i].value == abbreviationForUS) {
          oElem.options[i].value = sSelectedCountry;
          oElem.options[i].innerText = sSelectedCountry;
        }
      }
    }

    else {
      var sNewOption = document.createElement("<option value='" + sSelectedCountry + "'>");

      oElem.options.add(sNewOption);
      sNewOption.innerText = sSelectedCountry;
    }
  }

}


function checkSelectedCountry(sCountry, tdStatesDD, tdProvincesDD, tdStatesTXT, sHiddenCountry, sHiddenState) {

  oElem = document.getElementById(sHiddenCountry);
  if (oElem != null)
    oElem.value = sCountry;

  oElem = document.getElementById(sHiddenState);
  if (oElem != null)
    oElem.value = '';

  if (tdStatesDD != null)
    displayDDStatesOrDDProvincesOrTxtStates(tdStatesDD, tdProvincesDD, tdStatesTXT, sHiddenState, sHiddenCountry);

}


function updateState(tdBillToStatesDD, tdBillToProvincesDD, tdBillToStatesTXT, sHiddenState, sNewStateId, sNewValue, bOpener) {
  var idStates, idProvinces, idStatesTxt, oElem, oElemNew;

  idStates = tdBillToStatesDD.replace("td", "dd");
  idProvinces = tdBillToProvincesDD.replace("td", "dd");
  idStatesTxt = tdBillToStatesTXT.replace("td", "TXT");

  if (sNewStateId != '') 
	sNewValue = (bOpener) ? opener.document.getElementById(sNewStateId).value : document.getElementById(sNewStateId).value;

  if (bOpener) {
    opener.document.getElementById(idStates).value = sNewValue;
    opener.document.getElementById(idProvinces).value = sNewValue;
    opener.document.getElementById(idStatesTxt).value = sNewValue;
    oElem = opener.document.getElementById(sHiddenState);
  }

  else {
    document.getElementById(idStates).value = sNewValue;
    document.getElementById(idProvinces).value = sNewValue;
    document.getElementById(idStatesTxt).value = sNewValue;
    oElem = document.getElementById(sHiddenState);
  }

  if (oElem != null)
    oElem.value = sNewValue;


}


function updateCountry(tdBillToCountriesDD, sHiddenCountry, sNewCountryId, tdStatesDD, tdProvincesDD, tdStatesTXT, sHiddenState, sNewCountry, bOpener) {
  var idCountries, oElem, oElemNew, abbreviationForUS;

  idCountries = tdBillToCountriesDD.replace("td", "dd");

  if (sNewCountryId != '')
    sNewCountry = (bOpener) ? opener.document.getElementById(sNewCountryId).value : document.getElementById(sNewCountryId).value;

  oElem = (bOpener) ? opener.document.getElementById(idCountries) : document.getElementById(idCountries);
  bCountryFound = false;

  if (sNewCountry == '') {
    abbreviationForUS = GetSystemAttribute('P21SystemAttribute', 'ValueForUSInCountryDropDown');
    if (abbreviationForUS == '') 
      abbreviationForUS = 'US';

    sNewCountry = abbreviationForUS;
  }


  for (i = 0;(i < oElem.options.length); i++) {
    if (oElem.options[i].value == sNewCountry)
      bCountryFound = true;
  }

  if (!bCountryFound) {

    sNewCountryTmp = sNewCountry.toUpperCase();

    if ((sNewCountryTmp == 'USA') || (sNewCountryTmp == 'U.S.A.') || (sNewCountryTmp == 'UNITED STATES') || (sNewCountryTmp == 'US') || (sNewCountryTmp == 'U.S.') || (sNewCountryTmp == 'AMERICA')) {
      for (i = 0;(i < oElem.options.length); i++) {
        sOptionCountry = oElem.options[i].value.toUpperCase();
        if ((sOptionCountry == 'USA') || (sOptionCountry == 'U.S.A.') || (sOptionCountry == 'UNITED STATES') || (sOptionCountry == 'US') || (sOptionCountry == 'U.S.') || (sOptionCountry == 'AMERICA')) {
          oElem.options[i].value = sNewCountry;
          oElem.options[i].innerText = sNewCountry;
        }
      }
    }

    else {
      var sNewOption = (bOpener) ? opener.document.createElement("<option value='" + sNewCountry + "'>") : document.createElement("<option value='" + sNewCountry + "'>");

      oElem.options.add(sNewOption);
      sNewOption.innerText = sNewCountry;
    }
      
  }

  oElem.value = sNewCountry;

  oElem = (bOpener) ? opener.document.getElementById(sHiddenCountry) : document.getElementById(sHiddenCountry);

  if (oElem != null)
    oElem.value = sNewCountry;

  displayDDStatesOrDDProvincesOrTxtStates(tdStatesDD, tdProvincesDD, tdStatesTXT, sHiddenState, sHiddenCountry, bOpener);
}

var origRemaining = '';
function getTotal(){
var currency;
var number;
if(origRemaining == ''){ 
currency = document.getElementById('cRemain').innerHTML;
origRemaining = currency;
}
else{
currency = origRemaining;
}
number = Number(currency.replace(/[^0-9\.]+/g,""));
iTotal = 0;
for(i=0;i<(0 + document.getElementById('hdnListCount').value);i++){
if(document.getElementById('txtShoppingListQuantity' + i) != null ){
iTotal += (Math.round((0 + document.getElementById('txtUnitPrice' + i).value) * (0 + document.getElementById('txtShoppingListQuantity' + i).value) * 100) / 100);
}
}
tot = Math.round(iTotal*Math.pow(10,2))/Math.pow(10,2);
document.getElementById('cRemain').innerHTML = '$' + AppendZeros1((number - tot), 2);
document.getElementById('cTotal').innerHTML = '$' + AppendZeros1(tot, 2);
}
function resetQty(){
for(i=0;i<(0 + document.getElementById('hdnListCount').value);i++){
if(document.getElementById('txtShoppingListQuantity' + i) != null ){
document.getElementById('txtShoppingListQuantity' + i).value = '0';
}
}
getTotal();
}

function compareIntegers(vNum1, vNum2) {
  var iNum1 = parseInt(vNum1);
  var iNum2 = parseInt(vNum2);

  if (iNum1 < iNum2) {
    return -1;
  } else if (iNum1 > iNum2) {
    return 1;
  } else {
    return 0;
  }
}

function convertEnterToTab() 
{       
	var intKey = window.Event ? event.which : event.keyCode;
	if(intKey == 13) 
	{         
		var oSource = window.event.srcElement ;
		if (oSource.type == "button" || oSource.type == "submit")
			return;

		event.keyCode = 9;
	}
}

function enableEnterToTab(frmName)
{
	var frm
	frm = document.forms[frmName];

	if (frm != null)
		frm.onkeydown = convertEnterToTab;
}


function useShipAddress(frmName,cssPrefix)
{
    var frm;
    frm = document.forms[frmName];
    if(frm.elements["txtBillToFirstName"].disabled == false)
    {
	    if(frm.elements["txtUseShipping"].checked == true)
	    {
		    frm.elements["txtBillToFirstName"].value = frm.elements["txtShipToFirstName"].value;
		    frm.elements["txtBillToLastName"].value = frm.elements["txtShipToLastName"].value;
		    frm.elements["txtBillToAddress1"].value = frm.elements["txtShipToAddress1"].value;
		    frm.elements["txtBillToAddress2"].value = frm.elements["txtShipToAddress2"].value;
		    frm.elements["txtBillToCity"].value = frm.elements["txtShipToCity"].value;
		    frm.elements["txtBillToZip"].value = frm.elements["txtShipToZip"].value;
		    updateState('tdBillToStatesDD','tdBillToProvincesDD', 'tdBillToStatesTXT',  cssPrefix + '_txtBillToState', cssPrefix + '_txtShipToState','','');
		    updateCountry('tdBillToCountriesDD', cssPrefix + '_txtBillToCountry', cssPrefix + '_txtShipToCountry', 'tdBillToStatesDD','tdBillToProvincesDD', 'tdBillToStatesTXT',cssPrefix + '_txtBillToState','','');
	    }
    }
}


var xmlHttp;
function AJAXCall(url)
{
	if (window.ActiveXObject) 
	{
   		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	} 
   	else if (window.XMLHttpRequest) 
	{
    		xmlHttp = new XMLHttpRequest();                
	}
   	xmlHttp.open("GET", url, false);
   	xmlHttp.send(null);
}

function GetFeatureAttribute(attributeName,featureName)
{
    return getAttributeInternal('N',attributeName,featureName,'N')
}

function GetSystemAttribute(attributeName,featureName)
{
    return getAttributeInternal('Y',attributeName,featureName,'N')
}

function GetSessionSetting(sessionVariable)
{
    return getAttributeInternal('N', sessionVariable, "", 'Y')
}

function getAttributeInternal(systemAttribute,attributeName,featureName,sessionSetting)
{
    var url = 'SystemFolders/p21customerpages/AJAXConfigHandler.aspx?systemAttribute=' + systemAttribute + '&attributeName=' + attributeName + '&featureName=' + featureName + '&sessionSetting=' + sessionSetting;
    // alert(url);
    AJAXCall(url)
    var ret = xmlHttp.responseXML.getElementsByTagName("AttributeValue")[0].firstChild.data;
    if (ret == 'blank')
    {
        ret = '';
    }
    return ret
}



