/* MAIN JAVASCRIPT FUNCTIONS */
		window.onload=function()
		{
			xAddEventListener(window,"resize",adjustLayout,false);
			adjustLayout();
		}


//       window.onresize = function () 
//		{
//			xAddEventListener(window,"resize",adjustLayout,false);
//			adjustLayout();
//			
//		}

		function adjustLayout()
		{
			var cHeight=xHeight("center");
			var lHeight=xHeight("left");
			var rHeight=xHeight("right");
			var maxHeight=Math.max(cHeight,Math.max(lHeight,rHeight));
			xHeight("center",maxHeight);
			xHeight("left",maxHeight);
			xHeight("right",maxHeight);
			xShow("left");
			xShow("footer");
		}
		


// figure out which browser the user has
var xVersion='3.10', xOp7=false, xOp5or6=false, xIE4Up=false, xNN4=false, xUA=navigator.userAgent.toLowerCase();
if (window.opera) {
	xOp7 = (xUA.indexOf('opera 7') != -1 || xUA.indexOf('opera/7') != -1);
	if (!xOp7) xOp5or6 = (xUA.indexOf('opera 5') != -1 || xUA.indexOf('opera/5') != -1 || xUA.indexOf('opera 6') != -1 || xUA.indexOf('opera/6') != -1);
	}
else if (document.layers) xNN4 = true;
else { 
	xIE4Up = document.all && xUA.indexOf('msie') != -1 && parseInt(navigator.appVersion) >= 4;
	}
	
// function to determine visibility
function xShow(e) {
	if (!(e=xGetElementById(e))) return;
	if (e.style && xDef(e.style.visibility)) e.style.visibility = 'inherit';
	else if (xDef(e.visibility)) e.visibility = 'show';
	}
function xHide(e) {
    alert("hiding");
	if (!(e=xGetElementById(e))) return;
	if (e.style && xDef(e.style.visibility)) e.style.visibility = 'hidden';
	else if (xDef(e.visibility)) e.visibility = 'hide';
	}
	
// internal function to get the current styles
function xGetCS(ele, sP) {
	return parseInt(document.defaultView.getComputedStyle(ele,"").getPropertyValue(sP));
	}
	
// internal function to figure out the CSS after resizing
function xSetCH(ele, uH){
	if (uH<0) return;
	var pt=0, pb=0, bt=0, bb=0;
	if (xDef(document.defaultView) && xDef(document.defaultView.getComputedStyle)) {
		pt = xGetCS(ele, "padding-top");
		pb = xGetCS(ele, "padding-bottom");
		bt = xGetCS(ele, "border-top-width");
		bb = xGetCS(ele, "border-bottom-width");
		}
	else if (xDef(ele.currentStyle,document.compatMode)) {
		if (document.compatMode == "CSS1Compat"){
			pt = parseInt(ele.currentStyle.paddingTop);
			pb = parseInt(ele.currentStyle.paddingBottom);
			bt = parseInt(ele.currentStyle.borderTopWidth);
			bb = parseInt(ele.currentStyle.borderBottomWidth);
			}
		}
	else if (xDef(ele.offsetHeight,ele.style.height)) {
		ele.style.height = uH+"px";
		pt = ele.offsetHeight-uH;
		}
	if (isNaN(pt)) pt = 0; 
	if (isNaN(pb)) pb = 0; 
	if (isNaN(bt)) bt = 0; 
	if (isNaN(bb)) bb = 0;
	var cssH = uH-(pt+pb+bt+bb);
	if (isNaN(cssH) || cssH<0) return;
	else ele.style.height = cssH + "px";
	}

	
// function to figure out the height of columns on the page
function xHeight(e, uH) {
	if (!(e=xGetElementById(e)) || (uH && uH<0)) return 0;
	uH = Math.round(uH);
	var css = xDef(e.style);
	if (css && xDef(e.style.height,e.offsetHeight) && typeof(e.style.height) == "string") {
		if (arguments.length>1) xSetCH(e, uH);
		uH = e.offsetHeight;
		}
	else if (css && xDef(e.style.pixelHeight)) {
		if (arguments.length>1) e.style.pixelHeight = uH;
		uH = e.style.pixelHeight;
		}
	else if (xDef(e.clip) && xDef(e.clip.bottom)) {
		if (arguments.length>1) e.clip.bottom = uH;
		uH = e.clip.bottom;
		}
	return uH;
	}
	
// used to find elements in Netscape 4 only
function xLayer(id, root) { 
	var i, layer, found=null;
	if (!root) root = window;
	for (i=0; i<root.document.layers.length; i++) {
		layer = root.document.layers[i];
		if (layer.id == id) return layer;
		if (layer.document.layers.length) found = xLayer(id,layer);
		if (found) return found;
		}
	return null;
	}
	
// internal function to get the element by its ID
function xGetElementById(e) {
	if (typeof(e) != "string") return e;
	if (document.getElementById) e = document.getElementById(e);
	else if (document.all) e = document.all[e];
	else if (document.layers) e = xLayer(e);
	else e = null;
	return e;
	}
	
// internal function to get width of object
function xClientWidth() {
	var w=0;
	if (xOp5or6) w = window.innerWidth;
	else if (xIE4Up && document.documentElement && document.documentElement.clientWidth)
		w = document.documentElement.clientWidth;
	else if (document.body && document.body.clientWidth)
		w = document.body.clientWidth;
	else if (xDef(window.innerWidth, window.innerHeight, document.height)) {
		w = window.innerWidth;
		if (document.height > window.innerHeight) w-=16;
		}
	return w;
	}

// internal function to get height of object
function xClientHeight() {
	var h=0;
	if (xOp5or6) h = window.innerHeight;
	else if (xIE4Up && document.documentElement && document.documentElement.clientHeight)
		h = document.documentElement.clientHeight;
	else if (document.body && document.body.clientHeight)
		h = document.body.clientHeight;
	else if (xDef(window.innerWidth, window.innerHeight, document.width)) {
		h = window.innerHeight;
		if (document.width>window.innerWidth) h-=16;
		}
	return h;
	}
	
// internal function to scroll to the left
function xScrollLeft() {
	var offset = 0;
	if (xDef(window.pageXOffset)) 
		offset = window.pageXOffset;
	else if (document.documentElement && document.documentElement.scrollLeft) 
		offset = document.documentElement.scrollLeft;
	else if (document.body && xDef(document.body.scrollLeft)) 
		offset = document.body.scrollLeft;
	return offset;
	}
	
// internal function to scroll up
function xScrollTop() {
	var offset = 0;
	if (xDef(window.pageYOffset)) 
		offset = window.pageYOffset;
	else if (document.documentElement && document.documentElement.scrollTop) 
		offset = document.documentElement.scrollTop;
	else if (document.body && xDef(document.body.scrollTop)) 
		offset = document.body.scrollTop;
	return offset;
	}
	
