﻿

// "Macro" for document.getElementById
function $(e){
    return document.getElementById(e);
}

//Trim a javascript string
function trim(s) {
    return s.replace(/^\s+|\s+$/g, '');
}


//returns true if current browser is IE6 (should also return true for older versions of IE)
function IE6() {
	return (window.external && typeof window.XMLHttpRequest == "undefined");
}


//Encodes the string, correctly encodes the + sign
function encode(s) {
	s = escape(s);
	s = s.replace(/\+/g, "%2B");
	return s;
}


function reg() 
{
    //FF enter key handler
    if (!window.event) {
        return document.body.onkeypress = FFKeyHandler;
    }
}


//MJW 1/15/09 Not used
//function netscapeKeyPress(e)
//{
//	if (e.which==13)
//	{
//    fnTrapKD("",e); // disabled
//	}
//}


function FFKeyHandler(e) {
    if (e.keyCode == 13) {
        //var elem = document.activeElement;
        var elem = e.target;

        if (elem != null && elem.tagName == "TEXTAREA") {
            return true;
        }
        
        if (elem != null && elem.name) {
            switch (elem.name) {
			    case "txtSearchDept": //Change Ship to Page
				    __doPostBack('ibtSearchDept','');
				    return false;
			    case "txtSearchShipTo": //Change Ship to Page
				    __doPostBack('ibtSearchShipTo','');
				    return false;
                default:
                    return false;
            }
        } else {
            return false;
        }
    } else {
        return true;
    }
}


function fnTrapKD(btn, event) {
	if (event.keyCode == 13){
		doIT(btn, event);
	}
}


function doIT(btn, event) {
	document.Form1.enterkey.value=btn
	event.returnValue=false;
	event.cancel = true;
	if (btn.length !=0){
		document.Form1.submit();
	}
}


var usernameenterkeyevent
usernameenterkeyevent = false
var eventname 


function checkenterkey()
{
    if (!window.event) {
        return;
    }

	var KillIt = true;
	var e = window.event
	
	if (event.keyCode == 13){
		//alert(e.srcElement.name);
		switch (e.srcElement.name) {
			case "comment": //Purchase Page - Order Comment
			case "orderhistorydetailctl:approvecomment": //ApproveOrderDetails Page - Approver Comment
				//alert("do nothing");
				KillIt = false;
				break;
			case "ibtShipTo": //Change Ship To Page '>' button
				__doPostBack('ibtShipTo','');
				KillIt = true
				break;
			case "txtSearchDept": //Change Ship to Page
				__doPostBack('ibtSearchDept','');
				KillIt = true
				break;
			case "txtSearchShipTo": //Change Ship to Page
				__doPostBack('ibtSearchShipTo','');
				KillIt = true
				break;
			case "txtRefineSearch":
				__doPostBack('cmdRefineSearch','');
			case "txtDeliveryComments":
				KillIt = false;
				break;
			default:
				//alert("trap");
				KillIt = true;
		}
		
		if (KillIt){
			//alert("KillIt");
			fnTrapKD("",e);
		}
	}
}

//MJW 1/15/09 Not used
//function fnTrapKDforLogin(btn, event)
//{
//	var validate 
//    var targ;
//	if (event.target) targ = event.target;
//	else if (event.srcElement) targ = event.srcElement;
//	
//    eventname =targ.name
//	if (event.keyCode == 13)
//	{
//	    if (btn =='login') 
//	        validate = validatefieldswithoutfocus(loginfields)
//	    else
//	        validate = validatefieldswithoutfocus(forgetfields);
//		if (validate)   
//		   doIT(btn, event)
//		else {
//		   usernameenterkeyevent =true;
//		   <% If Request.Browser.Browser.ToUpper().IndexOf("IE") >= 0 %> 
//		   event.keyCode = 9;   
//		   <% end if%>       // change key down to tab event in order to keep window enter key function
//		}
//	}     
//}




//MJW 1/15/09 Not used
//function fnTrapKDFocus(btn,event)
//{   
//	if (!usernameenterkeyevent)  return ;
//	if (usernameenterkeyevent)
//	{
//		validatefieldswithfocus(loginfields,loginfields.length-1)
//	}
//	usernameenterkeyevent = false;
//}



//MJW 1/15/09 Not used
//function validatefieldswithfocus(fields,count)
//{
//	for (var i=0; i< count;i++)
//	{
//	eval("var otmp = document.Form1." + fields[i][0]);
//	if (otmp=="[object]" || otmp=="[object HTMLInputElement]")
//	{
//		if (otmp.value=="")
//		{
//		<% If Request.Browser.Browser.ToUpper().IndexOf("IE") >= 0 %> 
//			alert(fields[i][1])
//			otmp.focus()
//			return false
//		<%else%>
//			otmp.focus()
//		<% end if %>
//		return false
//		}
//		}
//	}
//	return true
//}


//MJW 1/15/09 Not used
//function validatefieldswithoutfocus(fields)
//{
//for (var i=0; i< fields.length;i++)
//	{
//	eval("var otmp = document.Form1." + fields[i][0]);
//	if (otmp=="[object]" || otmp=="[object HTMLInputElement]")
//	{
//       if (otmp.value=="")
//       {
//       return false
//       }
//	}
//	}
//	return true
//}


//MJW 1/15/09 Not used
////function for Netscape
//function validatefieldswithfocus(fields,count,texttype)
//{
//	var returnvalue
//    returnvalue =true
//	for (var i=0; i< count;i++)
//	{   
//		eval("var otmp = document.Form1." + fields[i][0]);
//		if (otmp=="[object]" || otmp=="[object HTMLInputElement]")
//		{
//			if (otmp.value=="")
//			{
//				alert(fields[i][1])
//				otmp.focus()
//				returnvalue = false
//				break;
//			}
//			else
//			{
//			    // check if password is blank or not . move cursor to password if password is blank
//				i++;
//				eval("var otmp = document.Form1." + fields[i][0]);
//				if (otmp=="[object]" || otmp=="[object HTMLInputElement]")
//				{
//					if (otmp.value=="")
//					{
//					 otmp.focus()
//					 returnvalue = false
//					 break;
//					}
//				}
//			}
//		}
//	}
//	return returnvalue
//}


function disabledenterkey()
{
	if (window.event.keyCode == 13)
	{  
	window.event.keyCode =0
	}
}


function clickAddtoCart(e, buttonid,thebox,thevalidator)
{ 
	var bt = document.getElementById(buttonid); 
	if (typeof bt == 'object')
	{ 
		if(navigator.appName.indexOf("Netscape")>(-1))
		{ 
			if (e.keyCode == 13)
			{
			validate = CheckQuantity1(thebox,thevalidator)
				if (validate) 
				{
					bt.click(); 
					return false;
				}
			} 
		} 
		if (navigator.appName.indexOf("Microsoft Internet Explorer")>(-1))
		{ 
			if (event.keyCode == 13)
			{ 
				validate = CheckQuantity1(thebox,thevalidator)
				if (validate)
				{
					bt.click(); 
					return false;
				}
				else
				{
					cancelevent()
					event.keyCode = 9;
				}
			} 
		} 
	} 
} 


//MJW 1/15/09 Not used
//function clickAddtoCartQuickOrder(e, buttonid,thebox)
//{
//	var bt = document.getElementById(buttonid); 
//	if (typeof bt == 'object')
//	{ 
//		if(navigator.appName.indexOf("Netscape")>(-1))
//		{ 
//			if (e.keyCode == 13)
//			{
//				bt.click(); 
//				return false;
//			} 
//		} 
//		if (navigator.appName.indexOf("Microsoft Internet Explorer")>(-1))
//		{ 
//			if (event.keyCode == 13)
//			{ 
//				cancelevent();				
//				bt.click(); 
//				return false; 
//			} 
//		} 
//	} 
//} 



//functions for checkout login page
var checkoutloginfields = [['txtUserName','Please enter your Username'],['txtPassword','Please enter your password']];
var forgetfields = [['yourpostcode','Please enter your postal code'],['txtEmail','Email address is required.']];
var eventname;

function clickCheckLogin(e, buttonid,type) { 
    var bt = document.getElementById(buttonid); 
    if (typeof bt == 'object') { 
	    if(navigator.appName.indexOf("Netscape")>(-1)) { 
		    if (e.keyCode == 13) {
			    if ( type=="checkoutlogin") 
				    validate = validatefields(checkoutloginfields);
			    else
				    validate = validatefields(forgetfields);

				if (validate) {
					bt.click(); 
					return false;
				}
		    } 
	    } 
	
	    if (navigator.appName.indexOf("Microsoft Internet Explorer")>(-1)) { 
		    if (event.keyCode == 13) { 
			    if ( type=="checkoutlogin") 
				    validate = validatefields(checkoutloginfields);
			    else
				    validate = validatefields(forgetfields);
					
			    if (validate) {
				    bt.click(); 
                    return false;
			    } else {
				    cancelevent()
				    event.keyCode = 9;
			    }
		    } 
	    } 
	} 
} 


function cancelevent() {   
	event.returnValue=false;
    event.cancel = true;
}


function validatefields(fields) {
	for (var i=0; i< fields.length;i++) {
	    var returnvalue;
	    returnvalue = true;
	
	    eval("var otmp = document.Form1." + fields[i][0]);
	    
	    if (otmp=="[object]" || otmp=="[object HTMLInputElement]") {
		    if (otmp.value=="") {
			    alert(fields[i][1]);
			    otmp.focus();
			    returnvalue =  false;
			    break;
		    } else if (eventname == fields[0][0]) {
			    eval("var otmp = document.Form1." + fields[i+1][0]);
			    if (otmp=="[object]" || otmp=="[object HTMLInputElement]") {
				    if (otmp.value=="") {
					    otmp.focus();
					    returnvalue =  false;
					    break;
				    }
			    }
		    }
	    }
	}
	return returnvalue;
}


var value;

//MJW 1/15/09 Not used
//function SetupProvinceCode() {
//    var countrycode;
//    var currcountrycode;
//    var statecode;
//    var description;
//    var dCountry;
//    var dState;
//    var index;
//    var lastindex;
//    var isempty = false;
//  
//    dState = document.Form1.Account1_dState;
//    dCountry =document.Form1.Account1_dCountry;

//    for (i=0;i<dCountry.length ;i++) {
//	    if (dCountry.options[i].selected) {
//		    countrycode=dCountry.options[i].value;
//		    break;
//	    }
//    }

//    do {
//        isempty=false;
//	    for (var i=0;i<dState.length;i++) {
//		    dState .options [i]=null;
//		    isempty=true;
//	    }
//    }
//    
//    
//    while(isempty)
//	
//var j =0 
//tOption= new Option("Select a Prov./State","")
//dState.options [j]=tOption
//j=j+1
//for(i=0;i<StateCodes.length -1 ;i++){
//	value = StateCodes[i]
//	currcountrycode =getcode()
//	if (currcountrycode == countrycode){
//		statecode =getcode()
//		description =getcode()
//		tOption= new Option(description,statecode)
//		dState.options [j]=tOption
//		j=j+1
//	}
//}
//dState.options[0].selected =true
//}


//MJW 1/15/09 Not used
//function getcode()
//{
//	var index;
//	var code;
//	index = value.indexOf(":");
//	if (index==-1)
//	{
//		code = value
//	}
//	else
//	{
//		code = value.substring(0,index);
//		value = value.substring(index+1);
//}
//return code
//}


//MJW 1/15/09 Not used
//function loginneeded()
//{
//	alert("<%=application(session("lang") & "_loginneededMSG")%>");
//	return false;
//}