// internal function to resize window
function xResizeEvent() { 
	if (window.xREL) setTimeout("xResizeEvent()", 250);
	var cw = xClientWidth(), ch = xClientHeight();
	if (window.xPCW != cw || window.xPCH != ch) { 
		window.xPCW = cw; 
		window.xPCH = ch; 
		if (window.xREL) window.xREL(); 
		}
	}
	
// internal function to scroll window
function xScrollEvent() { 
	if (window.xSEL) setTimeout("xScrollEvent()", 250);
	var sl = xScrollLeft(), st = xScrollTop();
	if (window.xPSL != sl || window.xPST != st) { 
		window.xPSL = sl; 
		window.xPST = st; 
		if (window.xSEL) window.xSEL(); 
		}
	}
	
// determines arguments
function xDef() {
	for (var i=0; i<arguments.length; ++i) {
		if (typeof(arguments[i]) == "" || typeof(arguments[i]) == "undefined") return false;
		}
	return true;
	}

	
// function to kick off other functions above
function xAddEventListener(e, eventType, eventListener, useCapture) {
	if (!(e = xGetElementById(e))) return;
	eventType = eventType.toLowerCase();
	if ((!xIE4Up && !xOp7) && e == window) {
		if (eventType == 'resize') { 
			window.xPCW = xClientWidth(); 
			window.xPCH = xClientHeight(); 
			window.xREL = eventListener; 
			xResizeEvent(); 
			return; 
			}
		if (eventType == 'scroll') { 
			window.xPSL = xScrollLeft(); 
			window.xPST = xScrollTop(); 
			window.xSEL = eventListener; 
			xScrollEvent(); 
			return; 
			}
		}
	var eh = "e.on" + eventType + "=eventListener";
	if (e.addEventListener) e.addEventListener(eventType, eventListener, useCapture);
	else if (e.attachEvent) e.attachEvent("on"+eventType, eventListener);
	else if (e.captureEvents) {
		if (useCapture || (eventType.indexOf('mousemove') != -1)) { 
			e.captureEvents(eval("Event."+eventType.toUpperCase())); 
			}
		eval(eh);
		}
	else eval(eh);
	}

// function to pop the product image window
function prodPop(prod_id, color) {
	var atts = "width=375,height=525,resize";
	var prodWin = window.open("product_detail.php?id=" + prod_id + "&img=" + color, "prodWin", atts);
	prodWin.focus();
	}

// function to pop up the portal
function bestop_portal(theProduct) {
	if (theProduct == null) theProduct = "hardtop";
	url = "http://www.bestop.com/portal/" + theProduct + "/index.php";
	atts = "width=625,height=500";
	var portalWin = window.open(url, "portalWin", atts);
	portalWin.focus();
	}
	
// function to b-LInk
window.name = "ShoppingCart";
function popupWin(wholeUrl) { 
	var atts = "width=625,height=400"; 
	var newWin = window.open(wholeUrl, "newWin", atts); 
 	newWin.focus(); 
 	} 
 	
 	function popupWinG(wholeUrl) { 
	var atts = "width=760,height=400, scrollbars=yes, resizable=yes"; 
	var newWin = window.open(wholeUrl, "newWin", atts); 
 	newWin.focus(); 
 	} 
 	//BTV
 	function btv(theProduct, theDealer) {
		var dealer = theDealer;
		if (theProduct == null) theProduct = "soundbar";
		url = "http://www.bestop.com/btv/index.php?p=" + theProduct + "&d=" + dealer;
		atts = "width=640,height=600,scrollbar,scrollbars";
		var newWin = window.open(url, "newWin", atts);
		newWin.focus();
		}
		
	//closerLook
	function bestop_closerLook(theProduct) { 
		if (theProduct == null) theProduct = "TrailMax_Seats"; 
		url = "http://www.bestop.com/closer_look/?p=" + theProduct; 
		atts = "width=640,height=550"; 
		var closerLookWin = window.open(url, "closerLookWin", atts); 
		closerLookWin.focus(); 
}
//hardware
	function hardwarePopup(thePage) { 
		if (thePage == null) thePage = "supertop_hardware.html"; 
		url = "http://www.bestop.com/hardware/" + thePage; 
		atts = "width=400,height=600,scrollbars=yes"; 
		var theWin = window.open(url, "theWin", atts); 
		theWin.focus(); 
}
	
		
// POP-UP for close up view
function popUp(URL) {
var view_width = 420;
var view_height = 565;
var look='toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width='+view_width+',height='+view_height+','
popwin=window.open("","",look)
popwin.document.open()
popwin.document.write('<title>Close-up View - Bestop</title><head>')
popwin.document.write('</head>')
popwin.document.write('<body bgcolor="#F3EBD5" leftmargin=0 rightmargin=0 topmargin=0 bottommargin=0 marginheight=0 marginwidth=0>')
popwin.document.write('<table cellpadding=0 cellspacing=0 border=0 width="100%" height="100%" ><tr><td align="center">')
popwin.document.write('<center><br>')
popwin.document.write('<table cellpadding=0 cellspacing=0 border=1 bordercolor="666666"><tr><td>')
popwin.document.write('<img src="'+URL+'">')
popwin.document.write('</td></tr></table>')
popwin.document.write('</td></tr><tr><td valign="bottom" align="center">')
popwin.document.write('<br><form><input type=submit value="Close" class="button-popups" onClick=\'self.close()\'></form><br>')
popwin.document.write('</center>')
popwin.document.write('</td></tr></table>')
popwin.document.write('</body>')
popwin.document.close()
}
		
 // pops up the Product Registration window
 function popRegistration() {
 	var atts = "height=600,width=800,scrollbars,resizable";
	var url = "/register/index.php";	
	var registerWin = window.open(url, "registerWin", atts);
	registerWin.focus();
 }

// This is the global variable for the popupPresetImage, setPopupImageCaptionTitle,
// setPopupImageCaptionText and setPopupImage functions
var g_szPopupImageLocation = "";
var g_szPopupCaptionTitle = "";
var g_szPopupCaptionText = "";

// This functions sets the value of the global popup image caption title variable
function setPopupImageCaptionTitle(_captionTitle)
{
    g_szPopupCaptionTitle = unescape(_captionTitle);
}

// This functions sets the value of the global popup image caption text variable
function setPopupImageCaptionText(_captionText)
{
    g_szPopupCaptionText = unescape(_captionText);
}

// This function sets the value of the global popup image location variable
function setPopupImage(imgLocation)
{
    // Parameters:
    //      imgLocation = the location of the image to show
    
    // Step 1.  Make sure the parameter is valid
    if(!imgLocation) { return; }
    
    
    // Step 2.  Update the global variable
    g_szPopupImageLocation = imgLocation;
    
    // Step 3.  Preload the new image
    preLoadImages([g_szPopupImageLocation]);
}

// This function creates a same window pop-up for the preset global image variable
function popupPresetImage(containerDiv, thumbnailImg)
{
    // Parameters:
    //      containerDiv = the div to set the innerHTML with the imgLocation
    //      thumbnailImg = the id of the img tag to place this image next to
    //      captionTitle = the text to display as the caption title below the image
    //      captionText = the text to display below the caption title
    
    
    // All we do is call the popupImage function
    popupImage(g_szPopupImageLocation, containerDiv, thumbnailImg);
}

// This function creates a same window pop-up for an image
function popupImage(imgLocation, containerDiv, thumbnailImg)
{
    // Parameters:
    //      imgLocation = the location of the image to show
    //      containerDiv = the div to set the innerHTML with the imgLocation
    //      thumbnailImg = the id of the img tag to place this image next to
    
    // Step 1.  Make sure the parameters are valid
    if(!imgLocation || !containerDiv || !thumbnailImg)
    {
        return;
    }
    
    
    // Step 2.  Find the thumbnailImg location
    var objThumbnailImg = xGetElementById(thumbnailImg);
    if(!objThumbnailImg || objThumbnailImg == thumbnailImg)
    {
        // We can't proceed without the thumbnail image
        return;
    }
    
    var xThumbnail = findXPos(objThumbnailImg);
    var yThumbnail = findYPos(objThumbnailImg);
    
    
    // Step 3.  Find the containing div
    var objContainer = xGetElementById(containerDiv);
    if(!objContainer || objContainer == containerDiv)
    {
        // We can't proceed without the container div
        return;
    }
    
    
    // Step 4.  Create the inner HTML
    var szInnerHtml =
        '<div class="content">' +
            '<a href="#" onclick="popupImage(&quot;' + imgLocation + '&quot;, &quot;' + containerDiv +
                '&quot;, &quot;' + thumbnailImg + '&quot;);">' +
                '<img src="' + imgLocation + '" style="z-index:0;" />' +
            '</a>';
            
    if (g_szPopupCaptionTitle!="")
            szInnerHtml += '<h2>' + g_szPopupCaptionTitle +'</h2>';
            
    if (g_szPopupCaptionText != "")
            szInnerHtml += '<p>' + g_szPopupCaptionText + '</p>';
            
    szInnerHtml += '<div class="clear">' +
                '<a href="#" onclick="popupImage(&quot;' + imgLocation + '&quot;, &quot;' + containerDiv +
                '&quot;, &quot;' + thumbnailImg + '&quot;);">' +
                    '<img src="images/btn_close2.gif" alt="Close" class="right" />'  +
                '</a>' +
            '</div>' +
        '</div>';
        
    objContainer.innerHTML = szInnerHtml;
    
    
    // Step 5.  Set the x and y location for the div to be near the image
    var xDiv = -70;
    var yDiv = -120;
    
    objContainer.style.display = (!objContainer.style.display || objContainer.style.display == "" || objContainer.style.display == "none") ? "block" : "none";
    objContainer.style.left = xThumbnail + xDiv + 'px';
    objContainer.style.top = yThumbnail + yDiv + 'px';
}

// This function preloads the supplied images
function preLoadImages(aImages) {
    // Parameters:
    //      aImages = an array of all the image src values
    
    // Step 1.  Make sure the supplied parameter is valid
    if(!aImages || !aImages.length) { return; }
    
    
    // Step 2.  Pre-load the images
    for(var i = 0; i < aImages.length; i++)
    {
        var img = new Image();
        img.src = aImages[i];
    }
}

// This function finds the X location for a given object
function findXPos(o) {
    // Parameters:
    //      o = the object to find the X position of
    
    var n = 0;
    if (o.offsetParent) {
    while (1) {
      n += o.offsetLeft;
      if (!o.offsetParent) { break; }
      o = o.offsetParent;
    }
    } else if (o.x) {
    n += o.x;
    }
    
    // Return the processed X position
    return n;
}

// This function finds the Y location for a given object
function findYPos(o) {
    // Parameters:
    //      o = the object to find the Y position of
    
    var n = 0;
    if (o.offsetParent) {
    while (1) {
      n += o.offsetTop;
      if (!o.offsetParent) { break; }
      o = o.offsetParent;
    }
    } else if (o.y) {
    n += o.y;
    }

    // Return the processed Y position
    return n;
}

function popupImageWin(imageLocation, popupTitle)
{
	PositionX = 100;
	PositionY = 100;

	defaultWidth  = 500;
	defaultHeight = 500;

	var AutoClose = true;
	
	var options='scrollbars=no,location=no,width=150,height=100,left='+PositionX+',top='+PositionY;
	imgWin=window.open('','_blank',options);
	with (imgWin.document){
	        writeln('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">');
        	writeln('<html xmlns="http://www.w3.org/1999/xhtml">');
		write('<head><title>Loading Image by 4 Wheel Drive Hardware</title><style>body{margin:0px;overflow:hidden;}</style>');write('<sc'+'ript>');
		write('function reSizeToImage(){');
		write('width=document.images[0].width;');
		write('height=document.images[0].height;');
		write('window.doneAlready = true;');
		write('window.resizeTo(width+20,height+55);}');
		write('function doTitle(){document.title="'+popupTitle+'";}');
		write('</sc'+'ript>');
		if (!AutoClose) write('</head><body bgcolor=ffffff scroll="no" onload="reSizeToImage();doTitle();self.focus()">')
		else write('</head><body bgcolor=ffffff scroll="no" onload="reSizeToImage();doTitle();self.focus()">');
		write('<img name="fourwheelparts" src='+imageLocation+' style="display:block"></body></html>');
		close();		
	}
}
function popupWindow(popupLocation, popupWidth, popupHeight)
{
        PositionX = 100;
        PositionY = 100;
 
        var options='scrollbars=no,location=no,width='+popupWidth+',height='+popupHeight+',left='+PositionX+',top='+PositionY;
        var imgWin=window.open(popupLocation,'_blank',options);
}
function popupResizeableWindow(popupLocation, popupWidth, popupHeight)
{
        PositionX = 100;
        PositionY = 100;
 
        var options='resizable=yes,scrollbars=no,location=no,width='+popupWidth+',height='+popupHeight+',left='+PositionX+',top='+PositionY;
        var imgWin=window.open(popupLocation,'_blank',options);
}

// This function is called when tabs first load on our product page
function initTab()
{
    swapTab('tabC0', 'tab0');
}