function CheckQuantity1(theQty,theValidator) {
    var thistalue;
    var theText = document.getElementById(theQty); 
    var validator = document.getElementById(theValidator); 
    if (typeof theText == 'object') { 
	    thistalue = theText.value;
	    if (parseFloat(thistalue) == 0) { 
		    if (navigator.appName.indexOf("Microsoft Internet Explorer")>(-1))
			    validator.style.display ="";
		    else
			    alert("Quantity must be greater than 0");

		    theText.focus();
		    return false;
        }
	
	    if (!IsBlank(thistalue)) { 
	        if (navigator.appName.indexOf("Microsoft Internet Explorer")>(-1))
                validator.style.display ="";
	        else  
                alert("Quantity must be all numeric.");

	        theText.focus();
	        return false;
	    } else {  
		    theText.value=parseFloat(thistalue);
		    theText.focus();
		    return true;
	    }
	}
}

function CheckQuantity(theText) {
    var thistalue;
    thistalue =theText.value;

    if (parseFloat(thistalue) == 0) { 
	    alert("Quantity must be greater than 0");
	    theText.focus();
	    return false;
    }

    if (!IsNumeric(thistalue)) { 
	    alert("Quantity must be all numeric.");
	    theText.focus();
	    return false;
    } else {
        theText.value=parseFloat(thistalue);
        theText.focus();
	    return true;
    }
}


function IsBlank(thevalue) {
    //  check for valid numeric strings	
	var strValidChars = "0123456789";
	var strChar;
	var blnResult = true;

	if (thevalue.length == 0) return false;

	//  test strString consists of valid characters listed above
	for (i = 0; i < thevalue.length && blnResult == true; i++) {
		strChar = thevalue.charAt(i);
		if (strValidChars.indexOf(strChar) == -1) {
			blnResult = false;
		}
	}
	return blnResult;
}


function IsNumeric(strString) {
//  check for valid numeric strings	
	var strValidChars = "0123456789";
	var strChar;
	var blnResult = true;

	if (strString.length == 0) return false;

	//  test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++) {
	    strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1) {
			blnResult = false;
		}
	}
	return blnResult;
}

function ProductDetails(productid, categoryid, url){
    //Pass in the url from Purchase page so we are not in SSL
    if(typeof url == "undefined"){
        url = "";
    }

	var w = window.open(url + "ProductDetailsPop.aspx?prodid=" + productid,"ProductDetailsPop","toolbar=no,menubar=no,directories=no,scrollbars=yes,width=870,height=644,top=1,left=1, resizable=yes");
	w.focus();
}



function ViewXStamp(url){
	var w;
	w = window.open(url, "", "titlebar=no,toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes,height=400,width=416,left=1,top=1");
	w.focus();
}


function ViewPromoOffer(productid){
	var w = window.open("PopupHolder.aspx?TemplateID=3&prodid=" + productid,"PromoOffer","toolbar=no,menubar=no,directories=no,scrollbars=yes,width=760,height=300,top=1,left=1, resizable=yes");
	w.focus();
}


function ViewRoles(){
	var w = window.open("PopupHolder.aspx?TemplateID=4","Roles","toolbar=no,menubar=no,directories=no,scrollbars=yes,width=760,height=600,top=1,left=1, resizable=yes");
	w.focus();
}

function ViewSimilarItems(categoryID, searchProvider, categoryDescription){
    switch(searchProvider){
        case "BMI":
            this.location.href = "ProductList.aspx?similar=1&bcuse=1&browse=1&category=" + categoryID;
            break;
        case "UNITED":
            this.location.href = "UnitedSearch.aspx?similar=1&bcuse=1&browse=1&category=" + categoryID + "&categorydesc=" + categoryDescription;
            break;
        case "SPR":
            this.location.href = "SPRSearch1.aspx?similar=1&bcuse=1&browse=1&category=" + categoryID;
            break;
        default:
            this.location.href = "ProductList.aspx?similar=1&bcuse=1&browse=1&category=" + categoryID;
            break;   
    }
}

function ClearTextBox(TheBox, text) {
    if (TheBox.value ==text) 
    TheBox.value ="";
}


function InitTextBox(TheBox, text) {
    if (TheBox.value=="")
        TheBox.value = text ;
}


//Get the absolute X position of the element
function posX(e) {
	var x = 0;
	var c = 0;
	var currentStyle = e.currentStyle;
	do {
		x += e.offsetLeft;
		if (currentStyle) {
			c = parseInt(e.currentStyle.borderLeftWidth);
			if (!isNaN(c)) {
				x += c;
			}
		}
		e = e.offsetParent;
	} while (e);
	return x;
}

//Get the absolute Y position of the element
function posY(e) {
	var y = 0;
	var c = 0;
	var currentStyle = e.currentStyle;
	do {
		y += e.offsetTop;
		if (currentStyle) {
			c = parseInt(e.currentStyle.borderTopWidth);
			if (!isNaN(c)) {
				y += c;
			}
		}
		e = e.offsetParent;
	} while (e);
	return y;
}


function gbOn(e) {
	e.className = e.className.replace(/gbutton_off/gi, "gbutton_on");
}


function gbOff(e) {
	e.className = e.className.replace(/gbutton_on/gi, "gbutton_off");
}

//used for empty <a href=""></a>
function EmptyHref() {
}


function Breadcrumb(index) {
	document.getElementById("hdnBreadCrumbAction").value = "click|" + index;
	document.forms[0].submit();
}

function BreadcrumbRemove(index) {
	document.getElementById("hdnBreadCrumbAction").value = "remove|" + index;
	document.forms[0].submit();
}


function formatNumber (val, decimalPlaces, hasDollar) {

	var sign = "";
	var n;
	var i;
	var asc;

	val=val.toString();
	   
    //Remove commas
    //val = val.toString().replace(/,/g,'');
    
    //Remove dollar sign
	//val = val.toString().replace(/\$/g,'');

    //Check for negaitve number
	if (val.length>0) {
		//if(val.charAt(0) == "-"){
		if (val.indexOf('-')>=0 || val.indexOf('(')>=0 || val.indexOf(')')>=0) {
			sign = "-";
		}
	}

	//Remove everything except 0-9 and .
	n="";
	for (i=0; i<val.length; i++) {
		asc=val.charCodeAt(i);
		//01234567890 -$,
		if ((asc>=48 && asc<=57) || asc==46) {
			n+=val.substr(i,1);
		}
	}
	

    //Remove dashes - "negative signs"
    //n = val.toString().replace(/-/g,'');
	

	if (n.length>0) {
		if (decimalPlaces>0) {
			//format decimal
			n = round (n, decimalPlaces);
			for (var k = n.indexOf('.') - 3; k>0; k -= 3)
				n = n.substring(0, k) + ',' + n.substring(k);
		} else {
			//format no decimal
			for (var k = n.length - 3; k>0; k -= 3)
				n = n.substring(0, k) + ',' + n.substring(k);
		}
	}
	
	if (n.length>0)
		if (hasDollar==1)
			return "$" + sign + n;
		else
			return sign + n;
	else
		return "";

}
function round (n,d) {
	n = Math.round(n * 100) / 100;
	n = (n + 0.001) + '';
	return n.substring(0, n.indexOf('.') + d+1);
}




//////////////////////////////
//	General Item functions	//
//////////////////////////////

//returns all the item checkboxes regardless of the checked state
function getItemCheckboxes() {
	var checkboxes = new Array();

	var elems = document.getElementsByTagName("INPUT");
	for (var i=0; i<elems.length; i++) {
		if (elems[i].type == "checkbox") {
			if (elems[i].id.indexOf("chkItem_") >= 0) {
				checkboxes[checkboxes.length] = elems[i];
			}
		}
	}
	
	return checkboxes;
}

//returns an array of product ids for checked items
function getCheckedItems() {
	//get array of all checked DVP check boxes
	var checks = getItemCheckboxes();

	//create an array for the checked prod ids
	var prodIDs = new Array();
	
	//add the prodIDs for all checkboxes that are checked
	for (var i=0; i<checks.length; i++) {
		if (checks[i].checked) {
			prodIDs[prodIDs.length] = checks[i].id.replace(/chkItem_/gi, "");
		}
	}
	
	return prodIDs;
}

//Checks/unchecks the checkbox for each item.
function checkAllItems() {
	var check;
	var btn = $("cmdCheckAllTop");
	if (btn.src.toLowerCase().indexOf("btn_check_all_items.gif") >= 0 ) {
		check = true;
	} else {
		check = false;
	}
	
	//switch the image
	if (check) {
		btn.src = btn.src.replace(/btn_check_all_items.gif/gi, "btn_uncheck_all_items.gif");
	} else {
		btn.src = btn.src.replace(/btn_uncheck_all_items.gif/gi, "btn_check_all_items.gif");
	}
	$("cmdCheckAllBot").src = btn.src;

	var checkBoxes = getItemCheckboxes();
	for (var i=0; i<checkBoxes.length; i++) {
		checkBoxes[i].checked = check;
	}
	
	return false;
}

//OLD FORMAT
//hdnTrackedItems = prodid(5)sku(5)price(5)qty(5)comment|6|prodid(5)sku(5)price(5)qty(5)comment
//NEW FORMAT
//hdnTrackedItems = prodid(5)sku(5)qty(5)comment|6|prodid(5)sku(5)qty(5)comment

function TrackCheckedItems(obj){
//alert($("hdnTrackedItems").value);
        var prodID = obj.id.replace(/chkItem_/gi, "");
		var sku = escape($("hdnItemSku_" + prodID).value);
		//var price = escape($("hdnItemPrice_" + prodID).value);
	    var comment = $("txtItemComment_" + prodID).value;
	    var showInvalidQtyMsg = false;
	    
	    //get and validate the qty
	    var qty = parseInt($("txtItemQty_" + prodID).value);
	    if (isNaN(qty) || qty==0 || qty != $("txtItemQty_" + prodID).value.replace(/^\s+|\s+$/g, '')) {
	        qty = 1;
	        $("txtItemQty_" + prodID).value = qty;
	        showInvalidQtyMsg = true;
	    }
	    
    if (obj.checked){
        //Add to list
        if ($("hdnTrackedItems").value == ""){
            $("hdnTrackedItems").value = prodID + String.fromCharCode(5) + sku + String.fromCharCode(5) + qty + String.fromCharCode(5) + comment;
        }else{
            $("hdnTrackedItems").value = $("hdnTrackedItems").value + String.fromCharCode(6) + prodID + String.fromCharCode(5) + sku + String.fromCharCode(5) + qty + String.fromCharCode(5) + comment;
        }
//        //Add to list
//        if ($("hdnTrackedItems").value == ""){
//            $("hdnTrackedItems").value = prodID + String.fromCharCode(5) + sku + String.fromCharCode(5) + price + String.fromCharCode(5) + qty + String.fromCharCode(5) + comment;
//        }else{
//            $("hdnTrackedItems").value = $("hdnTrackedItems").value + String.fromCharCode(6) + prodID + String.fromCharCode(5) + sku + String.fromCharCode(5) + price + String.fromCharCode(5) + qty + String.fromCharCode(5) + comment;
//        }
    }else{
        //Remove from list      
        var trackedItems = "";
        var items = $("hdnTrackedItems").value.split(String.fromCharCode(6));
        for (var i=0; i<items.length; i++){
            var details = items[i].split(String.fromCharCode(5));           
            if (details[0] != prodID){
                if (trackedItems == ""){
                    trackedItems = items[i];
                }else{
                    trackedItems = trackedItems + String.fromCharCode(6) + items[i];
                }
            }
        }
        $("hdnTrackedItems").value = trackedItems;
    }
    
    ToggleUncheckTrackedItemsButton();
    
    if (showInvalidQtyMsg){
        alert("You entered an invalid quantity.  It was replaced with a value of 1.");
    }
//alert($("hdnTrackedItems").value);
}



//Checks/unchecks the checkbox for each item and track product_id/sku in hidden field
function CheckAllItemsAndTrack() {
	var check;
	var btn = $("cmdCheckAllTop");
	if (btn.src.toLowerCase().indexOf("btn_check_all_items.gif") >= 0 ) {
		check = true;
	} else {
		check = false;
	}
	
	//switch the image
	if (check) {
		btn.src = btn.src.replace(/btn_check_all_items.gif/gi, "btn_uncheck_all_items.gif");
	} else {
		btn.src = btn.src.replace(/btn_uncheck_all_items.gif/gi, "btn_check_all_items.gif");
	}
	$("cmdCheckAllBot").src = btn.src;

    
    var showInvalidQtyMsg = false;
    
	var checkBoxes = getItemCheckboxes();
	for (var i=0; i<checkBoxes.length; i++) {
	    var prodID = checkBoxes[i].id.replace(/chkItem_/gi, "")
		var sku = escape($("hdnItemSku_" + prodID).value);
		//var price = escape($("hdnItemPrice_" + prodID).value);
	    var comment = $("txtItemComment_" + prodID).value;
	    
	    //get and validate the qty
	    var qty = parseInt($("txtItemQty_" + prodID).value || qty != $("txtItemQty_" + prodID).value.replace(/^\s+|\s+$/g, ''));
	    if (isNaN(qty) || qty==0) {
		    qty = 1;
		    $("txtItemQty_" + prodID).value = 1;
		    showInvalidQtyMsg = true;
	    }
		
	    if (check){ //add to tracking collection 
	        if (!checkBoxes[i].checked){
	            if ($("hdnTrackedItems").value == ""){
	                $("hdnTrackedItems").value = prodID + String.fromCharCode(5) + sku + String.fromCharCode(5) + qty + String.fromCharCode(5) + comment;
	            }else{
	                $("hdnTrackedItems").value = $("hdnTrackedItems").value + String.fromCharCode(6) + prodID + String.fromCharCode(5) + sku + String.fromCharCode(5) + qty + String.fromCharCode(5) + comment;
	            }
		        checkBoxes[i].checked = check;
//	            if ($("hdnTrackedItems").value == ""){
//	                $("hdnTrackedItems").value = prodID + String.fromCharCode(5) + sku + String.fromCharCode(5) + price + String.fromCharCode(5) + qty + String.fromCharCode(5) + comment;
//	            }else{
//	                $("hdnTrackedItems").value = $("hdnTrackedItems").value + String.fromCharCode(6) + prodID + String.fromCharCode(5) + sku + String.fromCharCode(5) + price + String.fromCharCode(5) + qty + String.fromCharCode(5) + comment;
//	            }
//		        checkBoxes[i].checked = check;
		    }
	    }else{ //uncheck - remove from tracking collection
	        if (checkBoxes[i].checked){
	            var checkedItems = "";
	            var items = $("hdnTrackedItems").value.split(String.fromCharCode(6));
                for (var j=0; j<items.length; j++){
                    var details = items[j].split(String.fromCharCode(5));           
	                if (details[0] != prodID){
	                    if (checkedItems == ""){
	                        //checkedItems = details[0] + String.fromCharCode(5) + details[1] + String.fromCharCode(5) + details[2] + String.fromCharCode(5) + details[3] + String.fromCharCode(5) + details[4];
	                        checkedItems = items[j];
	                    }else{
	                        //checkedItems = checkedItems + String.fromCharCode(6) + details[0] + String.fromCharCode(5) + details[1] + String.fromCharCode(5) + details[2] + String.fromCharCode(5) + details[3] + String.fromCharCode(5) + details[4];
	                        checkedItems = checkedItems + String.fromCharCode(6) + items[j];
	                    }
	                }
	            }
	            $("hdnTrackedItems").value = checkedItems;
		        checkBoxes[i].checked = check;
		    }
	    }
	    
	}
	
	ToggleUncheckTrackedItemsButton();
	
	if (showInvalidQtyMsg){
        alert("You entered an invalid quantity.  It was replaced with a value of 1.");
    }
    
	
	return false;
}


function RecheckTrackedItems(){

    if ($("hdnTrackedItems") != null && $("hdnTrackedItems").value != ""){
        var allCheckedOnPage = true;
        var checkBoxes = getItemCheckboxes();
        var items = $("hdnTrackedItems").value.split(String.fromCharCode(6));
        for (var i=0; i<checkBoxes.length; i++){
            var checked = false;
	        for (var k=0; k<items.length; k++) {
	            var details = items[k].split(String.fromCharCode(5));
	            if (checkBoxes[i].id.replace(/chkItem_/gi, "") == details[0]){
		            checkBoxes[i].checked = true;
		            $("txtItemQty_" + details[0]).value = details[2];
                    $("txtItemComment_" + details[0]).value = details[3];
//		            $("txtItemQty_" + details[0]).value = details[3];
//                    $("txtItemComment_" + details[0]).value = details[4];
		            checked = true;
		            break;
		        }
	        }
            //See if all the items on the page are checked
	        if (!checked){
	            allCheckedOnPage = false;
	        }
	    }

	    //switch the image
	    if (allCheckedOnPage) {
	        var btn = $("cmdCheckAllTop");
		    btn.src = btn.src.replace(/btn_check_all_items.gif/gi, "btn_uncheck_all_items.gif");
		    $("cmdCheckAllBot").src = btn.src;
	    }
    }
    
    ToggleUncheckTrackedItemsButton();
}

//update the qunatity after the item has been checked
function UpdateTrackedQty(prodID){

    var chk = $("chkItem_" + prodID);
    if (chk.checked){
        var showInvalidQtyMsg = false;
        
	    var qty = parseInt($("txtItemQty_" + prodID).value);

	    if (isNaN(qty) || qty==0 || qty != $("txtItemQty_" + prodID).value.replace(/^\s+|\s+$/g, '')) {
	        qty = 1;
	        $("txtItemQty_" + prodID).value = qty;
		    showInvalidQtyMsg = true;
	    }
	    
	    //Replace the stored value with this one
	    var trackedItems = "";
	    var items = $("hdnTrackedItems").value.split(String.fromCharCode(6));

        for (var i=0; i<items.length; i++){

            var details = items[i].split(String.fromCharCode(5));
            if (details[0] == prodID){
                     
                //store the new quantity
                if (trackedItems == ""){
                    trackedItems = details[0] + String.fromCharCode(5) + details[1] + String.fromCharCode(5) + qty + String.fromCharCode(5) + details[3];
//                    trackedItems = details[0] + String.fromCharCode(5) + details[1] + String.fromCharCode(5) + details[2] + String.fromCharCode(5) + qty + String.fromCharCode(5) + details[4];
                }else{
                    trackedItems = trackedItems + String.fromCharCode(6) + details[0] + String.fromCharCode(5) + details[1] + String.fromCharCode(5) + qty + String.fromCharCode(5) + details[3];
//                    trackedItems = trackedItems + String.fromCharCode(6) + details[0] + String.fromCharCode(5) + details[1] + String.fromCharCode(5) + details[2] + String.fromCharCode(5) + qty + String.fromCharCode(5) + details[4];
                }
            }else{
                if (trackedItems == ""){
                    trackedItems = items[i];
                }else{
                    trackedItems = trackedItems + String.fromCharCode(6) + items[i];
                }
            }
        }
        $("hdnTrackedItems").value = trackedItems;
        
        if (showInvalidQtyMsg){
            alert("You entered an invalid quantity.  It was replaced with a value of 1.");
        }
    }
}


//update the comment after the item has been checked
function UpdateTrackedComment(prodID){
    var chk = $("chkItem_" + prodID);
    
    if (chk.checked){
	    var comment = $("txtItemComment_" + prodID).value;

	    //Replace the stored value with this one
	    var trackedItems = "";
	    var items = $("hdnTrackedItems").value.split(String.fromCharCode(6));
        for (var i=0; i<items.length; i++){
            var details = items[i].split(String.fromCharCode(5));           
            if (details[0] == prodID){
                //store the new quantity
                if (trackedItems == ""){
                    trackedItems = details[0] + String.fromCharCode(5) + details[1] + String.fromCharCode(5) + details[2] + String.fromCharCode(5) + comment;
//                    trackedItems = details[0] + String.fromCharCode(5) + details[1] + String.fromCharCode(5) + details[2] + String.fromCharCode(5) + details[3] + String.fromCharCode(5) + comment;
                }else{
                    trackedItems = trackedItems + String.fromCharCode(6) + details[0] + String.fromCharCode(5) + details[1] + String.fromCharCode(5) + details[2] + String.fromCharCode(5) + comment;
//                    trackedItems = trackedItems + String.fromCharCode(6) + details[0] + String.fromCharCode(5) + details[1] + String.fromCharCode(5) + details[2] + String.fromCharCode(5) + details[3] + String.fromCharCode(5) + comment;
                }
            }else{
                if (trackedItems == ""){
                    trackedItems = items[i];
                }else{
                    trackedItems = trackedItems + String.fromCharCode(6) + items[i];
                }
            }
        }
        $("hdnTrackedItems").value = trackedItems;
    }
}


//show the compare page
function compareTrackedCheckedItems() {
	//get array of prod ids that are checked
	//var prodIDs = getCheckedItems();  

	var items = $("hdnTrackedItems").value.split(String.fromCharCode(6));

	//there should now be 2 or 3 values in the items array
	if (items.length != 2 && items.length != 3) {
		alert("Please check 2 or 3 items to compare.");
	} else {
		//show the compare page
		var url = "compare.aspx";
		url += "?bcuse=1";
		
		var details = items[0].split(String.fromCharCode(5))
		url += "&prodID1=" + escape(details[0]);
		url += "&sku1=" + escape(details[1]);
		
		var details = items[1].split(String.fromCharCode(5))
		url += "&prodID2=" + escape(details[0]);
		url += "&sku2=" + escape(details[1]);
		
		if (items.length == 3) {
		    var details = items[2].split(String.fromCharCode(5))
			url += "&prodID3=" + escape(details[0]);
			url += "&sku3=" + escape(details[1]);
		} else {
			url += "&prodID3=&sku3=";
		}

		self.location = url;
	}
	
	return false;
}


function UncheckTrackedItems(){
   
    //Uncheck all items on the page
	var checkBoxes = getItemCheckboxes();
	for (var i=0; i<checkBoxes.length; i++) {
	    checkBoxes[i].checked = false;
	}
	
	//Clear the Tracked Items
	$("hdnTrackedItems").value = ""

    //Set the image for Check/Uncheck button
    var btn = $("cmdCheckAllTop");
    btn.src = btn.src.replace(/btn_uncheck_all_items.gif/gi, "btn_check_all_items.gif");
    $("cmdCheckAllBot").src = btn.src;

    //Disable Uncheck All Across All Pages
    ToggleUncheckTrackedItemsButton();
    
    return false;
}

function ToggleUncheckTrackedItemsButton(){
    if ($("hdnTrackedItems") != null) {
        if ($("hdnTrackedItems").value == ""){    
            $("cmdUncheckTrackedItemsTop").style.visibility = "hidden";
            $("cmdUncheckTrackedItemsBot").style.visibility = "hidden";
        }else{
            $("cmdUncheckTrackedItemsTop").style.visibility = "visible";
            $("cmdUncheckTrackedItemsBot").style.visibility = "visible";
        }
    }
}