// This function handles switching our tabs on the product page
function swapTab(st, a)
{
    for (var i = 0; i < 15; i++)
    {
        var j = i;
        var strA = 'tab' + j;
        var stName = 'tabC' + j;
        var strAlink = 'tab' + j + 'A';
        if (document.getElementById(stName) != null && document.getElementById(strA) != null)
        {
            document.getElementById(stName).style.display = 'none';
            //document.getElementById(strA).style.background = 'url("/images/css/tab-inactive.gif")';
            document.getElementById(strAlink).style.color = '#004276';
            document.getElementById(strAlink).style.fontWeight = 'normal';
        }
    }
    
    var aLink;
    
    aLink = a + 'A';
    if (document.getElementById(st))
        document.getElementById(st).style.display = 'block';
    
//    if (document.getElementById(a))
//        document.getElementById(a).style.background = 'url("/images/css/tab-active.gif")';
    
    if (document.getElementById(aLink))
    {
        document.getElementById(aLink).style.color = '#004276';
        document.getElementById(aLink).style.fontWeight = 'normal';
    }
}

// This function is called to switch the image of the main graphic to the specified one
function changeMainImage(elementID, newImage, linecode, width, height, wm)
{
    var imgElement = document.getElementById(elementID);
        
    if (imgElement)
    {
        if ((linecode == 1) || (linecode == 2) || (linecode == 3))
            linecode = "BST";
            
        imgElement.src = getImagePath(newImage, linecode, width, height, wm);
        
        setPopupImage(getImagePath(newImage,linecode,380,0,wm));
    }
}

function getImagePath(newImage, linecode, width, height, wm)
{
    var strMainPath = "http://www.4wd.com/aux_incl/images.ashx?i=";
    //var strMainPath = "http://localhost:3809/aux_incl/images.ashx?i=";
    var strPath =  "";
    
    if (width==null)
        width = 150;
    
    if (height==null)
        height = 150;
        
    if (wm==null)
    {
        wm = "P";
    }
        
    strMainPath += newImage+"&w="+width+"&h="+height+"&wm="+wm;
    strPath =  strMainPath  + "&partNo=" + linecode + "&jeep-parts=true";
    return strPath;
}

function changeImageByDropDownList(control, mainImgID, linecode, width, height)
{
    var strVal = control.value;
    var a_Value = new Array();
    var strImgName = "";
    
    a_Value = strVal.split('|');
    
    if ((a_Value.length > 1) && (a_Value[0] != "-1"))
    {
        strImgName = a_Value[1];
        changeMainImage(mainImgID, strImgName, "BST", width, height);
        var idxSelected = control.selectedIndex;
        g_szPopupCaptionTitle = control.options[idxSelected].text + " - " + g_szPopupCaptionTitle;
    }
}

// This function shows an element
function showElement(_elementID)
{
    // Parameters:
    //      _elementID = the ID of the object to show
    
    changeElementDisplay(_elementID, "block");
}

// This function hides an element
function hideElement(_elementID)
{
    // Parameters:
    //      _elementID = the ID of the object to hide
    
    changeElementDisplay(_elementID, "none");
}

// This function changes the display property for an object using it's ID
function changeElementDisplay(_elementID, _displayState)
{
    // Parameters:
    //      _elementID = the ID of the object to change the display property for
    //      _displayState = the display property value (none or block)
    
    // Step 1.  Make sure the parameter is valid
    if(!_elementID || !_displayState || (_displayState != "none" && _displayState != "block")) { return; }
    
    
    // Step 2.  Get the object
    var objElement = xGetElementById(_elementID);
    if(!objElement || !objElement.style) { return; }
    
    
    // Step 3.  Update the display property
    objElement.style.display = _displayState;
}

// This function finds the X location for a given object
function findXPosition(o) {
    // Parameters:
    //      o = the object to find the X position of
    
    var n = 0;
    if (o.offsetParent) {
    while (1) {
      n += o.offsetLeft;
      if (!o.offsetParent) { break; }
      o = o.offsetParent;
    }
    } else if (o.x) {
    n += o.x;
    }
    
    // Return the processed X position
    return n;
}

// This function finds the Y location for a given object
function findYPosition(o) {
    // Parameters:
    //      o = the object to find the Y position of
    
    var n = 0;
    if (o.offsetParent) {
    while (1) {
      n += o.offsetTop;
      if (!o.offsetParent) { break; }
      o = o.offsetParent;
    }
    } else if (o.y) {
    n += o.y;
    }

    // Return the processed Y position
    return n;
}

// Removes leading whitespaces
function LTrim( value ) {
	if(!value || !value.replace) { return value; }
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value ) {
	if(!value || !value.replace) { return value; }
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value ) {
	if(!value || !value.replace) { return value; }
	return LTrim(RTrim(value));
	
}


// Gets an element by it's id on the page
function getElement(id)
{
    if (document.getElementById)
        var returnVar = document.getElementById(id);
    else if (document.all)
        var returnVar = document.all[id];
    else if (document.layers)
        var returnVar = document.layers[id];
    return returnVar;
}

// This function gets the value of the supplied element
function getValue(objElement)
{
	// Parameters:
	//		objElement = the element to get the value for
	
	
    // Make sure the object is valid
    if(!objElement) { return ""; }
    
    // Return the value of the object
	var szValue = "";
	
	if(objElement.innerHTML)
	{
		szValue = trim(objElement.innerHTML);
	}
	
	if(objElement.value && (objElement.value != "-1" || szValue == ""))
	{
		szValue = trim(objElement.value);
	}
	
	// Check if we need to get a value from the drop down
	if(szValue == "" && objElement.length)
    {
        // This is a drop down, so loop through and get the selected value
        for(var i = 0; i < objElement.length; i++)
        {
            if(objElement[i] && objElement[i].selected)
            {
                szValue = trim(objElement[i].value);
            }
        }
    }
    
    // Return the value we have at this point
    return szValue;
}

// This function sets the value of an element
function setValue(objElement, _value)
{
	// Parameters:
	//		objElement = the element to set the value for
	//		_value = the value to set


	// Make sure we have valid parameters
	if(!objElement || !_value) { return; }
    _value = unescape(_value);
    
    // Step 2.  Set the value of the object
    if(objElement.value && !objElement.innerHTML)
    {
        objElement.value = _value;
    }
    else
    {
		objElement.innerHTML = _value;
    }
}