//show the compare page
function compareCheckedItems() {
	//get array of prod ids that are checked
	var prodIDs = getCheckedItems();
	
	//there should now be 2 or 3 values in the items array
	if (prodIDs.length != 2 && prodIDs.length != 3) {
		alert("Please check 2 or 3 items to compare.");
	} else {
		//show the compare page
		var url = "compare.aspx";
		url += "?bcuse=1";
		
		url += "&prodID1=" + escape(prodIDs[0]);
		url += "&sku1=" + escape($("hdnItemSku_" + prodIDs[0]).value);
		
		url += "&prodID2=" + escape(prodIDs[1]);
		url += "&sku2=" + escape($("hdnItemSku_" + prodIDs[1]).value);
		
		if (prodIDs.length == 3) {
			url += "&prodID3=" + escape(prodIDs[2]);
			url += "&sku3=" + escape($("hdnItemSku_" + prodIDs[2]).value);
		} else {
			url += "&prodID3=&sku3=";
		}

		self.location = url;

	}
	
	return false;
}


function addToCart(prodID, useBreadcrumb, checkAccessories) {
	//useBreadcrumb & checkAccessories are optional

	//get the line comment and price
	//var price = $("hdnItemPrice_" + prodID).value;
	var comment = $("txtItemComment_" + prodID).value;
	
	//get the uom, it may not exist
	var uom="";
	if ($("hdnItemUOM_" + prodID) != null) {
	    uom = $("hdnItemUOM_" + prodID).value;
	}
	
	//get and validate the qty
	var qty = parseInt($("txtItemQty_" + prodID).value);
	if (isNaN(qty) || qty==0) {
		alert("Please enter a valid quantity.");
		return false;
	}

	//build the URL:
	//   QS PARAMS:item=prodID(CHAR5)qty(CHAR5)comment
	//NOTE:  addCheckedToCart uses this same format but items are separated with CHAR6
	var s = prodID;
	s += String.fromCharCode(5);
	s += qty;
	s += String.fromCharCode(5);
//	s += price;
//	s += String.fromCharCode(5);
	s += comment;
	
	//add uom if it exists
	if (uom != "") {
	    s += String.fromCharCode(5);
	    s += uom;
	}

	//ajax call to add it to the cart
	var url = "ajax/addToCart.aspx";
	url += "?items=" + encode(s);
	if (useBreadcrumb==true) {
		url += "&useBreadcrumb=1";
	}
	if (checkAccessories==true) {
		//check hidden field to see if accessories have already been purchased, this field may not exist.
		var hdnPurchaseFlag = $("hdnItemAccPurchased_" + prodID);
		if (hdnPurchaseFlag != null && hdnPurchaseFlag.value == "1") {
			checkAccessories = false;
		}
	
	
		if (checkAccessories==true) {
			url += "&checkAccessories=1";
		}
	}
	url = RandomizeUrl(url);
	var response = ajax.gets(url);
	
	//check for error
	if (response.toLowerCase() == "error") {
		self.location = "errorpage.aspx";
		return;
	} else {
		//Update the cart display
		var s = response.split("|");		
		
		//update the n Item(s) display
		$("SearchBar1_CartSummaryCTL_Label1").innerHTML = s[0];
		
		//update total cart price
		$("SearchBar1_CartSummaryCTL_ltotal").innerHTML =  formatNumber(s[1], 2, true);
		
		//item (3) may have the SHOWACCESSORIES
		if (s[3]=="SHOWACCESSORIES") {
			//show the accessories popup, s[2] is redirect url
			showAccessories(prodID, $("hdnItemSku_" + prodID).value, s[2]);
		} else if (s[2]!="") {
			//redirect
			self.location = s[2];
		}
	}
}

//MJW - no longer used
//Adds all checked items to the cart.  Assumes breadcrumb is used.
//function addCheckedItemsToCart() {
//	//get array of prod ids that are checked
//	var prodIDs = getCheckedItems();
//	
//	//verfiy items are checked
//	if (prodIDs.length == 0) {
//		alert("Please check one or more items to add to the cart.");
//		return false;
//	}

//	//build the URL:
//	//   QS PARAMS:item=prodID(CHAR5)qty(CHAR5)price(CHAR5)comment(CHAR6)next items...
//	//NOTE:  addCheckedToCart uses this same format but only for a single item
//	var s = "";
//	for (var i=0; i<prodIDs.length; i++) {
//		//get the line comment and price
//		var price = $("hdnItemPrice_" + prodIDs[i]).value;
//		var comment = $("txtItemComment_" + prodIDs[i]).value;
//	
//		//get and validate the qty
//		var qty = parseInt($("txtItemQty_" + prodIDs[i]).value);
//		if (isNaN(qty) || qty==0) {
//			alert("Please enter a valid quantity.");
//			return false;
//		}

//		if (s != "") {
//			s += String.fromCharCode(6);
//		}
//		s += prodIDs[i];
//		s += String.fromCharCode(5);
//		s += qty;
//		s += String.fromCharCode(5);
////		s += price;
////		s += String.fromCharCode(5);
//		s += comment;
//	}

//	//ajax call to add it to the cart
//	var url = "ajax/addToCart.aspx";
//	url += "?items=" + encode(s);
//	url += "&useBreadcrumb=1";
//	
//	url = RandomizeUrl(url);
//	var response = ajax.gets(url);


//	//check for error
//	if (response.toLowerCase() == "error") {
//		self.location = "errorpage.aspx";
//		return;
//	} else {
//		//Update the cart display
//		var s = response.split("|");		
//		
//		//update the n Item(s) display
//		$("SearchBar1_CartSummaryCTL_Label1").innerHTML = s[0];
//		
//		//update total cart price
//		$("SearchBar1_CartSummaryCTL_ltotal").innerHTML = s[1];
//		
//		//redirect
//		if (s[2]!="") {
//			self.location = s[2];
//		}
//	}

//	return false;
//}

//Adds all checked items to the cart.  Assumes breadcrumb is used.
function addTrackedItemsToCart() {
	//get array of prod ids that are checked
	var items = $("hdnTrackedItems").value.split(String.fromCharCode(6));

	//verfiy items are checked
	if ($("hdnTrackedItems").value == "") {
		alert("Please check one or more items to add to the cart.");
		return false;
	}

	//build the URL:
	//   QS PARAMS:item=prodID(CHAR5)qty(CHAR5)comment(CHAR6)next items...
	//NOTE:  addCheckedToCart uses this same format but only for a single item
	var s = "";
	for (var i=0; i<items.length; i++) {
		//get the line comment and price
		var details = items[i].split(String.fromCharCode(5))

		if (s != "") {
			s += String.fromCharCode(6);
		}

		s += details[0]; //prodid
		s += String.fromCharCode(5);
		s += details[2];//quantity
		s += String.fromCharCode(5);
		s += details[3];//comment

//		s += details[0]; //prodid
//		s += String.fromCharCode(5);
//		s += details[3];//quantity
//		s += String.fromCharCode(5);
////		s += details[2]; //price
////		s += String.fromCharCode(5);
//		s += details[4];//comment

	}

	//ajax call to add it to the cart
	var url = "ajax/addToCart.aspx";
	url += "?items=" + encode(s);
	url += "&useBreadcrumb=1";
	
	url = RandomizeUrl(url);
	var response = ajax.gets(url);


	//check for error
	if (response.toLowerCase() == "error") {
		self.location = "errorpage.aspx";
		return;
	} else {
		//Update the cart display
		var s = response.split("|");		
		
		//update the n Item(s) display
		$("SearchBar1_CartSummaryCTL_Label1").innerHTML = s[0];
		
		//update total cart price
		$("SearchBar1_CartSummaryCTL_ltotal").innerHTML = s[1];
		
		//redirect
		if (s[2]!="") {
			self.location = s[2];
		}
	}
	
	return false;
}



//////////////////////////////
//	Product List Control	//
//////////////////////////////

function ProdListCtl_Page(page) {
	document.getElementById("hdnProdListCtlAction").value = "Page|" + page;
	document.forms[0].submit();
}
function ProdListCtl_Sort(location) {
	var cbo = document.getElementById("cboProdListSort" + location);
	var value = cbo[cbo.selectedIndex].value;
	document.getElementById("hdnProdListCtlAction").value = "Sort|" + value;
	document.forms[0].submit();
}
function ProdListCtl_ItemsPerPage(location) {
	var cbo = document.getElementById("cboProdListItemsPerPage" + location);
	var value = cbo[cbo.selectedIndex].value;
	document.getElementById("hdnProdListCtlAction").value = "ItemsPerPage|" + value;
	document.forms[0].submit();
}
	


//////////////////////
//	Search Page		//
//////////////////////

//current parametric span under Features that is open, null if none
var mParametricSpan = null;
var mParametricOverlay = null;		//div that is created and overlayed over selected span to make it appear selected.
function refineSearch() {
	document.getElementById("hdnProdListAction").value = "Search";
	document.forms[0].submit();
}
	
function Critia(span, value) {
	//we are in an <a> tag below, need to get the group name
	//	<div class="critGroup">
	//		<div class="critGroupTitle"></div>
	//		<div class="critItems">
	//			item
	//			item
	//			...
	//			<div class="moreHidden">
	//				hidden items...
	//			</div>
	//		</div>
	//		<div class="moreLink">
	//			<span>More . . .</span>
	//		</div>
	//	</div>

	//get the group title
	var div = span.parentNode.parentNode.parentNode;
	var groupTitle = "";
	if (div.className.indexOf("critGroup") == "-1") {
		//we're under divMoreHidden, move up one more
		div = div.parentNode;
	}
	groupTitle = div.firstChild.firstChild.nodeValue;
	var s = "Criteria";
	s += escape(String.fromCharCode(6));
	s += escape(groupTitle); 
	s += escape(String.fromCharCode(6));
	s += escape(span.innerHTML); //link name
	if (value!=null) {
		s += escape(String.fromCharCode(6));
		s += escape(value);
	}

	document.getElementById("hdnProdListAction").value = s;
	document.forms[0].submit();
}

//show/hide the more criteria items
function CriteriaMore(title) {
	var divItems = $("divCritItems_" + title);
	var divHdn = $("divCritHdnMore_" + title);
	var lnkMore = $("spnCritMore_" + title);

	//close any open parametric popup
	closeParametrics();
	
	var expand = false;
	
	//determine if we are expanding or collapsing
	if (lnkMore.innerHTML.toLowerCase().indexOf("more")>=0) {
		expand = true;
	}
	
	//show/hide
	if (expand) {
		lnkMore.innerHTML = "Collapse";
		if (divHdn.childNodes.length > 5) {
			//more than 5 hidden items, set height and show scroll bars.
			divItems.className += " critExpanded";
			divItems.onscroll = function() {closeParametrics();}
		}
		divHdn.style.display = "block";
		
	} else {
		lnkMore.innerHTML = "More . . .";
		divHdn.style.display = "none";
		divItems.className = divItems.className.replace(/ critExpanded/gi, "");
		divItems.onScroll = null;
	}
}


//posts the selected parametric 
function PMetricSelect(span, id, featureID) {
    //featureID will be not null only for united searches

	if (mParametricSpan == null) {
		//shouldn't happen
		return;
	}
	
	var s;

	var ar = null;
	if (id != null) {
		ar = ParametricArrayItem(id);
	} else {
		ar = ParametricArrayItem(mParametricSpan.innerHTML);
	}

	if (ar[1]==1) {
		s = "Parametric";
	} else {
		//recyclable, woman owned, etc.
		s = "Feature";
	}
	s += String.fromCharCode(6);
	s += ar[0];
	s += String.fromCharCode(6);
	s += span.innerHTML;
	
	if (id != null) {
		s += String.fromCharCode(6);
		s += mParametricSpan.innerHTML;
	}
	
	if (featureID != null) {
	    //united
		s += String.fromCharCode(6);
		s += featureID;
	}
	
	s = encode(s);
	document.getElementById("hdnProdListAction").value = s;
	document.forms[0].submit();
}
	
//show/hide the parametric values
function PMetric(span, id) {
	//just return if it's the current item
	if (mParametricSpan != null && mParametricSpan.innerHTML == span.innerHTML) {
		return;
	}
	
	//close any existing parametric popup
	closeParametrics();

	//save the current span, highlight it
	mParametricSpan = span;



	
	//build the window
	var popup = document.createElement("TABLE");
	popup.className = "parametricPopup";
	popup.id = "tblParametricsPopup";
	
	var tbody = document.createElement("TBODY");
	popup.appendChild(tbody);

	var tr;
	var td;
	var img;
	
	//top row
	tr = document.createElement("TR");
	tr.className = "top";
	tbody.appendChild(tr);
	
	td = document.createElement("TD");
	td.className = "left";
	tr.appendChild(td);
	
	td = document.createElement("TD");
	td.className = "center";
	td.align="right";
	td.innerHTML = "<img src='images/para_x.gif' onclick='closeParametrics();'>"
	tr.appendChild(td);
	

	td = document.createElement("TD");
	td.className = "right";
	tr.appendChild(td);
	
	//middle row
	tr = document.createElement("TR");
	tr.className = "middle";
	tbody.appendChild(tr);
	
	td = document.createElement("TD");
	td.className = "left";
	tr.appendChild(td);
	
	var tdContent = document.createElement("TD");
	tdContent.className = "center";
	//td.innerHTML = "<div class='loading'><img src='images/popup_hourglass.gif'><span>Loading . . .</span></div>";	
	tr.appendChild(tdContent);

	td = document.createElement("TD");
	td.className = "right";
	tr.appendChild(td);
	
	//bottom row
	tr = document.createElement("TR");
	tr.className = "bottom";
	tbody.appendChild(tr);
	
	td = document.createElement("TD");
	td.className = "left";
	tr.appendChild(td);
	
	td = document.createElement("TD");
	td.className = "center";
	tr.appendChild(td);

	td = document.createElement("TD");
	td.className = "right";
	tr.appendChild(td);
	
	//add it to the page
	document.body.appendChild(popup);


	//coords of the viewable area of the browser
	var winT = document.body.scrollTop;
	var winL = document.body.scrollLeft;
	var winR;
	var winB;
	if (window.innerWidth) {
		//FF
		winR = winL + document.documentElement.clientWidth;
		winB = winT + window.innerHeight;
	} else {
		//IE
		winR = winL + document.body.clientWidth;
		winB = winT + document.body.clientHeight;
	}
	var winH = winB - winT;
	var winW = winR - winL;


	//calculate the position of the features span that opened the popup
	var spanT = posY(mParametricSpan.parentNode);
	var spanL = posX(mParametricSpan.parentNode);
	var spanH = mParametricSpan.parentNode.offsetHeight;
	var spanW = mParametricSpan.parentNode.offsetWidth;
	
	//adjust for the scroll position 
	e = mParametricSpan;
	while (e!= null) {
		if (e.className.indexOf("critItems") >= 0) {
			spanT -= e.scrollTop;
			e = null;
			break;
		}
		e = e.parentNode;
	}

	//create a div to simulate the span is selected
	mParametricOverlay = document.createElement("DIV");
	mParametricOverlay.className = "pmetricSelected"
	mParametricOverlay.style.left   = spanL + "px";
	mParametricOverlay.style.top    = spanT + "px";
	mParametricOverlay.style.width  = spanW + "px";	
	mParametricOverlay.style.height = (spanH-1) + "px";
	mParametricOverlay.innerHTML = mParametricSpan.parentNode.innerHTML;
	document.body.appendChild(mParametricOverlay);
	

	//add the content, increase # of columns until height fits on screen
	var columns = 0;
	var vMar = 40;	//margin (extra space above and below popup)
	do {
		tdContent.innerHTML = "";
		columns++;
		var valTable = writeParametricValues(id, columns);
		tdContent.appendChild(valTable);
		
		//set the max column widths in the table
		var maxColWidth = parseInt(660 / columns);
		var cols = valTable.getElementsByTagName("TD");
		for (var i=0; i<cols.length; i++) {
			if (cols[i].offsetWidth > maxColWidth) {
				cols[i].style.width = maxColWidth;
			}
		}
		
	}while(winH - vMar < popup.offsetHeight && columns<5)	//restrict total # of columns


	//calculate the position
	var popT = posY(mParametricSpan.parentNode);
	e = mParametricSpan;
	while (e!= null) {
		if (e.className.indexOf("critItems") >= 0) {
			popT -= e.scrollTop;
			e = null;
			break;
		}
		e = e.parentNode;
	}
	var popL = spanL;
	
	if (mParametricOverlay.currentStyle) {
		popL += mParametricOverlay.offsetWidth;
		popL--;
	} else {
		popL += parseInt(document.defaultView.getComputedStyle(mParametricOverlay, null).getPropertyValue("width"));
		popL += parseInt(document.defaultView.getComputedStyle(mParametricOverlay, null).getPropertyValue("border-left-width"));
		popL += parseInt(document.defaultView.getComputedStyle(mParametricOverlay, null).getPropertyValue("padding-left"));
		popL += parseInt(document.defaultView.getComputedStyle(mParametricOverlay, null).getPropertyValue("padding-right"));
		popL--;
	}
	
	
	//adjust vertical position to keep it on screen
	var popH = popup.offsetHeight;
	while (popT + popH > winB - 20) {
		popT --;
	}
	if (popT < winT + 10) {
		popT = winT + 10;
	}
	
	//now adjust the vertical position to make sure it's not above or below the selected span (this can happen if the selected span is partially visible);
	//also, insure it's not next to the rounded corner.
	if (popT > spanT - 7) {
		popT = spanT - 7;
	}
	
	if (spanT + spanH + 7 > popT + popH) {
		popT = spanT + spanH + 7 - popH;
	}
	
	//hide any dropdowns
	if (IE6()) {
		var cbos = document.getElementsByTagName("SELECT");
		for (var i=0; i<cbos.length; i++) {
			cbos[i].style.visibility = "hidden";
		}
	}


	//position the div & show it
	mParametricOverlay.style.visibility = "visible";
	popup.style.top = popT + "px";
	popup.style.left = popL + "px";
	popup.style.visibility = "visible";

}


function writeParametricValues(id, columns) {
	//returns a table with the specified # of columns containing the parametric values

	//find the item in the parametrics array
	var ar = null;
	if (id != null) {
		ar = ParametricArrayItem(id);
	} else {
		ar = ParametricArrayItem(mParametricSpan.innerHTML);
	}
	
	//set flag indicating it's a united search
	var united = false;
	try {
	    //mSearchType may not be defined
	    if (mSearchType == 'united') {
	        united = true;
	    }
	} catch(e){}
	
	//the values in ar begin with elem 2 and are value-count-value-count...
	//NOTE: united searches are value-count-featureID-value-count-featureID...
	//put these in new arrays
	var inc = 2;
	if (united) {
	    inc = 3;
	}
	var values = new Array();
	var counts = new Array();
    var featureIds = new Array();
	
	for (var i=2; i<ar.length; i+=inc) {
		values[values.length] = ar[i];
		var s = ar[i+1].toString();
		if (s.length > 3) {
		    //format count if > 1000
			counts[counts.length] = s.substring(0, s.length-3) + "," + s.substring(s.length-3, s.length);
		} else {
		    //no formatting <= 999
			counts[counts.length] = s;
		}
		
		if (united) {
		    featureIds[featureIds.length] = ar[i+2];
		}
	}

	//create the table
	var table = document.createElement("TABLE");
	var tbody = document.createElement("TBODY");
	table.appendChild(tbody);
	
	var tr = document.createElement("TR");
	tbody.appendChild(tr);
	
	var tds = new Array();
	for (var i=0; i<columns; i++) {
		var td = document.createElement("TD");
		if (i>0) {
			td.className = "additional";
		}
		tr.appendChild(td);
		tds[tds.length] = td;
	}

	//add the parametric values
	var rowCount = parseInt(values.length / columns);
	if (values.length % columns > 0) {
		rowCount ++;
	}

	for (var r=0; r<rowCount; r++) {
		for (var c=0; c<columns; c++) {
			var i = r + c*rowCount;
			
			var div = document.createElement("DIV");
			tds[c].appendChild(div);

			if (i < values.length) {
			    if (united) {
					div.innerHTML = "<span onclick='PMetricSelect(this, " + id + ", " + featureIds[i] + ");'>" + values[i] + "</span> (" + counts[i] + ")";
			    } else if (id != null) {
					div.innerHTML = "<span onclick='PMetricSelect(this, " + id + ");'>" + values[i] + "</span> (" + counts[i] + ")";
				} else {
					div.innerHTML = "<span onclick='PMetricSelect(this);'>" + values[i] + "</span> (" + counts[i] + ")";
				}
			}			
		}			
	}
	
	//return the table
	return table;
}


function closeParametrics() {
	//close the current popup div if it's open
	var popup = document.getElementById("tblParametricsPopup");
	if (popup != null) {
		document.body.removeChild(popup);
	}

	if (mParametricOverlay != null) {
		document.body.removeChild(mParametricOverlay);
		mParametricOverlay = null;
	}
	
	//show any dropdowns
	if (IE6()) {
		var cbos = document.getElementsByTagName("SELECT");
		for (var i=0; i<cbos.length; i++) {
			cbos[i].style.visibility = "visible";
		}
	}
} 

//returns the sub-array for the parametric item matching the current name
function ParametricArrayItem(name) {
	for (var i=0; i<mParametrics.length; i++) {
		if (mParametrics[i][0] == name) {
			return mParametrics[i];
		}
	}
	return null;
}

//////////////
//	Popup	//
//////////////

var mPopupResizeFunction = null;
var mPopupCloseRedirectUrl = null;
var mPopupCloseFunction = null;