// Global variable to get browser window information
var windowState =
(function()
{
    var readScroll = {scrollLeft:0,scrollTop:0};
    var readSize = {clientWidth:0,clientHeight:0};
    var readScrollX = 'scrollLeft';
    var readScrollY = 'scrollTop';
    var readWidth = 'clientWidth';
    var readHeight = 'clientHeight';

    function otherWindowTest(obj)
    {
        if((document.compatMode)&& (document.compatMode == 'CSS1Compat')&& (document.documentElement))
        {
            return document.documentElement;
        }
        else if(document.body)
        {
            return document.body;
        } else {
            return obj;
        }
    };
    
    if((typeof this.innerHeight == 'number') && (typeof this.innerWidth == 'number'))
    {
        readSize = this;
        readWidth = 'innerWidth';
        readHeight = 'innerHeight';
    } else {
        readSize = otherWindowTest(readSize);
    }
    if((typeof this.pageYOffset == 'number') && (typeof this.pageXOffset == 'number')) {
        readScroll = this;
        readScrollY = 'pageYOffset';
        readScrollX = 'pageXOffset';
    } else {
        readScroll = otherWindowTest(readScroll);
    }
    
    return {
getScrollX:function(){
return (readScroll[readScrollX]||0);
},
getScrollY:function(){
return (readScroll[readScrollY]||0);
},
getWidth:function(){
return (readSize[readWidth]||0);
},
getHeight:function(){
return (readSize[readHeight]||0);
    }
};
})();

// show/hide hidden div
function showHide(popup, o, xAdd, yAdd) {
    // Parameters:
    //      popup = the ID tag for the <div> to show/hide
    //      o = the ID tag of a relative <img> to use for positioning [null=center]
    //      xAdd = the numerical value to move the popup relative to the image [null=center]
    //      yAdd = the numerical value to move the popup relative to the image [null=center]
    var j = getElement(popup);
    var wrapper = getElement('wrapper');
    if(j && j.style && wrapper)
    {
        // Update the style
        if(!j.style.display || j.style.display == "" || j.style.display == "none")
        {
            // Move the object off the screen so we can get it's height
            j.style.left = '-10000px';
            j.style.top = '-10000px';
            j.style.display = 'block';
        
            // Check to center the image
            if(!o && xAdd == null && yAdd == null)
            {
                // Center the popup
                //var viewPortWidth = windowState.getWidth();
                var viewPortWidth = wrapper.clientWidth;
                var viewPortHeight = windowState.getHeight();
                var horizontalScroll = windowState.getScrollX();
                var verticalScroll = windowState.getScrollY();
                
                var divWidth = 0;
                if(j.offsetWidth) { divWidth = j.offsetWidth; }
                else if(j.style.width) { divWidth = j.style.width; }
                else { divWidth = 440; }
                
                var divHeight = 0;
                if(j.offsetHeight) { divHeight = j.offsetHeight; }
                else if(j.style.height) { divHeight = j.style.height; }
                else { divHeight = 100; }
                
                xAdd = Math.round(horizontalScroll+((viewPortWidth-divWidth)/2));
                yAdd = Math.round(verticalScroll+((viewPortHeight-divHeight)/2));
            }
            else
            {        
                if(o) { xAdd = xAdd + findXPosition(getElement(o)); }  
                if(o) { yAdd = yAdd + findYPosition(getElement(o)); }
            }
        
            j.style.left = xAdd + 'px';
            j.style.top = yAdd + 'px';
        }
        else
        {
            j.style.display = 'none';
        }
    }
}

function ChangeInstallationChartRating(rating, titleID, textID)
{
    var elementTitle = document.getElementById(titleID);
    var elementText = document.getElementById(textID);
    var TitleText = "";
    var DescriptionText = "";
    
    switch(rating)
    {
        case 1:
            TitleText = "Beginner";
            DescriptionText = "This type of product requires no tools or the most basic tools like screwdrivers, wrenches, hammers etc. Products are easy to install.";
            break;
        case 2:
            TitleText = "Intermediate";
            DescriptionText = "This type of product requires the basic tools and some specialty tools like floor jacks, drill, torx bits, brake bleeder wrenches and the likes. If you own any of these, you should have no problem installing these products.";
            break;
        case 3:
            TitleText = "Advanced";
            DescriptionText = "This type of products requires a good amount of specialty tools and mechanical ability. Tools like feeler gauges, oil wrenches, flaring tools, electronic multi-meter are in your tool set. Some of these products will require help of a buddy. Take the time to do the job right.";
            break;
        case 4:
            TitleText = "Expert";
            DescriptionText = "This type of product requires that you are an experienced mechanic or have them installed by a mechanic. In some case welding, cutting etc will be required. You know how to use any or all of the following tools: welder, die grinder, pneumatic tools, pullers, coil spring compressor and more. Some of these products may take a couple of days to install.<br />Note: When in doubt of your own ability, please consult a professional mechanic.";
            break;
    }
    
    elementTitle.innerHTML = TitleText;
    elementText.innerHTML = DescriptionText;
}

// This is used during checkout to change the class of the <div id="checkout"> tag to
//      include a class="res800" for people with 800 width resolution
function changeCheckoutClass()
{
    // Get the div tag
    var objCheckoutTag = getElement("checkout");
    if(!objCheckoutTag) { return; }
    
    // width of the body (code taken from dw_viewport.js from http://www.dyn-web.com/)
    var d = document.documentElement;
    var b = document.body;
  
    var ww = 0;
    if (window.innerWidth) { ww = window.innerWidth - 18; }
    else if (d && d.clientWidth) { ww = d.clientWidth; }
    else if (b && b.clientWidth) { ww = b.clientWidth; }
    
    // We only process if the width is 800 or less
    if(ww > 800) { return; }
    
    // Change the class
    var szClass = "res800";
    if(objCheckoutTag.className)
    {
        szClass += " " + objCheckoutTag.className;
    }
    
    objCheckoutTag.className = szClass;
}

// This function handles switching the checkout-payment screen to different inputs
function switchPaymentScreen(_arrayShowIDs, _arrayHideIDs)
{
    // Parameters:
	//		_arrayShowIDs = a list of IDs of the tags to show
	//      _arrayHideIDs = a list of the IDs of the tags to hide
	
    // Make sure the supplied parameters are valid
    if(!_arrayShowIDs || !_arrayHideIDs)
    {
        return;
    }
    
    // Split apart the supplied IDs
    _arrayShowIDs = _arrayShowIDs.split("|");
    _arrayHideIDs = _arrayHideIDs.split("|");
    
    // Hide the objects
    for(var i = 0; i < _arrayHideIDs.length; i++)
	{
	    if(!_arrayHideIDs[i]) { continue; }
	    // Hide the element
	    hideElement(_arrayHideIDs[i]);
	}
    
    // Show the objects
    for(var i = 0; i < _arrayShowIDs.length; i++)
	{
	    if(!_arrayShowIDs[i]) { continue; }
	    // Show the element
	    showElement(_arrayShowIDs[i]);
	}
}