//	openPopup - opens an embedded popup window, calls the url to get the content.
//
//		resizeFunction - (optional) if specified, the function will be called if
//									the popup is larger than the browser window.  
//		redirectUrl - (optional)	if specified, the page will redirect when the 
//									popup is closed
//		dontRedirectFromCloseButton - (optional) if true, redirectUlr is ignored when
//												 close button is pressed.
//      closeFunction               - (optional) specifies a javascript function to call when
//                                    the popup is closed.
//      popupHTML - (optional, if specified this content is added to the popup, the url is ignored)
function openPopup(url, resizeFunction, redirectUrl, dontRedirectFromCloseButton, closeFunction, popupHTML) {
    //exit if already shown
	if ($("tblEmbeddedPopup") != null) {
	    return;
	}
    

	disablePage();
	
	//save the resize function
	if (resizeFunction == null || resizeFunction == "") {
		mPopupResizeFunction = null;
	} else {
		mPopupResizeFunction = resizeFunction;
	}
	
	if (redirectUrl == null || redirectUrl == "") {
		mPopupCloseRedirectUrl = null;
	} else {
		mPopupCloseRedirectUrl = redirectUrl;
	}
	
	if (closeFunction != null && closeFunction != "" && mPopupCloseRedirectUrl==null) {
	    mPopupCloseFunction = closeFunction;
	}
	
	
	
	//build the window
	var table = document.createElement("TABLE");
	table.className = "embedded_popup";
	table.id = "tblEmbeddedPopup";
	
	var tbody = document.createElement("TBODY");
	table.appendChild(tbody);

	var tr;
	var td;
	var img;
	
	//top row
	tr = document.createElement("TR");
	tr.className = "top";
	tbody.appendChild(tr);
	
	td = document.createElement("TD");
	td.className = "left";
	tr.appendChild(td);
	
	td = document.createElement("TD");
	td.className = "center";
	td.align="right";
	
	if (dontRedirectFromCloseButton != null && dontRedirectFromCloseButton == true) {
		td.innerHTML = "<img src='images/popup_close.gif' onclick='closePopup(true);'>"
	} else {
		td.innerHTML = "<img src='images/popup_close.gif' onclick='closePopup();'>"
	}
	tr.appendChild(td);
	

	td = document.createElement("TD");
	td.className = "right";
	tr.appendChild(td);
	

	//middle row
	tr = document.createElement("TR");
	tr.className = "middle";
	tbody.appendChild(tr);
	
	td = document.createElement("TD");
	td.className = "left";
	tr.appendChild(td);
	
	td = document.createElement("TD");
	td.className = "center";
/*
	if (popupHTML != null && popupHTML != "") {
	    td.innerHTML = popupHTML;
	} else {
    	td.innerHTML = "<div class='loading'><img src='images/popup_hourglass.gif'><span>Loading . . .</span></div>";	
    }
*/    
	td.innerHTML = "<div class='loading'><img src='images/popup_hourglass.gif'><span>Loading . . .</span></div>";	
	tr.appendChild(td);

	td = document.createElement("TD");
	td.className = "right";
	tr.appendChild(td);
	
	//bottom row
	tr = document.createElement("TR");
	tr.className = "bottom";
	tbody.appendChild(tr);
	
	td = document.createElement("TD");
	td.className = "left";
	tr.appendChild(td);
	
	td = document.createElement("TD");
	td.className = "center";
	tr.appendChild(td);

	td = document.createElement("TD");
	td.className = "right";
	tr.appendChild(td);
	
	//add it to the page
	document.body.appendChild(table);

	//coords of the viewable area of the browser
	var winT = document.body.scrollTop;
	var winL = document.body.scrollLeft;
	var winR;
	var winB;
	if (window.innerWidth) {
		//FF
		winR = winL + document.documentElement.clientWidth;
		winB = winT + window.innerHeight;
	} else {
		//IE
		winR = winL + document.body.clientWidth;
		winB = winT + document.body.clientHeight;
	}
	var winH = winB - winT;
	var winW = winR - winL;
	
	
	//center it
	table.style.left = (winW/2 - table.offsetWidth/2) + winL;
	table.style.top = (winH/2 - table.offsetHeight/2) + winT;


    //show the embedded contetn rather than making the ajax call (used by QuickItem)
	if (popupHTML != null && popupHTML != "") {
	    showPopupCallback(popupHTML);
    }

	//show it	
	table.style.visibility = "visible";	
	
	//make the ajax call if the popupHTML does not contain the content
	if (popupHTML == null || popupHTML == "") {
	    url = RandomizeUrl(url);
	    ajax.get(url, showPopupCallback)
    }
}


function closePopup(dontRedirect) {
	//dontRedirect is optional.
	
	if (mPopupCloseFunction != null) {
		var popup = $("tblEmbeddedPopup");
		if (popup != null) {
			document.body.removeChild(popup);
		}
	
		//remove the disabler
		closeDisabler();

        //call the close function
	    eval (mPopupCloseFunction);
	} else if (mPopupCloseRedirectUrl == null || dontRedirect == true) {
		//get the popup and remove it
		var popup = $("tblEmbeddedPopup");
		if (popup != null) {
			document.body.removeChild(popup);
		}
	
		//remove the disabler
		closeDisabler();
	} else {
		//don't need to close, just redirect
		self.location = mPopupCloseRedirectUrl;
	}
}


function closeDisabler() {
	//remove disabler
	var disabler = $("divPageDisabler");
	if (disabler != null) {
		document.body.removeChild(disabler);
	}

	//show all dropdown boxes
	var e = document.getElementsByTagName("SELECT");
	for (var i=0; i<e.length; i++) {
		e[i].style.visibility = "visible";
	}
	
	//hide all checkboxes
	e = document.getElementsByTagName("INPUT");
	for (var i=0; i<e.length; i++) {
		if (e[i].type =="checkbox") {
			e[i].style.visibility = "visible";
		}
	}
	
}

function disablePage() {
	//add the page disabler, this may already be in some pages
	var disabler = $("divPageDisabler");
	if (disabler == null) {
		disabler = document.createElement("DIV");
		disabler.id = "divPageDisabler";
		disabler.className = "pagedisabler";
		
		//document.body.appendChild(disabler);
		document.body.insertBefore(disabler, document.body.firstChild);
	}
	
	//calculate the total window height (not just the viewport)
	var scrollH;
	var windowH;

	if (window.innerHeight && window.scrollMaxY) {	
		scrollH = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ 
		scrollH = document.body.scrollHeight;
	} else { 
		scrollH = document.body.offsetHeight;
	}
	

	if (self.innerHeight) {
		windowH = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { 
		windowH = document.documentElement.clientHeight;
	} else if (document.body) { 
		windowH = document.body.clientHeight;
	}	
	
	if (scrollH < windowH) {
		disabler.style.height = windowH;
	} else {
		disabler.style.height = scrollH;
	}
	
	//show it
	disabler.style.display = "block";
	
	//hide all dropdown boxes
	var e= document.getElementsByTagName("SELECT");
	for (var i=0; i<e.length; i++) {
		e[i].style.visibility = "hidden";
	}
	
	//hide all checkboxes
	e = document.getElementsByTagName("INPUT");
	for (var i=0; i<e.length; i++) {
		if (e[i].type =="checkbox") {
			e[i].style.visibility = "hidden";
		}
	}
}


//ajax callback
function showPopupCallback(response) {
	//check for error
	if (response.toLowerCase() == "error") {
		self.location = "errorpage.aspx";
		return;
	}


	//get the popup
	var popup = $("tblEmbeddedPopup");
	
	//exit if null
	if (popup == null) {
		closeDisabler();
		return;
	}
	
	//hide the popup
	popup.style.visibility = "hidden";
	
	//get the content td
	var tds = popup.getElementsByTagName("TD");
	
	//add the response to the content
	tds[4].innerHTML = response;

	//coords of the viewable area of the browser
	var winT = document.body.scrollTop;
	var winL = document.body.scrollLeft;
	var winR;
	var winB;
	if (window.innerWidth) {
		//FF
		winR = winL + document.documentElement.clientWidth;
		winB = winT + window.innerHeight;
	} else {
		//IE
		winR = winL + document.body.clientWidth;
		winB = winT + document.body.clientHeight;
	}
	var winH = winB - winT;
	var winW = winR - winL;
	
	//call the resize funtion if it's specified and popup is too big
	if (mPopupResizeFunction != null) {
		var vMar = 20;	//margin (extra space above and below popup)
		var popH = popup.offsetHeight;
		if (winH - vMar < popH) {
			//it's too big
			var delta = popH - winH + vMar;
			
			//call resize function
			eval(mPopupResizeFunction + "(" + delta + ")");
			
			//resize the main popup
			popH -= delta;
			popup.style.height = popH + "px";
		}
	}

	

	//center it
	popup.style.left = (winW/2 - popup.offsetWidth/2) + winL;
	popup.style.top = (winH/2 - popup.offsetHeight/2) + winT;

	//show it	
	popup.style.visibility = "visible";	
}



//////////////////////////////////
//	larger/alternate images		//
//////////////////////////////////
function showLargerImage(prodID) {
	openPopup("ajax/largerImage.aspx?prodID=" + prodID);
}

function showAdditionalImages(prodID) {
	openPopup("ajax/additionalImages.aspx?prodID=" + prodID);
}

function showTour(url) {
	window.open(url, 'bmitour', "width=800,height=600,toolbar=0,resizable=yes");
}

function showCardPrint(url) {
	var w = window.open(url, 'bmicardprint', "width=550,height=350,toolbar=0,resizable=yes");
	w.focus();
}

//////////////////
//	favorites	//
//////////////////
function showFavorites(prodID, sku, exclude_group_id) {
	//exclude_group_id can be null, if not the group will not be shown.
	openPopup("ajax/favorites.aspx?prodID=" + encode(prodID) + "&sku=" + encode(sku));
}

function addToFavorites(prodID, sku, groupID) {
	//ajax call to save item to fav list
	var qty = $("txtFavPop_" + groupID).value;
	
	//validate the qty
	qty = parseInt(qty);
	if (isNaN(qty)) {
		alert("Please enter a valid quantity.");
		return;
	}
	
	closePopup();
	openPopup("ajax/favorites.aspx?prodID=" + encode(prodID) + "&sku=" + encode(sku) + "&groupID=" + groupID + "&qty=" + qty + "&save=1");
}

//////////////////////
//	accessories		//
//////////////////////
function showAccessories(prodID, sku, redirectUrl, dontRedirectFromCloseButton) {
	//redirectUrl is optional, if specified the page will be redirected when the popup closes.
	//dontRedirectFromCloseButton is also optional, if true redirectUrl is ignored if the close button is pressed.
	var url = "ajax/accessories.aspx?prodID=" + encode(prodID) + "&sku=" + encode(sku);
	if (redirectUrl!=null && redirectUrl!="") {
		openPopup(url, "resizeAccessories", redirectUrl, dontRedirectFromCloseButton);
	} else {
		openPopup(url, "resizeAccessories");
	}
}

function resizeAccessories(delta) {
	//need to resize scrolling area and add scroll bars
	var scroll = $("AccessoryPop_divAccessoryList");
	scroll.style.height = (scroll.offsetHeight - delta) + "px";
	scroll.style.overflowY = "scroll";				
}

function getAccessoryIds() {
	return $("AccessoryPop_hdnAccessoryProductIds").value.split('|');
}


function checkAllAccessories(img) {
	//checks/unchecks all the accessories
	
	var check;
	if (img.src.toLowerCase().indexOf("btn_check_all_items.gif") >= 0 ) {
		check = true;
	} else {
		check = false;
	}
	
	//switch the image
	if (check) {
		img.src = img.src.replace(/btn_check_all_items.gif/gi, "btn_uncheck_all_items.gif");
	} else {
		img.src = img.src.replace(/btn_uncheck_all_items.gif/gi, "btn_check_all_items.gif");
	}
	
	//get the array of product ids
	var ids = getAccessoryIds();

	//walk thru the ids and check/uncheck each box
	for (var i=0; i<ids.length; i++) {
		$("AccessoryPop_chkAcc_" + ids[i]).checked = check;
	}	
}


	
function addAccessoriesToCart() {
	//add all checked accessories to the cart
	
	//prod id(CHAR5)qty(CHAR6)prod id...

	//get the ids
	var ids = getAccessoryIds();

	//variable for qs data
	var s = "";
	
	for (var i=0; i<ids.length; i++) {
		if ($("AccessoryPop_chkAcc_" + ids[i]).checked) {
			//item is checked

			//validate the quantity

			var qty = parseInt($("AccessoryPop_txtAccID_" + ids[i]).value);
			if (isNaN(qty) || qty==0) {
				alert("Please enter a valid quantity for all checked accessories.");
				return;
			}

			if (s!="") {
				s += String.fromCharCode(6);
			}
			s += ids[i];
			s += String.fromCharCode(5);
			s += qty;
//			s += String.fromCharCode(5);
//			s += $("AccessoryPop_hdnAccPrice_" + ids[i]).value;
		}
	}
	
	if (s=="") {
		alert("Please select one or more accessories.");
	} else {
		//get the parent product id
		var parentProdID = $("AccessoryPop_hdnParentProductID").value;
	
		//Update hidden field used to track if accessories have been purchased, this field may not exist
		var hdnPurchaseFlag = $("hdnItemAccPurchased_" + parentProdID);
		if (hdnPurchaseFlag != null) {
			hdnPurchaseFlag.value = "1";
		}
	
		
		//save the items, no response from the server here.
		var url = "ajax/accessories.aspx?prodID=" + parentProdID + "&sku=" + $("AccessoryPop_hdnParentSku").value + "&addtocart=1&items=" + encode(s);
        url = RandomizeUrl(url);
		var response = ajax.gets(url);

		if (response.toLowerCase() == "error") {
			self.location = "errorpage.aspx";
			return;
		}

		//response - parent product id|total # items in cart|total cart price|# of accessories in the cart for this item
		var s = response.split("|");

		//update the n Item(s) display
		$("SearchBar1_CartSummaryCTL_Label1").innerHTML = s[1];
		
		//update total cart price
		$("SearchBar1_CartSummaryCTL_ltotal").innerHTML = s[2];
		
		//update # in cart on accessory link (may not exist)
		var span = $("spnAccessoryNumberInCart_" + s[0]);
		if (span != null) {
			span.innerHTML = "(" + s[3] + " in cart)";
		}

		closePopup();
	}
}

function RandomizeUrl(url) {
    //randomizes the url by adding a random number to the end, this prevents cache pages from being use during ajax calls
    if (url.indexOf("?") == -1) {
        url += "?";
    } else {
        url += "&";
    }
    url += "nocache=" + new Date().getTime() + "-" + Math.floor(Math.random()*1000);
    return url;
}

//////////////////////
//	    returns     //
//////////////////////
function showReturnRequest(redirectUrl) {
	var url = "ajax/returnRequest.aspx";
	openPopup(url, "", "CustomerOrderHistory.aspx", false);
}


//////////////////////////////////////
//      Quick Item Functions        //
//////////////////////////////////////

var mQIPopup = false;       //=true when popup is called

function QI_getIndex(elem) {
    //returns the index from the id of a QI field.
    //txtQI_1_price, index=1, field="price"
    if (elem.id.indexOf("_") >= 0) {
        var s = elem.id.split("_");
        if (s.length == 3) {
            if (s[0]=="txtQI") {
                return parseInt(s[1]);
            }
        }
    }
    
    //not valid
    return null;
}

function QI_getField(elem) {
    //returns the index from the id of a QI field.
    //txtQI_1_price, index=1, field="price"

    if (elem.id.indexOf("_") >= 0) {
        var s = elem.id.split("_");
        if (s.length == 3) {
            if (s[0]=="txtQI") {
                return s[2];
            }
        }
    }
    
    //not valid
    return null;
}

function QI_Blur(elem) {
    //get the index and field for this elem
    var index = QI_getIndex(elem);
    var field = QI_getField(elem);

    //sku - call ajax if sku != "" and it's changed
    if (field == "sku") {
        var sku = trim($(elem.id).value);

        //if sku is not empty and it has changed from the last valid sku, call the ajax
        if (mQIPopup == false && sku != "" && sku != $("hdnQI_" + index + "_lastValidSku").value) {
            //clear everything except sku
            QI_ClearFields(index);
            
            //show loading in the description
            $("spnQI_" + index + "_desc").innerHTML = "Loading . . .";
            
            var url = "ajax/quickitem.aspx?sku=" + encode(sku) + "&index=" + index + "&price=" + $("hdnQI_ShowPrice").value + "&attind=" + $("hdnQI_ShowAttributeIndicator").value;
            url = RandomizeUrl(url);

            mQIPopup = true;
            ajax.get(url, QI_Callback);
        } else if (sku == "") {
            //clear other fields if no sku
            QI_ClearFields(index);
        }
    }
    
    //qty, if it's a valid item it must be a #
    if (field == "qty") {
        //validate the qty
        var sku = trim($("txtQI_" + index + "_sku").value);
        var lastValidSku = trim($("hdnQI_" + index + "_lastValidSku").value);
        if (sku != "" && sku == lastValidSku) {
            var qty = trim(elem.value);
            if (isNaN(parseInt(qty))) {
                elem.value = "1";
            } else {
                //insure it's an int
                var x = parseInt(qty);
                if (x < 0) {
                    elem.value = "1";
                } else {
                    //if decimal was entered this will replace with an int
                    elem.value = x; 
                }
            }
        }
        
        //calc total
        QI_Total();
        
        
//        //if no line comments, this field adds the new row
//        if ($("hdnQI_ShowLineComments").value!="True") {
//            if (!QI_LastRowEmpty()) {
//                QI_AddRow();
//            }
//        }
    }
    
//    //line comment, add new line if required
//    if (field == "comment") {
//        if (!QI_LastRowEmpty()) {
//            QI_AddRow();
//        }
//    }
    
}


function QI_ClearFields(index) {
    //clears all fields except for the sku
    
    $("hdnQI_" + index + "_productID").value = "";
    $("hdnQI_" + index + "_lastValidSku").value = "";
    $("hdnQI_" + index + "_price").value = "";
    $("txtQI_" + index + "_qty").value = "";
    $("spnQI_" + index + "_desc").innerHTML = "";
    
    if ($("hdnQI_ShowPrice").value == "True") {
        $("spnQI_" + index + "_price").innerHTML = "";
    }
    
    if ($("hdnQI_ShowLineComments").value=="True") {
        $("txtQI_" + index + "_comment").value = "";
    }
    
    //total
    QI_Total();
}

function QI_Callback(response) {
    //ajax call back for quick item
    
    //split the response, r[0] will have the response type.
    var r = response.split(String.fromCharCode(6));
    
    //check for error
    if (r[0] == "ERROR") {
	    self.location = "errorpage.aspx";
    }
    
    //get result and index (control #)
    //result = status(chr6)index  (if MATCH OR PARTIAL_MATCH (chr6) + more data)
    //      status = ERROR, MAX_RESULTS_EXCEEDED, MATCH, NO_MATCH, PARTIAL_MATCH
    var result = r[0];
    var index = r[1];
    
    //make sure the row still exists, exit if not
    if ($("trQI_" + index) == null) {
        return;
    }
    
    //process the result
    if (result == "MAX_RESULTS_EXCEEDED") {
        //r[2] contains max results allowed
        $("spnQI_" + index + "_desc").innerHTML = "More than " + r[2] + " items were found for \"" + $("txtQI_" + index + "_sku").value + "\", please enter a more specific item number.";
        $("txtQI_" + index + "_sku").focus();
        $("txtQI_" + index + "_sku").select();
        //clear the popup open flag
        mQIPopup = false;
    } else if (result == "MATCH") {
        //returned single item, populate the fields
        //r[2] = product_id (chr5) item_alias (chr5) uom (chr5) price (chr5) formatted_price (chr5) contract_item (chr5) description
        var s = r[2].split(String.fromCharCode(5));
        
        $("hdnQI_" + index + "_productID").value = s[0];            //product id
        $("txtQI_" + index + "_sku").value = s[1];                  //item #
        $("hdnQI_" + index + "_lastValidSku").value = s[1];         //last valid item #
        $("hdnQI_" + index + "_price").value = s[3];                //price (hidden)
        $("txtQI_" + index + "_qty").value = 1;                     //qty
        $("spnQI_" + index + "_desc").innerHTML = s[6];
        
        //price
        if ($("hdnQI_ShowPrice").value == "True") {
            var p = "$" + s[4]; //price
            if (s[2] != "") {   //uom
                p += "/" + s[2];
            }
            if (s[5] != "") {   //contract item
                p += "<br><span>";
                p += s[5] + "</span>";
            }
            $("spnQI_" + index + "_price").innerHTML = p;
        }
        
        //calc total
        QI_Total();

        //set focus to qty field
        $("txtQI_" + index + "_qty").focus();
        $("txtQI_" + index + "_qty").select();

        //add a new row if needed
        if (!QI_LastRowEmpty()) {
            QI_AddRow();
        }
        //clear the popup open flag
        mQIPopup = false;
    } else if (result == "NO_MATCH") {
        $("spnQI_" + index + "_desc").innerHTML = "No Products Found for item \"" + $("txtQI_" + index + "_sku").value + "\".";
        $("txtQI_" + index + "_sku").focus();
        $("txtQI_" + index + "_sku").select();
        //clear the popup open flag
        mQIPopup = false;
    } else if (result == "PARTIAL_MATCH") {
        //r[2] = html for popup
        $("spnQI_" + index + "_desc").innerHTML = "";   //clear the loading message
        openPopup(null, "QI_PopupResize", null, null, "QI_PopupClose(" + index + ")", r[2]);
    }        
}

function QI_PopupResize(delta) {
	//need to resize scrolling area and add scroll bars
	var scroll = $("QuickItemPop_divItemList");
	scroll.style.height = (scroll.offsetHeight - delta) + "px";
	scroll.style.overflowY = "scroll";		
}

function QI_PopupClose(index) {
    //quick item popup closed without a selection, return focus to sku
    $("txtQI_" + index + "_sku").focus();
    $("txtQI_" + index + "_sku").select();
    //clear the popup open flag
    mQIPopup = false;
}

function QI_PopupSelect(elem) {
    //elem is the img Select button.
    
    var index = null;   //the quick item control index to populate with the item selected from the popup
    var productID = null;
    var sku = null;
    var price = null;
    var priceString = null;
    var contractItem = null;
    var desc = null;
    

    //get the index
    index = $("QIPop_index").value;

    //move up to <div class="right">
    var div = elem;
    while (!(elem.tagName == "DIV" && elem.className != null && elem.className == "right")) {
        elem = elem.parentNode;
    }
    
    //get the product_id and price
    var nl = elem.getElementsByTagName("INPUT");
    for (var i=0; i<nl.length; i++) {
        if (nl[i].type == "hidden" && nl[i].name != null && nl[i].name == "QIPop_hdnQIProdID") {
            productID = nl[i].value;
        } 
        if (nl[i].type == "hidden" && nl[i].name != null && nl[i].name == "QIPop_hdnQIPrice") {
            price = nl[i].value;
        } 
    }
    
    //get the sku
    var nl = elem.getElementsByTagName("TD");
    for (var i=0; i<nl.length; i++) {
        if ( (nl[i].className != null || nl[i].className != "") && nl[i].className == "sku") {
            sku = nl[i].innerHTML;
            break;
        } 
    }
    
    //get the price string
    var nl = elem.getElementsByTagName("DIV");
    for (var i=0; i<nl.length; i++) {
        if ( (nl[i].className != null || nl[i].className != "") && nl[i].className == "price") {
            priceString = nl[i].innerHTML;
            break;
        } 
    }
    
    //get the contract item text
    contractItem = "";
    var nl = elem.getElementsByTagName("DIV");
    for (var i=0; i<nl.length; i++) {
        if ( (nl[i].className != null || nl[i].className != "") && nl[i].className == "contract_item") {
            contractItem = nl[i].innerHTML;
            break;
        } 
    }
    
    //get the description
    var nl = elem.getElementsByTagName("DIV");
    for (var i=0; i<nl.length; i++) {
        if ( (nl[i].className != null || nl[i].className != "") && nl[i].className == "short_description") {
            desc = nl[i].innerHTML;
            break;
        } 
    }
    

// Debug values . . .
//    var s = "index = " + index + "\n" +
//            "productID = " + productID + "\n" +
//            "sku = " + sku + "\n" +
//            "price = " + price + "\n" +
//            "priceString = " + priceString + "\n" +
//            "contractItem = " + contractItem + "\n" +
//            "desc = " + desc;
//    alert(s);

    //close popup
    closePopup(true);

    //populate the quick item fields
    $("hdnQI_" + index + "_productID").value = productID;           //product id
    $("txtQI_" + index + "_sku").value = sku;                       //item #
    $("hdnQI_" + index + "_lastValidSku").value = sku;              //last valid item #
    $("hdnQI_" + index + "_price").value = price;                   //price (hidden)
    $("txtQI_" + index + "_qty").value = 1;                         //qty
    $("spnQI_" + index + "_desc").innerHTML = desc;
    
    //price string
    if ($("hdnQI_ShowPrice").value == "True") {
        var p = priceString;
        if (contractItem != null && contractItem != "") {
            p += "<br><span>" + contractItem + "</span>";
        }
        $("spnQI_" + index + "_price").innerHTML = p;
    }
    
    //total
    QI_Total();

    //set focus to qty
    $("txtQI_" + index + "_qty").focus();
    $("txtQI_" + index + "_qty").select();

    //add a new row if needed
    if (!QI_LastRowEmpty()) {
        QI_AddRow();
    }
    
    //clear the popup open flag
    mQIPopup = false;
    
}//QI_PopupSelect

function QI_LastIndex() {
    //returns the control index of the last row

    //get the last used index
    var nl = document.getElementsByTagName("INPUT");
    var index = 0;
    for (var i=0; i<nl.length; i++) {
        var curIndex = QI_getIndex(nl[i]);
        var curField = QI_getField(nl[i]);
        
        if (curIndex != null && curField != null && curField == "sku") {
            if (curIndex > index) {
                index = curIndex;
            }
        }
    }//for (var i=0; i<nl.length; i++) {
    
    return index;
}

function QI_LastRowEmpty() {
    //returns true if the last row does not have a sku
    var e = $("txtQI_" + QI_LastIndex() + "_sku");
    
    if (e.value == null || trim(e.value) == "") {
        return true;
    } else {
        return false;
    }
}

function QI_AddRow() {
    //Adds a new row of controls to the quick item control
    
    
    //save the last index
    var priorLastIndex = QI_LastIndex();
    
    //add one to create the next index
    var index = priorLastIndex + 1;
    
    var tbody = $("tblQuickItem").getElementsByTagName("TBODY")[0];
    var tr;
    var td;
    var e;
    
    //control row
    tr = document.createElement("TR");
    tr.id = "trQI_" + index;
    
    //sku column
    td = document.createElement("TD");
    td.className = "sku";
    tr.appendChild(td);
    
    e = document.createElement("INPUT");
    e.type = "text";
    e.id = "txtQI_" + index + "_sku";
    e.name = "txtQI_" + index + "_sku";
    e.className = "solid";
    e.maxLength = "20";
    e.onblur = function(){QI_Blur(this);}
    td.appendChild(e);

    e = document.createElement("INPUT");
    e.type = "hidden";
    e.id = "hdnQI_" + index + "_productID";
    e.name = "hdnQI_" + index + "_productID";
    td.appendChild(e);

    e = document.createElement("INPUT");
    e.type = "hidden";
    e.id = "hdnQI_" + index + "_lastValidSku";
    td.appendChild(e);
    
    e = document.createElement("INPUT");
    e.type = "hidden";
    e.id = "hdnQI_" + index + "_price";
    e.name = "hdnQI_" + index + "_price";
    td.appendChild(e);
    
    //price
    if ($("hdnQI_ShowPrice").value == "True") {
        td = document.createElement("TD");
        td.className = "price";
        tr.appendChild(td);
        
        e = document.createElement("SPAN");
        e.id = "spnQI_" + index + "_price";
        td.appendChild(e);
    }
        
    //qty
    td = document.createElement("TD");
    td.className = "qty";
    tr.appendChild(td);

    e = document.createElement("INPUT");
    e.type = "text";
    e.id = "txtQI_" + index + "_qty";
    e.name = "txtQI_" + index + "_qty";
    e.onblur = function(){QI_Blur(this);}
    e.className = "solid";
    td.appendChild(e);

    //comment
    if ($("hdnQI_ShowLineComments").value=="True") {
        td = document.createElement("TD");
        td.className = "comment";
        tr.appendChild(td);

        e = document.createElement("INPUT");
        e.type = "text";
        e.id = "txtQI_" + index + "_comment";
        e.name = "txtQI_" + index + "_comment";
        e.onblur = function(){QI_Blur(this);}
        e.className = "solid";
        td.appendChild(e);
    }
    
    //delete
    td = document.createElement("TD");
    td.className = "delete";
    td.id = "tdQI_" + index + "_delete";
    tr.appendChild(td);
    
    //add the control row
    tbody.appendChild(tr);    
    
    //description row
    tr = document.createElement("TR");
    tr.id = "trQI_" + index + "_desc";
    tr.className = "desc";
    
    //description columns
    td = document.createElement("TD");
    td.className = "desc";
    td.style.width =  $("hdnQI_DescWidth").value + "px";
    td.colSpan = $("hdnQI_DescCols").value;
    tr.appendChild(td);
    
    e = document.createElement("SPAN");
    e.id = "spnQI_" + index + "_desc";
    td.appendChild(e);
    
    //blank column (placeholder for delete)
    td = document.createElement("TD");
    tr.appendChild(td);
    
    //add the control row
    tbody.appendChild(tr);    
    
//    //set focus to new sku field
//    $("txtQI_" + index + "_sku").focus();
//    $("txtQI_" + index + "_sku").focus();
    
    //add delete button to prior row
    e = document.createElement("IMG");
    e.src = "images/buttons/btn_x.gif";
    e.onclick = function(){QI_Delete(priorLastIndex);}
    $("tdQI_" + priorLastIndex + "_delete").appendChild(e);
    
    //insure new line is visible
    //get the element to show
    var scrollElem = $("trQI_" + index + "_desc");
  
    //y position that is to be visible
    var y = posY(scrollElem);
    y += scrollElem.offsetHeight;
    y += 40;    //adds enought to keep the submit or add to cart button visible
    
    //calc the viewable area
	var winT = document.body.scrollTop;
	var winB;
	if (window.innerWidth) {
		//FF
		winB = winT + window.innerHeight;
	} else {
		//IE
		winB = winT + document.body.clientHeight;
	}
    //scroll if y is off screen
    if (y > winB) {
        document.body.scrollTop += y - winB;
    }
}//function QI_AddRow() {


function QI_Delete(index) {
    var sku = trim($("txtQI_" + index + "_sku").value);
    var msg;
    if (sku != "") {
        msg = "Delete \"" + sku + "\"?";
    } else {
        msg = "Delete this item?";
    }
    
    if (confirm(msg)) {
        var tbody = $("tblQuickItem").getElementsByTagName("TBODY")[0];
        var e = $("trQI_" + index + "_desc");
        tbody.removeChild(e);
        var e = $("trQI_" + index);
        tbody.removeChild(e);
        
        //total
        QI_Total();
    }
}

function QI_Total() {
    //only used on quickorder page
    
    //QI_Total_Top and QI_Total_Bottom only exist on quick order page
    if ($("QI_Total_Bottom") == null) {
        return;
    }
    
    //get all the hidden fields, look for the price field
    var total = 0;
    var elems = $("tblQuickItem").getElementsByTagName("INPUT");
    
    for (var i=0; i<elems.length; i++) {
        var e = elems[i];
        
        if (e.type=="hidden" && e.id!=null && e.id.indexOf("_")>=0) {
        var s = e.id.split("_");
        if (s.length == 3) {
            if (s[0]=="hdnQI" && s[2]=="price") {
                var price = e.value;
                if (price=="" || isNaN(price)) {
                    price = 0;
                }
                var qty = $("txtQI_" + s[1] + "_qty").value;
                if (qty=="" || isNaN(qty)) {
                    qty = 0;
                }
                
                total += (qty*price);

            }
        }
        }//if (e.type=="hidden" && e.id!=null) {
    }//for (var i=0; i<elems.length; i++) {
    
    $("QI_Total_Top").innerHTML = formatNumber(total, 2, 1);
    $("QI_Total_Bottom").innerHTML = formatNumber(total, 2, 1);
    

    
}

//////////////////
//      UOM     //
//////////////////
function UOM_show(product_id, displayElemID, hdnUomElemID) {
    //displayElemID is ID of html element, hiddenElemID and hdnUOMElemID are ids of hidden fields for the price and uom
    var url = "ajax/uom.aspx?productID=" + encode(product_id);
    url += "&displayElemID=" + encode(displayElemID);
    url += "&hdnUomElemID=" + encode(hdnUomElemID);
    
    url = RandomizeUrl(url);
    openPopup(url);
}

//function UOM_show(product_id, displayElemID, hdnPriceElemID, hdnUomElemID) {
//    //displayElemID is ID of html element, hiddenElemID and hdnUOMElemID are ids of hidden fields for the price and uom
//    var url = "ajax/uom.aspx?productID=" + encode(product_id);
//    url += "&displayElemID=" + encode(displayElemID);
//    url += "&hdnPriceElemID=" + encode(hdnPriceElemID);
//    url += "&hdnUomElemID=" + encode(hdnUomElemID);
//    
//    url = RandomizeUrl(url);
//    openPopup(url);
//}


function UOM_select(price, uom, displayElemID, hdnUomElemID) {
    //update the display value
    var s = formatNumber (price, 2, 1);
    s += "/" + uom;
    $(displayElemID).innerHTML = s;
    
    //update the hidden values
    $(hdnUomElemID).value = uom;
    
    //close the popup
    closePopup();
}

//function UOM_select(price, uom, displayElemID, hdnPriceElemID, hdnUomElemID) {
//    //update the display value
//    var s = formatNumber (price, 2, 1);
//    s += "/" + uom;
//    $(displayElemID).innerHTML = s;
//    
//    //update the hidden values
//    $(hdnPriceElemID).value = price;
//    $(hdnUomElemID).value = uom;
//    
//    //close the popup
//    closePopup();
//}

//////////////////////////////////
//  Shipping Method Selection   //
//////////////////////////////////
function updateShippingMethods(zipTextbox) {
    //if shipping zip has changed, clear the ship to method selection
    
    var hdnPrevZip = $("hdnPreviousShipToZip");
    var hdnZips = $("hdnShippingZips");
    var hdnShipMethods = $("hdnShippingMethods");
    var cbo = $("cboShippingMethod");
    
    //bail if any of the above controls do not exist
    if (hdnPrevZip == null || hdnZips == null || hdnShipMethods == null || cbo == null) {
        return;
    }
    
    //get the first 3 chars of the zip
    var zip = trim(zipTextbox.value);
    if (zip.length > 3) {
        zip = zip.substring(0, 3);
    }
    
    //if zip has not changed, bail
    if (zip == hdnPrevZip.value) {
        return;
    }
    
    //save the current zip
    hdnPrevZip.value = zip;
    
    //reset the drop down
    cbo.selectedIndex = 0;

    //see if the zip is in the list
    var zipExists = false;
    var split = hdnZips.value.split("~");
    for (var i=0; i<split.length; i++) {
        if (zip == split[i]) {
            zipExists = true;
            break;
        }
    }
    
    //remove all items in the combo after the please selection item
    cbo.options.length = 1;
    
    //now readd the options, some may not be added if they are dependant on the zip
    split = hdnShipMethods.value.split("|");
    for (var i=0; i<split.length; i++) {
        var s = split[i].split("~");
		if (s[1]=="False" || zipExists) {
		    var opt = document.createElement("OPTION");
		    opt.text = s[2];
		    opt.value = s[0] + "~" + s[1];
		    cbo.options[cbo.length] = opt;
		}
    }
    
    //show/hide the entire section containing the shipping method.
    if (cbo.options.length > 1) {
        //$("trShippingMethod").style.display = "block";
        $("trShippingMethod").style.visibility = "visible";
        cbo.options[0].value = "";
    } else {
        //$("trShippingMethod").style.display = "none";
        $("trShippingMethod").style.visibility = "hidden";
        cbo.options[0].value = "n/a";
    }
    
    //if only one option (besides Please Select), select it
    if (cbo.options.length == 2) {
        cbo.selectedIndex = 1;
    }
}