function changeClass(_objID, _newClassname)
{
    if (_objID)
    {
        var obj = getElement(_objID);
        
        if ((obj) && (_newClassname!= null) && (obj.className != _newClassname))
        {
            obj.className = _newClassname;
        }
    }
}

var g_SM_subtotal;
var g_SM_tax;
var g_SM_pickupstore;
var g_SM_ddlID;
var g_SM_litTotalID;
var g_SM_surcharges;

// This function saves a value to a cookie
function saveCookie(_cookieName, _cookieValue, _expMinutes)
{
    // Parameters:
    //      _cookieName = the name of the cookie to save
    //      _cookieValue = the value for the cookie
    //      _expMinutes = the number of minutes before the cookie will expire
    
    
    // Step 1.  Make sure the parameters are valid
    if(!_cookieName) { return; }
    if(!_cookieValue || !_expMinutes)
    {
        // They want to remove the cookie
        removeCookie(_cookieName);
        return;
    }
    var nExpMinutes = parseInt(_expMinutes, 10);
    
    
    // Step 2.  Create the expiration date    
    var dtDate = new Date();
	dtDate.setTime(dtDate.getTime()+(nExpMinutes*60*1000));
	
	
	// Step 3.  Make sure we don't have bad characters in the cookie value
	_cookieValue = escape(_cookieValue);
	
	
	// Step 4.  Save the cookie
	var szCookie = _cookieName + "=" + _cookieValue + "; expires=" + dtDate.toGMTString() + "; path=/";
	document.cookie = szCookie;
}

// This function removes a cookie
function removeCookie(_cookieName)
{
    // Parameters:
    //      _cookieName = the name of the cookie to remove
    
    
    // Step 1.  Make sure the parameter is valid
    if(!_cookieName) { return; }
    
    
    // Step 2.  Create a date in the past to remove the cookie
    var dtDate = new Date();
    dtDate.setTime(dtDate.getTime()+(-1*24*60*60*1000));
    
    
    // Step 3.  Remove the cookie
    var szCookie = _cookieName + "=; expires=" + dtDate.toGMTString() + "; path=/";
    document.cookie = szCookie;
}

// This function gets a cookie value (default value: empty string)
function getCookieValue(_cookieName)
{
    // Parameters:
    //      _cookieName = the name of the cookie to get the value from
    
    
    // Step 1.  Make sure the parameter is valid
    if(!_cookieName) { return ""; }
    
    
    // Step 2.  Get the cookie value
    if (document.cookie.length>0)
    {
        var c_start=document.cookie.indexOf(_cookieName + "=");
        if (c_start!=-1)
        { 
            var c_start=c_start + _cookieName.length+1; 
            var c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return "";
}

function changeNewPartsCID(ddlID)
{
    var ddlCategories = getElement(ddlID);
    
    if (ddlCategories != null)
    {
        var cID = ddlCategories.value;
        
        if (cID >= 0)
        {
            window.location = "/jeep-parts/new-jeep-products.aspx?cID=" + cID;
        }
    }
}

function changeShippingMethod(ddlID, litTotalID)
{
    var ddlShipping = getElement(ddlID);
    var ddlIndex;
    var objStorePickup = getElement('storepickup');
    
    
    if (ddlShipping != null)
    {
        var litPickupStore = getElement(g_SM_pickupstore);
        var arr = ddlShipping.value.split("|");
        switch (arr[0])
        {
            case 'TF':
                if (arr[1] == 0)
                {
                    showHideCentered('calculate-shipping');
                    //showHide('calculate-shipping', 'imgSecure', -400, -310)
                }
                else
                {
                    if (litPickupStore != null)
                    {
                        litPickupStore.innerHTML = "&nbsp;";
                    }
                    if(objStorePickup)
                    {
                        objStorePickup.style.display = 'none';
                    }
                    removeCookie("storeid");
                    saveCookie("lastSM", ddlShipping.selectedIndex, 60); // one hour
                    // set total
                    var litTotal = getElement(litTotalID);
                    if (litTotal != null)
                    {
                        var Total = g_SM_subtotal+g_SM_tax+g_SM_surcharges+parseFloat(arr[1]);
                        litTotal.innerHTML = "$".concat(Total.toFixed(2));
                    }
                }
                window.location = "/shoppingcart.aspx";
                break;
            case 'PIS':
                showHideCentered('storepickup');
                //showHide('storepickup', 'imgSecure', -500, -300);
                break;
            default:
                if (litPickupStore != null)
                {
                    litPickupStore.innerHTML = "&nbsp;";
                }
                if(objStorePickup)
                {
                    objStorePickup.style.display = 'none';
                }
                removeCookie("storeid");
                saveCookie("lastSM", ddlShipping.selectedIndex, 60); // one hour
                // set total
                var litTotal = getElement(litTotalID);
                if (litTotal != null)
                {
                    var Total = g_SM_subtotal+g_SM_tax+g_SM_surcharges+parseFloat(arr[1]);
                    litTotal.innerHTML = "$".concat(Total.toFixed(2));
                }
                window.location = "/shoppingcart.aspx";
                break;
        }
        
        saveCookie("sMethod", arr[0], 60*24); // one day
    }
}

function changeToLastSM(ddlID)
{
    var ddlShipping = document.getElementById(ddlID);
    
    if (ddlShipping != null && ddlShipping.options && ddlShipping.options.length > 0)
    {
        var nIndex = getCookieValue("lastSM");
        if(!nIndex)
        {
            // Find the first non-pickup index
            for(var i = 0; i < ddlShipping.options.length; i++)
            {
                if(ddlShipping.options[i].value.toUpperCase().indexOf("PIS|") == -1)
                {
                    nIndex = i;
                    break;
                }
            }
            
            // Reset to 0 if we still haven't found an index
            if(!nIndex) { nIndex = 0; }
        }
        
        // Update the dropdown to a value other than pickup in store
        if(parseInt(nIndex, 10) < ddlShipping.options.length)
        {
            ddlShipping.selectedIndex = nIndex;
            // Change the smethod cookie as well
            var arr = ddlShipping.options[nIndex].value.split("|");
            saveCookie("sMethod", arr[0], 60*24); // one day
            
            // Remove an existing store printout
            var litPickupStore = getElement(g_SM_pickupstore);
            if (litPickupStore != null)
            {
                litPickupStore.innerHTML = "";
            }
            removeCookie("storeid");
        }
        
        //RefreshShoppingCart();
        
        var ddlShipping = getElement(g_SM_ddlID);
        var arr = ddlShipping.value.split("|");

        // set total
        var litTotal = getElement(g_SM_litTotalID);
        if (litTotal != null)
        {
            var Total = g_SM_subtotal+g_SM_tax+g_SM_surcharges+parseFloat(arr[1]);
            litTotal.innerHTML = "$".concat(Total.toFixed(2));
        }
        
        window.location = "/shoppingcart.aspx";
    }
}

function RefreshShoppingCart()
{
    var szShippingMethod = getCookieValue("sMethod");
    var litPickupStore = getElement(g_SM_pickupstore);
    var objStorePickup = getElement('storepickup');
    
    switch(szShippingMethod)
    {
        case 'PIS':
            break;
        default:
            if (litPickupStore != null)
            {
                litPickupStore.innerHTML = "&nbsp;";
            }
            if(objStorePickup)
            {
                objStorePickup.style.display = 'none';
            }
            
            var ddlShipping = getElement(g_SM_ddlID);
            
            
            
            if (ddlShipping != null)
            {
                //update the ddl to match the saved shipping method
                var nIdx = 0;
                for(var i = 0; i < ddlShipping.options.length; i++)
                {
                    if(ddlShipping.options[i].value.toUpperCase().indexOf(szShippingMethod) != -1)
                    {
                        nIdx = i;
                        break;
                    }
                }
                
                ddlShipping.selectedIndex = nIdx;
                
                var arr = ddlShipping.value.split("|");

                // set total
                var litTotal = getElement(g_SM_litTotalID);
                if (litTotal != null)
                {
                    var Total = g_SM_subtotal+g_SM_tax+g_SM_surcharges+parseFloat(arr[1]);
                    litTotal.innerHTML = "$".concat(Total.toFixed(2));
                }
                
            }
            break;
    }
}

// This function removes the default text from an input box and sets the font color to black
function removeDefault(objElement, defaultValue)
{
    // Parameters:
    //      objElement = the object to change the .value property on
    //      defautlValue = the default/initial value to remove
    
    // Make sure the parameters are valid
    if(!objElement) { return; }
    
    // Change the font color
    objElement.style.color = '#000';
    // Remove the default value
    if(objElement.value == defaultValue) { objElement.value = ''; }
}
// This function shows the default text for an input box and sets the font color to #ddd
function showDefault(objElement, defaultValue)
{
    // Parameters:
    //      objElement = the object to change the .value property on
    //      defautlValue = the default/initial value to show
    
    // Make sure the parameters are valid
    if(!objElement) { return; }
    
    // Add the default value
    if(!objElement.value || objElement.value == '') { objElement.value = defaultValue; objElement.style.color = '#ddd'; }
}
// This function gets the value for an XmlNode from the input string using it's name (case insensitive)
function GetXmlNodeValue(inputXml, nodeName)
{
    return GetRegexValue(inputXml, "<" + nodeName + ">(.+)</" + nodeName + ">", 1);
}
// This function gets the text at the supplied matchIndex for the regexMatch on the inputString
function GetRegexValue(inputString, regexMatch, matchIndex)
{
    // Parameters:
    //      inputString = the text to perform the regular expression match on
    //      regexMatch = the regular expression to use to match on the inputString
    //      matchIndex = the index of the group to return
    
    // Make sure the parameters are valid
    if(!inputString || !regexMatch || parseInt(matchIndex, 10) != matchIndex)
    {
        return null;
    }

    // Get the regex value
    var r = new RegExp(regexMatch, "im");
    var m = r.exec(inputString);
    if(m != null && m.length > matchIndex)
    {
        return m[matchIndex];
    }
    
    // Return null by default
    return null;
}
// This function will slowly show up to 3 ellipses behind a text to show it is undergoing change
var objEllipsesTimeout = null;
function ShowTextEllipses(elementID, updateText)
{
    // Parameters:
    //      elementID = the ID of the HTML tag who's value/innerHTML to change
    //      updateText = the text to show when updating for the object (so we know how many ellipses to add/remove)
    
    // Make sure the parameters are valid
    if(!elementID || !updateText) { return; }
    var objElement = getElement(elementID);
    if(!objElement) { return; }
    
    var szCurrentValue = getValue(objElement);
    var szNextValue = updateText;
    if(szCurrentValue)
    {
        var szEllipses = GetRegexValue(szCurrentValue, updateText + "(.+)", 1);
        if(szEllipses)
        {
            if(szEllipses.length < 3)
            {
                szNextValue = szNextValue + szEllipses + ".";
            }
        }
        else
        {
            szNextValue = szNextValue + ".";
        }
    }
    
    // Update the value
    setValue(objElement, szNextValue);
    if(objEllipsesTimeout) { clearTimeout(objEllipsesTimeout); }
    objEllipsesTimeout = setTimeout('ShowTextEllipses(\'' + elementID + '\', \'' + updateText + '\')', 250);
}
function StopTextEllipses()
{
    // Parameters:
    //      None ---- we have a global object we work
    
    // Check if we have an ellipses in progress
    if(objEllipsesTimeout)
    {
        clearTimeout(objEllipsesTimeout);
        objEllipsesTimeout = null;
    }
}

// ---------------- Wish List Functions --------------- //
// ---- other functions exist in ajax-functions.js ---- //
// This function forwards to the wish list search page
function WishList_PerformSearch(searchBox, queryStringName, redirectLocation)
{
    // Parameters:
    //      searchBox = the ID of the <input> tag containing the search value
    //      queryStringName = the query string name to use when passing the searchBox value
    
    // Make sure the parameters are valid
    if(!searchBox || !queryStringName) { return; }
    var objSearchBox = getElement(searchBox);
    if(!objSearchBox) { return; }
    if(!redirectLocation) { redirectLocation = "/wishlist/find-list.aspx"; }
    
    // Redirect
    window.location = redirectLocation + "?" + queryStringName + "=" + escape(trim(getValue(objSearchBox)));
}
// This function creates a dynamic wish list add to cart popup
function WishList_AddToCartPopup(showMessageID, partNO, partQty, partDesc, partImage, partLine, partPrice, wishListItemID)
{
    // Parameters:
    //      showMessageID = the ID of the popup to pass to our showMessage function
    //      partNO = the PartNO that will be added to cart
    //      partQty = the Desired qty for this PartNO in the WishList
    //      partDescr = brief description of the part for the customer
    //      partImage = sample image of the part
    //      partLine = the line for the part
    //      partPrice = the price for the part
    
    // Make sure parameters we handle are valid
    if(!partNO || !partDesc || !partImage || !partLine || !partPrice) { return; }    
    var szContentID = "wishlist_add-to-cart_dynamicContent"; // this is gotten from the popup
    
    // Get the content tag
    var objContent = getElement(szContentID);
    if(!objContent) { return; }
    
    // Create the innerHTML for the content
    var szInnerHTML =
        '<h3 class="center">' + partDesc + '</h3>' +
        '<div class="hr"></div>' +
        '<img src="/aux_incl/images.ashx?i=' + partImage + '&partNo=' + partLine + '&w=55&h=55" alt="" class="left" style="margin-right: 10px;" />' +
        '<p><small>Part Number: ' + partNO + '</small></p>' +
        '<p>Add this item to your cart.</p>' +
        //'<p>You can send a personalized e-mail <small><a href="#" onclick="showMessage(&quot;wishlist_preview-personalized-email&quot;, &quot;wishlist_poup_add-to-cart_img&quot;, -200, -200); return false;">(preview)</a></small> with your purchase. Or, you can make the gift a surprise.</p>' +
        //'<input type="hidden" value="' + partNO + '" id="wishlist_popup_add-to-cart_partNO" name="wishlist_popup_add-to-cart_partNO" />' +
        '<input type="hidden" value="' + wishListItemID + '" id="wishlist_popup_add-to-cart_wishListItemID" name="wishlist_popup_add-to-cart_wishListItemID" />' +
            /*'<li>' +
                '<em>Personalized Message:</em>' +
                '<textarea id="wishlist_popup_add-to-cart_emailMessage" name="wishlist_popup_add-to-cart_emailMessage" rows="5" cols="25">I hope you enjoy this great gift!</textarea>' +
            '</li>' +
            '<li>' +
                '<em>&nbsp;</em>' +
                '<input type="checkbox" id="wishlist_popup_add-to-cart_chkMessage" name="wishlist_popup_add-to-cart_chkMessage" class="checkbox" /> <small>Yes, I want to send a personalized message.</small>' +
            '</li>' +
            */
                '<div class-"clear"></div><div class="center disc"><p class="pricetext">' + partPrice + '</p>' +
                '<p class="qty">Qty: ' +
                '<input type="text" id="wishlist_popup_add-to-cart_qty" name="wishlist_popup_add-to-cart_qty" class="qty" value="' + partQty + '" /></p>' +
                //'<a href="#" onclick="WishList_AddToCart(&quot;wishlist_popup_wishlistid&quot;, &quot;wishlist_popup_add-to-cart_partNO&quot;, &quot;wishlist_popup_add-to-cart_qty&quot;, &quot;wishlist_popup_add-to-cart_emailMessage&quot;, &quot;wishlist_popup_add-to-cart_chkMessage&quot;); return false;">' +
                '<p><a href="#" onclick="WishList_AddToCart(&quot;wishlist_popup_add-to-cart_wishListItemID&quot;, &quot;wishlist_popup_add-to-cart_qty&quot;); return false;">' +
                    '<img src="/images/buttons/btn_addtocart.gif" alt="Add To Cart" class="btn" />' +
                '</a></p></div>' +
        '<div class="clear">' +
            '<a href="#" onclick="showMessageCentered(&quot;wishlist_add-to-cart&quot;); return false;">' +
                '<img src="/images/buttons/btn_close2.gif" alt="close" class="right" />' +
            '</a>' +
        '</div>';
    
    // Update the content and show it
    setValue(objContent, szInnerHTML);
    showMessageCentered(showMessageID);
}
// This function handles the click for the add to cart in the wish list popup
function WishList_AddToCart(wishListItemID, partQty)
{
    // Parameters:
    //      wishListItemID = the ID of the <input> tag containing the WishListItem to add
    //      partQty = the ID of the <input> tag containing the Qty to add
    
    // Make sure the parameters are valid
    if(!wishListItemID || !partQty) { return; }
    var szQty = getValue(getElement(partQty));
    var szWishListItemID = getValue(getElement(wishListItemID));
    if(!szWishListItemID) { return; }
    
    // Make sure the object values are valid
    var nWishListItemID = parseInt(szWishListItemID, 10);
    if(szWishListItemID != nWishListItemID || nWishListItemID < 1) { return; }
    
    var nQty = parseInt(szQty, 10);
    if(szQty != nQty || nQty < 1) { nQty = 1; }
    
    // Redirect
    window.location = "/shoppingcart.aspx?wli=" + nWishListItemID + "&qty=" + nQty;
}

// shows/hide hidden div in the center
function showHideCentered(popup) {
    showHide(popup, null, null, null);
}

// Clears a dropdown of all its entries
function clearDropDown(objDropDown)
{
    if(!objDropDown || !objDropDown.length || !objDropDown.options)
    {
        return;
    }
    
    for(var j = objDropDown.length; j >= 0; j--)
    {
        objDropDown.options[j] = null;
    }
}

// Populates a dropdown using a string with format Value~Name|Value2~Name2|Value3~Name3
function populateDropDown(objDropDown, _delimitedString)
{
    if(!_delimitedString || !objDropDown)
    {
        return;
    }
    // Split the response (Value~Name|Value~Name|Value~Name) up into the individual brands
    var a_AllItems = _delimitedString.split('|');
    if(!a_AllItems || !a_AllItems.length)
    {
        // Unable to parse the delimited string
        return;
    }
    
    for(var i = 0; i < a_AllItems.length; i++)
    {
        // Make sure this row has information
        if(!a_AllItems[i])
        {
            continue;
        }
        
        // Split up the Value~Name into individual elements
        var a_ItemInfo = a_AllItems[i].split('~');
        if(a_ItemInfo.length < 2)
        {
            continue;
        }
                
        // Create a new option element for the dropdown
        var objDropDownOption = document.createElement("option");
        
        // Add the value to the drop down option
        if(a_ItemInfo[0]) { objDropDownOption.setAttribute('value', a_ItemInfo[0]); }
        else { objDropDownOption.setAttribute('value', ''); }
        
        // Add the text to the drop down option
        objDropDownOption.appendChild(document.createTextNode(a_ItemInfo[1]));
        
        // Append the new option to the dropdown
        objDropDown.appendChild(objDropDownOption);
    }
}

//begin add 05/28/2009 by Lester Santiago
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        window.onload = function() {
            oldonload();
            func();
        }
    }
}

function addUnLoadEvent(func) {
    var oldonunload = window.onunload;
    if (typeof window.onunload != 'function') {
        window.onunload = func;
    }
    else {
        window.onunload = function() {
            oldonunload();
            func();
        }
    }
}

function numbersonly(e) {
    var unicode = e.charCode ? e.charCode : e.keyCode;

    //if the key isn't the backspace key (which we should allow)
    if (unicode != 8) {
        //if not a number
        if (unicode < 48 || unicode > 57) {
            //disable key press
            return false;
        } //end if
        else {
            // enable keypress
            return true;
        } //end else
    } //end if
    else {
        // enable keypress
        return true;
    } //end else
} //end function


function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    return '';
}
