var intSelectedSku = mousex = mousey = algor = xMulti = yMulti = 0;
var showZoomTimer;
var largeImgBoxWidth = 580;
var largeImgBoxHeight = 410;
var mainImgBoxHeight = mainImgBoxWidth = 410;
var divPos = null;
var zoomOn = true;
var strOriginal = "";
var intIndexOfSelectShip = 0; //this is for the zip code price update
var intClearanceLeft = 561;
var altImgSection = 0;
var hasWatchedInternalvideo = false;

//////////
// mediaShowTab
//////////
function mediaShowTab(tabId) {
    pTurnOffAllMediaTabs()

    document.getElementById("mediaTab" + tabId).className = "mediaTab"
    document.getElementById("divMContent" + tabId).className = "bBoxG mContent"
}

//////////
// pTurnOffAllMediaTabs
//////////
function pTurnOffAllMediaTabs() {
    if (document.getElementById("mediaTab0")) {
        document.getElementById("mediaTab0").className = "mediaTabOff"
        document.getElementById("divMContent0").className = "mContentOff"
    }
    if (document.getElementById("mediaTab1")) {
        document.getElementById("mediaTab1").className = "mediaTabOff"
        document.getElementById("divMContent1").className = "mContentOff"
    }
}

//////////
// pShowTab
//////////
function pShowTab(tabId) {
    pTurnOffAllTabs()

    document.getElementById("content" + tabId).className = "pContent"
    document.getElementById("pTab" + tabId).className = "pTab"
}

//////////
// pTurnOffAllTabs
//////////
function pTurnOffAllTabs() {
    var maxTab = 5

    for (i = 0; i <= maxTab; i++) {
        document.getElementById("content" + i).className = "pContentOff"
        document.getElementById("pTab" + i).className = "pTabOff"
    }
}

//////////
// startZoom
//////////
function startZoom(waitCount) {
    //Make sure the zoom is ok (showOptions turns it off)
    if (zoomOn) {
        clearTimeout(showZoomTimer)
        showZoomTimer = setTimeout(function () { showZoom(1) }, 300);
    }
}

//////////
// showZoom
//////////
function showZoom(waitCount) {
    //Get the position on the screen
    imgPos = findPos(document.getElementById("imgProduct"))
    divPos = findPos(document.getElementById("divImg"))

    if (waitCount === undefined)
        waitCount = 1

    if (waitCount < 10) {
        //Set ratios
        var imgSmall = document.getElementById("imgProduct")
        var imgZoom = document.getElementById("imgZoom")

        if (document.getElementById("imgZoom").src != "") {
            xMulti = imgZoom.width / imgSmall.width
            yMulti = imgZoom.height / imgSmall.height

            document.getElementById("divZC").style.width = "1px"
            document.getElementById("divZC").style.height = "1px"
            document.getElementById("divZC").style.display = "block"

            if (xMulti > 0) {
                if (xMulti == 1)
                    zoomReset(); //document.getElementById("divZC").style.display = "none"
                else {
                    //Hide img overlays
                    document.getElementById("divImgText").style.display = "none"
                    document.getElementById("divOptImg").style.display = "none"

                    //Just show the image if the ratio is less then 2
                    document.onmousemove = update; // update(event) implied on NS, update(null) implied on IE
                    update();
                }
            }
            else {
                showZoomTimer = setTimeout(function () { showZoom(waitCount + 1) }, 100);
            }
        }
    }
    //Hide the box if it's shown and we reached the loop limit
    else {
        document.getElementById("divZC").style.width = "1px"
        document.getElementById("divZC").style.height = "1px"
        document.getElementById("divZC").style.display = "none"
    }
}

//////////
// stopZoom
//////////
function stopZoom(e) {
    if (divPos == null) {
        return false
    }
    if (mousex == 0 && mousey == 0) {
        return false
    }

    if ((mousex - divPos[0] > 0) && (mousex - divPos[0] < mainImgBoxWidth) && (mousey - divPos[1] > 0) && (mousey - divPos[1] < mainImgBoxHeight)) {
        return false
    }
    document.getElementById("divOptImg").style.display = "none"
    clearTimeout(showZoomTimer)

    zoomReset()
}

//////////
// zoomReset (do not move this into the function above)
//////////
function zoomReset() {
    //Unhide image text
    document.onmousemove = "";

    if (document.getElementById("divImgText").innerHTML != "")
        document.getElementById("divImgText").style.display = "block"
    else
        document.getElementById("divImgText").style.display = "none"

    document.getElementById("divOptImg").style.display = "block"

    document.getElementById("divZoomBox").style.display = "none"
    document.getElementById("divZC").style.display = "none"
    mousex = mousey = 0

    var imgZoom = document.getElementById("imgZoom")
    imgZoom.style.top = 0
    imgZoom.style.left = 0
}

//////////
// getMouseXY
//////////
function getMouseXY(e) // works on IE6,FF,Moz,Opera7
{
    if (!e) e = window.event; // works on IE, but not NS (we rely on NS passing us the event)

    if (e) {
        if (e.pageX || e.pageY) { // this doesn't work on IE6!! (works on FF,Moz,Opera7)
            mousex = e.pageX;
            mousey = e.pageY;
            algor = '[e.pageX]';
            if (e.clientX || e.clientY) algor += ' [e.clientX] '
        }
        else if (e.clientX || e.clientY) { // works on IE6,FF,Moz,Opera7
            mousex = e.clientX + document.documentElement.scrollLeft;
            mousey = e.clientY + document.documentElement.scrollTop;
            algor = '[e.clientX]';
            if (e.pageX || e.pageY) algor += ' [e.pageX] '
        }
    }
}

//////////
// update (Zoom)
//////////
function update(e) {
    if (xMulti == 0) { }
    else {
        var imgSmall = document.getElementById("imgProduct")
        var imgZoom = document.getElementById("imgZoom")

        var divZoomBox = document.getElementById("divZoomBox")
        var vewBody = document.getElementById("vewBody")

        xMulti = imgZoom.width / imgSmall.width
        yMulti = imgZoom.height / imgSmall.height

        getMouseXY(e); // NS is passing (event), while IE is passing (null)

        if ((mousey - divPos[1]) < mainImgBoxHeight && (mousey - divPos[1]) > 0 && (mousex - divPos[0]) > 0 && (mousex - divPos[0]) < mainImgBoxWidth) {
            //Zoom			
            if (imgZoom.width > largeImgBoxWidth || imgZoom.height > largeImgBoxHeight) {
                document.getElementById("divZC").style.display = "block"
                document.getElementById("divZC").style.width = largeImgBoxWidth + "px"
                document.getElementById("divZC").style.height = largeImgBoxHeight + "px"
                document.getElementById("divZC").style.margin = ""

                //Large Image
                imgZoom.style.top = -yMulti * (mousey - imgPos[1]) + (largeImgBoxHeight / 2) + "px"
                imgZoom.style.left = -xMulti * (mousex - imgPos[0]) + (largeImgBoxWidth / 2) + "px"

                //Zoom Box
                divZoomBox.style.display = "block"
                divZoomBox.style.height = largeImgBoxHeight / yMulti + "px"
                divZoomBox.style.width = largeImgBoxWidth / xMulti + "px"
                divZoomBox.style.top = (mousey - divPos[1]) - (largeImgBoxHeight / yMulti / 2) + "px"
                divZoomBox.style.left = (mousex - divPos[0]) - (largeImgBoxWidth / xMulti / 2) + "px"
            }
            //Just show large
            else {
                if (xMulti > 1.1 || yMulti > 1.1) {
                    document.getElementById("divZC").style.display = "block"
                    document.getElementById("divZC").style.width = imgZoom.width + 20 + "px"
                    document.getElementById("divZC").style.height = imgZoom.height + 20 + "px"
                    imgZoom.style.top = "10"
                    imgZoom.style.left = "10"
                }
            }
        }
        else {
            stopZoom()
        }
    }
}

//////////
// findPos
//////////
function findPos(obj) {
    var curleft = curtop = 0;

    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }

    return [curleft, curtop];
}

//////////
// viewPageSwapImage
//////////
function viewPageSwapImage(strImagePath, strAltImgId, strCap, selOrImg) {
    //alert("Img Path: " + strImagePath + "\nImg Id: " + strAltImgId + "\nCaption: " + strCap + "\nselOrImg: " + selOrImg);
    //Hide Video
	if (document.getElementById("player")){
		document.getElementById("player").style.display = "none"
		document.getElementById("player").innerHTML = ""
	}

    //Show Main Img Block
    document.getElementById("divMainImg").style.display = "block"

    zoomOn = true

    var newImg = document.createElement("img")

    newImg.src = strImagePath
    newImg.onLoad = altLoad(newImg)

    updateAltImgBorder(strAltImgId)

    setImgText(strCap, selOrImg)

    updateZoom(strImagePath)
}

//////////
// updateAltImgBorder
//////////
function updateAltImgBorder(strAltImgId) {
    var divAltImgWrapper = document.getElementById("divAltImgWrapper")

    // if there is only one image the wrapping div doesn't exist
    if (divAltImgWrapper) {
        var arrMiniImage = divAltImgWrapper.getElementsByTagName("div")

        for (var i = 0, len = arrMiniImage.length; i < len; i++) {
            if (arrMiniImage[i].id == strAltImgId)
                arrMiniImage[i].style.borderColor = "#993333"
            else
                arrMiniImage[i].style.borderColor = "#ccc"
        }
    }
}

//////////
// updateZoom
//////////
function updateZoom(strImagePath) {
    //Update Zoom Img
    xMulti = 0
    var imgLoad = new Image()
    imgLoad.onerror = function () {loadLarge(strImagePath);}
	
	imgLoad.src = strImagePath.replace(/\/p400\//, "/x/")
	
    if (imgLoad.width > 0 && imgLoad.width < 50) {
		loadLarge(strImagePath)
    }
	else if(imgLoad.width == 0){
		imgLoad.onerror();
	}
    else {
        var imgZoom = document.getElementById("imgZoom")
        imgZoom.src = imgLoad.src

		
		if (document.getElementById("imgZoomButton")){
            document.getElementById("imgZoomButton").innerHTML = "<a href=\"" + imgLoad.src + "\" target=\"_blank\">Move mouse over image to zoom in</a>"
		}
	}
	

}

//////////
// loadLarge
//////////
function loadLarge(strImagePath) {
    var imgLoad = new Image()
    imgLoad.onerror = function () { document.getElementById("imgZoom").src = "";document.getElementById("imgZoomButton").innerHTML = "<a style='text-decoration:underline;color:white;'>Move mouse over image to zoom in</a>";}
    imgLoad.src = strImagePath.replace(/\/p400\//, "/l/")

    var imgZoom = document.getElementById("imgZoom")
    imgZoom.src = imgLoad.src

	var imgSmall = document.getElementById("imgProduct")
    
	if (imgLoad.src != "") {
		if(imgLoad.width / imgSmall.width == 1)
			imgLoad.onerror();
		else if (document.getElementById("imgZoomButton"))
			document.getElementById("imgZoomButton").innerHTML = "<a href=\"" + imgLoad.src + "\" target=\"_blank\">Move mouse over image to zoom in</a>"
	}
}

//////////
// altLoad
//////////
function altLoad(newImg) {
    if (newImg.width == 0 || !newImg.complete)
        window.setTimeout(function () { altLoad(newImg); }, 50);
    else {
        var imgMain = document.getElementById("imgProduct")

        if (newImg.width > 400)
            newImg.width = 400
        if (newImg.height > 400)
            newImg.height = 400

        imgMain.src = newImg.src
        imgMain.width = newImg.width
        imgMain.height = newImg.height
    }
}


//////////
// turn compare price on / off
//////////
function displayComparePrice() {
    var price;
    var curPrice;

    //current price from dropdown
    curPrice = document.getElementById("divPrice").innerHTML;

    //get how many other price comparisons there are

    if (document.getElementById("tblFoundPrices")) {

        var productQty = document.getElementById("tblFoundPrices");
        productQty = productQty.getElementsByTagName("span");

        for (i = 0; i < productQty.length; i++) {
            //get the price for each product
            price = productQty[i].innerHTML;

            //if the shown product price is better than ours or equal, don't show

            // !!!! BUG !!!! There is a bug here. Only one of these elements will ever get generated by the .NET code
            if (price <= curPrice) {
                //document.getElementById("tblFoundPrices").style.display = "none";
                //document.getElementById("seenItForLess").style.display = "block";
            }
            else {
                //document.getElementById("tblFoundPrices").style.display = "block";
                //document.getElementById("seenItForLess").style.display = "none";
            }
        }
    }
}

//////////
// showAddToCart
//////////
function showAddToCart() {
    if (!bolHideAddToCart) {
        //var btnAddToCart = document.getElementById("btnAddToCart")
        //btnAddToCart.src = "//hi.atgimg.com/images/btn/addtocartlg.png"
        if (document.getElementById("lnkAddToCart")) {            
            document.getElementById("lnkAddToCart").className = "l sprite-addtocartlg";
			if (cSku == "0" && intSelectedSku != cSku) {
                document.getElementById("lnkAddToCart").onclick = function () { addToCart(0); return false; }
            }
            else {
                document.getElementById("lnkAddToCart").onclick = function () { openClearanceAjax(cSku); return false; }
            }
            document.getElementById("lnkAddToCart").title = "Add To Cart";
        }
    }
	//Change the Similar Items
	if(document.getElementById("0AddToCart")){
		document.getElementById("0AddToCart").className = "r cfb sprite-addtocartlg";
		document.getElementById("0AddToCart").onclick = function () { addToCartCoord(0); return false; }
	}
	//Change Accessories
	if(document.getElementById("1AddToCart")){
		document.getElementById("1AddToCart").className = "r cfb sprite-addtocartlg";
		document.getElementById("1AddToCart").onclick = function () { addToCartCoord(1); return false; }
	}
	//Change Collections
	if(document.getElementById("2AddToCart")){
		document.getElementById("2AddToCart").className = "r cfb sprite-addtocartlg";
		document.getElementById("2AddToCart").onclick = function () { addToCartCoord(2); return false; }
	}
}

//////////
// showNotify
//////////
function showNotify() {
	document.getElementById("lnkAddToCart").className = "l sprite-notify";
	showNotifyHelper("lnkAddToCart");
	//Change the Similar Items
	if(document.getElementById("0AddToCart")){
		document.getElementById("0AddToCart").className = "r cfb sprite-notify";
		showNotifyHelper("0AddToCart");
	}
	//Change Accessories
	if(document.getElementById("1AddToCart")){
		document.getElementById("1AddToCart").className = "r cfb sprite-notify";
		showNotifyHelper("1AddToCart");
	}
	//Change Collections
	if(document.getElementById("2AddToCart")){
		document.getElementById("2AddToCart").className = "r cfb sprite-notify";
		showNotifyHelper("2AddToCart");
	}
		
    //var btnAddToCart = document.getElementById("btnAddToCart")    
    //btnAddToCart.src = "//hi.atgimg.com/images/btn/notify.png"
    document.getElementById("tdShipInfo").style.display = 'none';
    document.getElementById("personalize").style.display = 'none';
	intClearanceLeft = 624;
}
function showNotifyHelper(id){
	document.getElementById(id).onclick = function () { notifyWhenInStock(intSelectedSku); return false; }
    document.getElementById(id).title = "Notify When In Stock";
}


function showCalcPrice(sku, gId)
{
	if (sku != 0)
	{
		openPopBox(400, 300, "<iframe class='noFrames' width='400' height='300' frameborder='0' src='/products/popBoxCalcPrice.aspx?sku=" + sku + "'></iframe>")
	}
	else
	{
		openPopBox(400, 300, "<iframe class='noFrames' width='400' height='300' frameborder='0' src='/products/popBoxCalcPrice.aspx?groupId=" + gId + "'></iframe>")
	}
}


//////////
// updateProdInfo
//////////
function updateProdInfo() {
    upImgTab('i');
    //If the sku is -1 it's a request to reset the options
    intSelectedSku = arrOpt[strKey].sku
    var leadL = arrOpt[strKey].leadL
    var leadU = arrOpt[strKey].leadU
    var strLead = "days"
    var outOfStock = false;

    if (document.getElementById("optError"))
        document.getElementById("optError").style.display = "none"

    //Stock Info
    var tdStockInfo = document.getElementById("tdStockInfo")
    if (arrOpt[strKey].bo != "") {
        outOfStock = true;
        tdStockInfo.innerHTML = "<span style=\"font-size:12pt;color:#993333;font-weight:bold;\">Out of Stock until " + arrOpt[strKey].bo + "<\/span>"
        tdStockInfo.style.display = "";
		showNotify();
    }
    else if (arrOpt[strKey].mfrStk != "" && arrOpt[strKey].mfrStk != "0" && Math.round(arrOpt[strKey].mfrStk) > -2 && !isObsolete) { //In Stock
        var tdStockInfo = document.getElementById("tdStockInfo")

        //In Stock
        if (arrOpt[strKey].mfrStk == -1 || arrOpt[strKey].mfrStk > 10)
            tdStockInfo.innerHTML = " In Stock";
        else if (arrOpt[strKey].mfrStk > 0 && arrOpt[strKey].mfrStk < 10)
            tdStockInfo.innerHTML = "Only " + arrOpt[strKey].mfrStk + " left";

        var shipTimeCutOffShow = false;
        if (arrOpt[strKey].shipTimeCutOff != "") {
            shipTimeCutOffShow = showCutOffTime();
        }

        showAddToCart()

        document.getElementById("personalize").style.display = 'none';
    }
    //Keep the 0 in quotes
    else if (arrOpt[strKey].mfrStk == "0" || arrOpt[strKey].mfrStk < -1) { //Out of stock and no backorder date
        outOfStock = true;
        tdStockInfo.innerHTML = "<span class=\"fntlb crd\">Out of Stock<\/span>"
        showNotify();
    }
    else { //No backorder and no MFR Stock information
        var tdStockInfo = document.getElementById("tdStockInfo")
        tdStockInfo.style.display = "none";
        showAddToCart();
    }

    //Ship Info
    //alert("stock: " + arrOpt[strKey].mfrStk + "\nshipTime: " + arrOpt[strKey].shipTime + "\nbackorder: " + arrOpt[strKey].bo + "\nshipTimeCutOff: " + shipTimeCutOffShow);

    //Fix for Bug ID: 1536
    //Not out of stock, and has proper ship time
    if (!outOfStock && arrOpt[strKey].shipTime != "" && !shipTimeCutOffShow) {
        document.getElementById("tdShipInfo").style.display = "block";
        document.getElementById("tdShipInfo").innerHTML = '<a href="http://www.atgstores.com/support/shipEstimate.aspx" onclick="openShipEstimate();return false;">Ships ' + arrOpt[strKey].shipTime + "</a>";

        ////////alert(arrOpt[strKey].leadL + " - " + arrOpt[strKey].leadU);
        ////////alert(arrOpt[strKey].ship_via);

        //If lower lead time is great than upper, reset upper
//            var lower = arrOpt[strKey].leadL;
//            var upper = arrOpt[strKey].leadU;

//            if (lower >= upper)
//                upper = lower;

        ////////alert(intGId);

        //If shipped 'Ground' or is Out of Stock, don't display
        if (arrOpt[strKey].ship_via != "Ground" && arrOpt[strKey].ship_via != "ground")
            document.getElementById("tdShipInfo").innerHTML += "<br /><a href=# onclick=\"showEstimatedDelivery(); return false;\">Delivery Estimate</a>";
    }
    else if(!shipTimeCutOffShow)
    {
        document.getElementById("tdShipInfo").style.display = "none";
    }

	//Description
	if (arrOpt[strKey].desc == "")
		document.getElementById("spnSkuDesc").innerHTML = ""
	else
		document.getElementById("spnSkuDesc").innerHTML = arrOpt[strKey].desc

	//Pack Qty
	if (arrOpt[strKey].packQty > 1)
		document.getElementById("spnSkuDesc").innerHTML += "<table><tr><td style=\"width: 100px; vertical-align: top\"><strong>Quantity</strong></td><td>" + arrOpt[strKey].packQty + "</td></tr></table>"

	//Part Number
	if (document.getElementById("spnPartNumber")) {
		document.getElementById("spnPartNumber").innerHTML = arrOpt[strKey].sku + "S";
		var patt = new RegExp("Sku=[0-9]*", "gi"); //change the sku for the internal emailContent and emailBizDev
		if (document.getElementById("emailContent"))
			document.getElementById("emailContent").href = document.getElementById("emailContent").href.replace(patt, "Sku=" + arrOpt[strKey].sku);

		if (document.getElementById("emailBizDev"))
			document.getElementById("emailBizDev").href = document.getElementById("emailBizDev").href.replace(patt, "Sku=" + arrOpt[strKey].sku);

		if (document.getElementById("priceHistory"))
			document.getElementById("priceHistory").href = document.getElementById("priceHistory").href.replace(patt, "Sku=" + arrOpt[strKey].sku);
	}

	//Mfr Part Number
	document.getElementById("tdMfrProdId").innerHTML = arrOpt[strKey].partNo

	//UPC
	if (arrOpt[strKey].upc == '') {
		document.getElementById("trUpc").style.display = "none";
	}
	else {
		document.getElementById("trUpcValue").innerHTML = arrOpt[strKey].upc;
		document.getElementById("trUpc").style.display = "";
		//document.getElementById("upc2").innerHTML = "<strong>UPC</strong>: " + arrOpt[strKey].upc + "<br />";
	}

	if (!bolHidePrice) {
		//Price
		document.getElementById("divPrice").innerHTML = toCurrency(arrOpt[strKey].price)

		//check if we need to hide comparison price?
		displayComparePrice()

		//Shipping
		if (arrOpt[strKey].cShip > 0) {
		    document.getElementById("divShipping").style.display = 'block';
		    document.getElementById("divShipping").innerHTML = " + " + toCurrency(arrOpt[strKey].cShip) + " shipping"
		}
		else if (arrOpt[strKey].price < 29.99) {
		    document.getElementById("divShipping").style.display = 'block';
		    document.getElementById("divShipping").innerHTML = "" //" + $6.99 shipping on orders less than $29.99"
		}
		else if (arrOpt[strKey].mfrStk != "0" && arrOpt[strKey].ship_via == "FreeTrk") { //White Glove Shipping               
		    if (document.getElementById("selShip") != null/* && arrOpt[strKey].site == "hfs"*/) {
		        //also make changes to the changeShip function
		        document.getElementById("divShipping").innerHTML = " + " + document.getElementById("selShip").options[document.getElementById("selShip").selectedIndex].text.replace(/\(.*/gi, '');
		    }
		    else if(arrOpt[strKey].ship_via.toLowerCase() == "freetrk" || arrOpt[strKey].ship_via.toLowerCase() == "freight"){
		        document.getElementById("divShipping").innerHTML = " + Free Delivery";
		    }
			else{
				document.getElementById("divShipping").innerHTML = " + Free Shipping";
			}
		}
		else if (arrOpt[strKey].mfrStk == "0" && document.getElementById("divShipping").innerHTML != " + Free Shipping") {
		    document.getElementById("divShipping").innerHTML = "";
		}

		//You Save
		document.getElementById("spnSave").innerHTML = toCurrency(arrOpt[strKey].msrp - arrOpt[strKey].price)

		//MSRP
		document.getElementById("divMSRP").innerHTML = toCurrency(arrOpt[strKey].msrp)
	}

    //Internal Info
    if (document.getElementById("spnIntPart")) {
    
        document.getElementById("spnIntPart").innerHTML = arrOpt[strKey].partNo

        if (document.getElementById("spnIntCost")) {
            document.getElementById("spnIntCost").innerHTML = toCurrency(arrOpt[strKey].ac) 
        }
    
        if (document.getElementById("calcPrice")) {
            var retail = document.getElementById("divPrice").innerHTML;
			document.getElementById("calcPrice").innerHTML = "Retail Price: " + retail + " <br /><a style='cursor: pointer;' onclick='showCalcPrice(" + intSelectedSku + ", 0)'>show how the retail price is calculated</a><br /><br />"
        }


        if (document.getElementById("spnIntShip")) {
            document.getElementById("spnIntShip").innerHTML = toCurrency(arrOpt[strKey].ship) 
        }
    
        if (document.getElementById("spnIntMargin")) {
            if (arrOpt[strKey].price > 29.99) {
                document.getElementById("spnIntMargin").innerHTML = toCurrency(arrOpt[strKey].price - arrOpt[strKey].ac - arrOpt[strKey].ship - stripCurrency(document.getElementById("spnIntDrop").innerHTML)) 
            }
            else {
                document.getElementById("spnIntMargin").innerHTML = toCurrency(arrOpt[strKey].price + 6.99 - arrOpt[strKey].ac - arrOpt[strKey].ship - stripCurrency(document.getElementById("spnIntDrop").innerHTML)) 
            }
        }
    
        if (document.getElementById("internalShip")) {
            if (arrOpt[strKey].mfrStk == -1 || arrOpt[strKey].mfrStk == 1000) {
                document.getElementById("internalShip").innerHTML = "Mfr Indicates in stock"; 
            }
            else {
                document.getElementById("internalShip").innerHTML = arrOpt[strKey].mfrStk 
            }
        }
    }

    //Swap Image
	viewPageSwapImage("//hi.atgimg.com/img/p400/" + intMfrId + "/" + arrOpt[strKey].img, "", arrOpt[strKey].imgT, 0)

	//Show swatch options if the image show is the group image
	//if (strGroupImg == intMfrId + "/" + arrOpt[strKey].img && arrOpt[strKey].oImg != "") {
	if (arrOpt[strKey].oImg != "") {
	    showOptImg(arrOpt[strKey].oImg)
	}
	else
	    document.getElementById("divOptImg").innerHTML = ""    

	//Dimensions
    ////////alert(gDim);
    ////////alert(arrOpt[strKey].d);
    if (arrOpt[strKey].d != "" && !gDim) {
        ////////alert(arrOpt[strKey].d);
		var arrDim = arrOpt[strKey].d.split('|');
		var tblDim = document.getElementById("tblDim")
		removeDim(tblDim)
		//arrDim.sort()
		for (var i = 0, len = arrDim.length; i < len; i++) {
            ////////alert(arrDim[i]);
			var addDimValue = arrDim[i].split(":")
			var row = tblDim.insertRow(tblDim.rows.length)
			row.className = "trDim"

			var cellLeft = row.insertCell(0);
			cellLeft.innerHTML = "<strong>" + addDimValue[0] + "</strong>"
			cellLeft.style.width = "100px"
			var cellRight = row.insertCell(1);
			if(addDimValue[1])
			    cellRight.innerHTML = addDimValue[1].replace(/\"/g, " inches")
        }
	}
    else if (!gDim) {
        removeDim(document.getElementById("tblDim"))
    }

    ////alert(document.getElementById("tblSpec").innerHTML);

    //Clearance
    if (Math.round(arrOpt[strKey].clearancePrice) != 0 /* && document.getElementById("clearanceViewPageDiv").innerHTML == ""*/) //if there is a clearancePrice but the div is empty
    {
		document.getElementById("clearanceViewPageDiv").style.left = intClearanceLeft + "px";
		
		if (!document.getElementById("noReturn"))
            document.getElementById("clearanceViewPageDiv").innerHTML = "<span class='fntsb cgl' style='width:100px;'>Also Available</span><div style='margin-top: -4px; width: 250px;'><img src='//hi.atgimg.com/images/layout/boxsm.png' alt='Open Box Item'> <span style='font-weight: normal;font-size:9pt;'> Open Box - </span><strong id='clearancePrice'>" + toCurrency(arrOpt[strKey].clearancePrice) + "</strong> <a href='javascript:void(0)' onClick='openClearanceAjax(0)'><img style='vertical-align: text-bottom;' src='//hi.atgimg.com/images/btn/addtocartwh.png' alt='Add to Cart Clearance'></a></div><div class='bBox' id='clearanceDivBBox' style='min-height: 176px; display: none; padding: 0px; position:absolute; width: 546px; top: -97px; left: -149px;z-index: 1000;'><div class='tlb'></div><div class='trb'></div><div id='clearanceDiv'><br /><br /></div><div class='blb'></div><div class='brb'></div></div>";
        else {
            document.getElementById("clearanceViewPageDiv").innerHTML = "<span class='fntsb cgl' style='width:100px;'>Also Available</span><div style='margin-top: -4px; width: 250px;'><img src='//hi.atgimg.com/images/layout/boxsm.png' alt='Open Box Item'> <span style='font-weight: normal;font-size:9pt;'> Open Box - </span><strong id='clearancePrice'>" + toCurrency(arrOpt[strKey].clearancePrice) + "</strong><br /><a href='javascript:void(0)' onClick='openClearanceAjax(0)'><img style='vertical-align: text-bottom;' src='//hi.atgimg.com/images/btn/addtocartwh.png' alt='Add to Cart Clearance'></a></div><div class='bBox' id='clearanceDivBBox' style='min-height: 176px; display: none; padding: 0px; position:absolute; width: 546px; top: -97px; left: -149px;z-index: 1000;'><div class='tlb'></div><div class='trb'></div><div id='clearanceDiv'><br /><br /></div><div class='blb'></div><div class='brb'></div></div>";
            document.getElementById("clearanceViewPageDiv").style.marginLeft = "233px";
        }
        
        document.getElementById("clearanceViewPageDiv").style.display = "inline"
	}
    else{
	    document.getElementById("clearanceViewPageDiv").style.display = "none";  //hide the div if we don't have a clearance item
	    document.getElementById("clearanceViewPageDiv").innerHTML = "";
	}

	if (document.getElementById("clearancePrice") != null) {
		document.getElementById("clearancePrice").innerHTML = toCurrency(arrOpt[strKey].clearancePrice);
	}

    //Coordinating Items
	if (document.getElementById("0price999")) {
	    document.getElementById("0price999").innerHTML = toCurrency(arrOpt[strKey].price);
	}
	//Accessories
	if (document.getElementById("1price999")) {
	    document.getElementById("1price999").innerHTML = toCurrency(arrOpt[strKey].price);
	}
}

//////////
// getSup
/////////
function getSup(intNum) {
    if (intNum == 1 || intNum == 21 || intNum == 31) {
        return "st";
    }
    else if (intNum == 2 || intNum == 22) {
        return "nd";
    }
    else if (intNum == 3 || intNum == 23) {
        return "rd";
    }
    else {
        return "th";
    }
}

function showEstimatedDelivery() {
    var inStock = 0;
    if (arrOpt[strKey].mfrStk > 0)
        inStock = arrOpt[strKey].mfrStk;

    var shipData = "Free Shipping";
    if (document.getElementById("selShip") != null)
        shipData = document.getElementById("selShip")[document.getElementById("selShip").selectedIndex].innerHTML;
    ////////alert(shipData);

    ////alert("blackbox/ajax/deliveryEstimateAjax.aspx?prodName=" + groupName + "&mfr=" + mfrName + "&groupId=" + intGId + "&sku=" + arrOpt[strKey].sku + "&partNo=" + arrOpt[strKey].partNo + "&leadLower=" + arrOpt[strKey].leadL + "&leadUpper=" + arrOpt[strKey].leadU + "&inStock=" + inStock + "&shipTime=" + arrOpt[strKey].shipTime + "&shipType=" + escape(shipData));
    var ajaxReqObj = new ajaxRequestObject("/ajax/deliveryEstimateAjax.aspx", "prodName=" + groupName + "&mfr=" + mfrName + "&groupId=" + intGId + "&sku=" + arrOpt[strKey].sku + "&partNo=" + arrOpt[strKey].partNo + "&leadLower=" + arrOpt[strKey].leadL + "&leadUpper=" + arrOpt[strKey].leadU + "&inStock=" + inStock + "&shipTime=" + arrOpt[strKey].shipTime + "&shipType=" + escape(shipData), showEstimate);
    ajaxReqObj.doGetCallback();

    //http://blackbox/products/deliveryEstimateAjax.aspx?prodName=Jackson+Furniture+4366-03-1915+Mesa+Sofa+Full+Length+Couch+&mfr=Jackson+Furniture&groupId=888257&sku=7274066&partNo=4366-03-1915-09&leadLower=7&leadUpper=14&inStock=0&shipTime=Dec+9th+-+Dec+16th&shipType=Free+Delivery&rand=1322693518209
    //http://blackbox/ajax/deliveryEstimateAjax.aspx?prodName=Jackson%20Furniture%204366-03-1915%20Mesa%20Sofa%20Full%20Length%20Couch%20&mfr=Jackson%20Furniture&groupId=888257&sku=7274066&partNo=4366-03-1915-09&leadLower=7&leadUpper=14&inStock=0&shipTime=Dec%209th%20-%20Dec%2016th&shipType=Inside%20Delivery%20Room%20of%20Choice%20%28%2479.99%29

}

function showEstimate(strFill) {
    openPopBox(700, 700, strFill);
    document.getElementById("popBox").style.height = 'auto'; 
    //Eliran & Dmitry vs Max & Aaron = 1 - 10
    //Eliran & Dmitry vs Max & Aleks = 10 - 9

    var curZip = readCookie("custzipcode");
    if (curZip != null && curZip != '')
    {
        document.getElementById("addressTxt").value = curZip;
        var ajaxReqObj = new ajaxRequestObject("/ajax/getAddressAjax.aspx", "zip=" + curZip, updateAddress);
        ajaxReqObj.doGetCallback();
    }
}

//function editAddress() {
//    document.getElementById("addressLbl").style.display = "none";
//    document.getElementById("changeBtn").style.display = "none";
//    document.getElementById("addressTxt").style.display = "block";
//    document.getElementById("addressBtn").style.display = "block";
//}

function changeAddress() {
//    document.getElementById("addressLbl").style.display = "block";
//    document.getElementById("changeBtn").style.display = "block";
//    document.getElementById("addressTxt").style.display = "none";
//    document.getElementById("addressBtn").style.display = "none";
    var zip = document.getElementById("addressTxt").value;

    if (zip.match(/^[0-9]{5}$/g))
    {
        SetCookie("custzipcode", zip, 30);
        var ajaxReqObj = new ajaxRequestObject("/ajax/getAddressAjax.aspx", "zip=" + zip, updateAddress);
        ajaxReqObj.doGetCallback();
    }
    else
    {
        document.getElementById("addressLbl").innerHTML = "<font style=\"color:red\">Enter a proper zip code</font>";
        document.getElementById("estimatedDelivery").style.display = "none";
    }
}

function updateAddress(strFill)
{
    ////alert(strFill);
    document.getElementById("addressLbl").innerHTML = strFill;
    if (strFill.match(/Enter a proper zip code/gi))
    {
        document.getElementById("estimatedDelivery").style.display = "none";
    }
    else
    {   
        document.getElementById("estimatedDelivery").style.display = "block";
    }
}

//////////
// scrollImage
//////////
function scrollImage(dir)
{
    ////////alert(altImgSectionCount);
    if (dir == 'left')
        altImgSection--;
    else
        altImgSection++;

    altImgSection = altImgSection < 0 ? altImgSectionCount - 1 : altImgSection >= altImgSectionCount ? 0 : altImgSection;

    imgArr = document.getElementById("altImageScrollbar");
    imgArr.innerHTML = '';

    //var str = '';
    var index = 0;
    for (var i = 0; i < 7; i++)
    {
        index = 7 * altImgSection + i;
        if (index < altImgCount)
        {
            if (index == 0)
            {
                imgArr.innerHTML += '<div class="altImg" id="altImg' + i + '"><img src="' + defMiniPath + "\" height=\"40px\" onmouseover=\"viewPageSwapImage('" + defPath + "', 'altImg" + i + "', '', 1)\" onclick=\"changeSku('')\"></div>"
            }
            else
            {
                imgArr.innerHTML += '<div class="altImg" id="altImg' + i + '"><img src="' + arrAltImg[index - 1].image + "\" height=\"40px\" onmouseover=\"viewPageSwapImage('" + arrAltImg[index - 1].image.replace(/\/t\//, /p400/).replace(/\/m\//, /p400/) + "', 'altImg" + i + "', '" + arrAltImg[index - 1].caption + "', 1)\" onclick=\"changeSku('" + arrAltImg[index - 1].sku + "')\"></div>"
            }
            //str += 7 * altImgSection + i +',';
        }
    }
    ////////alert(altImgCount);
    var pageMin = (altImgSection) * 7 + 1;
    var pageMax = (altImgSection) * 7 + 7;
    pageMax = pageMax > altImgCount ? altImgCount : pageMax;
    document.getElementById("pageNumber").innerHTML = "<div class=\"fnts\">" + pageMin + " - " + pageMax + " of " + altImgCount + "</div>";
    ////////alert("section: " + altImgSection + " --- indeces: " + str);

    ////////alert(dir);
}

function changeSku(sku)//, strImagePath, strAltImgId, strCap, selOrImg)
{   
    ////////alert(sku.toString());
    ////////alert(arrOptions[sku.toString()].optionKey);
	if(sku != "")
		setOptionKey(arrOptions[sku.toString()].optionKey.replace(/-/g, '::'));
	else
    {
        var strDefaultKey = "";
        var i = 0;
        while (document.getElementById("selOpt" + i) != null)
        {
            strDefaultKey += "0::";
            i++;
        }
        strDefaultKey = strDefaultKey.substr(0, strDefaultKey.length - 2);
        //////alert(strDefaultKey);
		setOptionKey(strDefaultKey);
    }
}

function remakeVid(groupID)
{
    document.getElementById("vidReportButton").innerHTML = "<font style=\"color:green\">This video has been reported</font>";

    var ajaxReqObj = new ajaxRequestObjectCache("/ajax/remakeVideoAjax.aspx", "group_id=" + groupID, '');
    ajaxReqObj.doGetCallback();
}

//////////
// changeShip
/////////
function changeShip(value) {
    //also make changes in the updateProdInfo
    if (arrOpt[strKey] == null || arrOpt[strKey].mfrStk != 0)
        document.getElementById("divShipping").innerHTML = " + " + document.getElementById("selShip").options[document.getElementById("selShip").selectedIndex].text.replace(/\(.*/gi, '');
}

//////////
// clearSelect
//////////
function clearSelect() {

    intSelectedSku = 0

    document.getElementById("spnPartNumber").innerHTML = intGId + "G"
    document.getElementById("spnSkuDesc").innerHTML = ""
    document.getElementById("tdStockInfo").innerHTML = ""
    document.getElementById("tdShipInfo").innerHTML = ""
    document.getElementById("tdShipInfo").style.display = "block"
    document.getElementById("clearanceViewPageDiv").style.display = "none"

    var retailPrice = document.getElementById("divPrice").innerHTML;

     if (document.getElementById("calcPrice")) {
          document.getElementById("calcPrice").innerHTML = "Retail Price: " + retailPrice + " <br /><a style='cursor: pointer;' onclick='showCalcPrice(0," + intGId + ")'>show how the retail price is calculated</a><br><br>"
        }


    if (document.getElementById("tblDim")) {
        var tblDim = document.getElementById("tblDim")
        if (!gDim) {
            removeDim(tblDim)

            var row = tblDim.insertRow(tblDim.rows.length)
            row.className = "trDim"

            var cellLeft = row.insertCell(0);
            cellLeft.innerHTML = "<a href=\"#\" onclick=\"addToCart(0)\">Select options to see dimensions</a>"
        }
    }
	
    viewPageSwapImage(defPath, "", defImgTxt, 0);
    //viewPageSwapImage("//hi.atgimg.com/img/p400/" + strGroupImg, "", defImgTxt, 0);
}

//////////
// removeDim
//////////
function removeDim(tblDim) {
    if (tblDim) {
        for (i = tblDim.rows.length - 1; i >= 0; i--) {
            tblDim.deleteRow(i);
        }
    }
}

//////////
// showOptImg
//////////
function showOptImg(strOptImg) {
    var arrOptImg = strOptImg.split("|")
    var strOpt = ""

    for (var i = 0, len = arrOptImg.length; i < len - 1; i++) {
        strOpt += "<div class=\"bBox\" style=\"width:60px;height:60px;padding:3px;margin-bottom:5px;\"><img src=\"http:\/\/hi.atgimg.com\/images\/options\/image\/" + arrOptImg[i] + "\" width=\"60px\" height=\"60px\"></div>"
    }

    document.getElementById("divOptImg").innerHTML = strOpt
}

//////////
// setImgText
//////////
function setImgText(strText, selOrImg) {
    ////alert("strText: " + strText + "selOrImg: " + selOrImg);

    if (strText != "")
    {
        document.getElementById("divImgText").innerHTML = strText
        document.getElementById("divImgText").style.display = "block"
    }
    else
    {
        document.getElementById("divImgText").innerHTML = "";
        document.getElementById("divImgText").style.display = "none"
    }




//    //selOrImg: if it's 0 then its called by the select boxes; 1 is the mouseover images below
//    if (selOrImg == 0) {
//        if (strText != "") {
//            document.getElementById("divImgText").innerHTML = strText
//            document.getElementById("divImgText").style.display = "block"
//        }
//        else if (defImgTxt != "") {
//            document.getElementById("divImgText").innerHTML = defImgTxt
//            document.getElementById("divImgText").style.display = "block"
//        }
//        else
//            document.getElementById("divImgText").style.display = "none"
//    }
//    else {
//        if (strText != "")
//        {
//            document.getElementById("divImgText").innerHTML = strText;
//            document.getElementById("divImgText").style.display = "block"
//        }
//        else
//        {
//            document.getElementById("divImgText").innerHTML = "";
//            document.getElementById("divImgText").style.display = "none"
//        }
//    }
}

//////////
// notifyWhenInStock
//////////
function notifyWhenInStock(intSku) {
    openPopBox(400, 300, "<iframe src='" + strSecurePath + "/products/notifyWhenInStock.aspx?sku=" + intSku + "' width='400px' height='300px' scrolling='no' frameBorder='0'></iframe>");
    //window.open(strSecurePath + '/products/notifyWhenInStock.aspx?sku=' + intSku, 'NotifyInStock', 'scrollbars=no, resizeable=no, toolbar=no, menubar=no, location=no, directories=no, width=400, height=275');
}

//////////
// addToCart
//////////
function addToCart(intGroupId) {
    if(hasWatchedInternalvideo){
		track("internalFlashVideo", window.location.href, 2);
	}
		
	var qty = document.getElementById("tbxQty").value.replace(/[^0-9]*/g, "")

	//Treepodia Loggin
	if (typeof Treepodia  != "undefined"){
		try { Treepodia.getProduct('UA-HOMEFURNITURE', intGId.toString()).logAddToCart(); } catch (e) {} 
	}
	
    if (qty == "")
        qty = 1

    var gaStr
    try {
        _gaq.push(function () {
            var tracker = _gaq._getAsyncTracker();
            gaStr = tracker._getLinkerUrl(strSecurePath + '/cart/addToCart.aspx');
        });
    } catch (cb) { }
    if (!gaStr) {
        gaStr = strSecurePath + "/cart/addToCart.aspx?"
        //gaStr = "blackbox/cart/addToCart.aspx?"        
    }
	
	var shipOpt = "";
    if (document.getElementById("selShip") != null)
        shipOpt = document.getElementById("selShip").value;
    var u;

    if (intSelectedSku > 0) {
        if (intGroupId == 0)
            u = gaStr + "&sku=" + intSelectedSku + "&qty=" + qty + "&shipOpt=" + shipOpt + getABTestCookieInfo();
        else
            u = gaStr + "&sku=" + intSelectedSku + "&qty=" + qty + "&alsoAdd=" + intGroupId + "&shipOpt=" + shipOpt + getABTestCookieInfo();
        
		window.location = u;
    }
    else {
		//Try to see if the select boxes are actually selected: BUG#1172
		var intSelNum = 0;
		var key = "";
		while(document.getElementById("selOpt" + intSelNum)){
			if(intSelNum == 0)
				key = document.getElementById("selOpt" + intSelNum).selectedIndex;
			else
				key += "::" + document.getElementById("selOpt" + intSelNum).selectedIndex;
			intSelNum++;
		}
		if(arrOpt[key]){
			intSelectedSku = arrOpt[key].sku;
			addToCart(0);
		}
		showOptError();
    }
    return false;
}

//////////
// showOptError
//////////
function showOptError(){

   if (document.getElementById("optError") != null) {
            document.getElementById("optError").style.display = "block";
            window.scrollTo(0, 0);
	}
   
}


function checkSelection()
{
    if (intSelectedSku < 1)
    {   showOptError();
        return false;
    }
    else {return true};
}




//////////
// viewOpt
//////////
function viewOpt(intGroupId) {
    document.getElementById("divOptionOverlay").style.display = "block"
    document.getElementById("divOptionOverlayContent").innerHTML = "<div class=\"bBox wtog cg\" style=\"position:absolute;top:225px;left:400px;font-size:12pt;font-weight:bold;width:150px;height:60px;padding:10px;\"><div class=\"tlb\"></div><div class=\"trb\"></div><img src=\"\/\/hi.atgimg.com\/images\/loading.gif\" style=\"vertical-align:middle;padding-right:10px;\"> Loading ...<div class=\"blb\"></div><div class=\"brb\"></div></div>"
    zoomOn = false

    var ajaxReqObj = new ajaxRequestObjectCache("/ajax/optDisplay.aspx", "v=12&groupId=" + intGroupId, displayOpt);
    ajaxReqObj.doGetCallback();
}

//////////
// displayOpt
//////////

      
function displayOpt(strResult) {
    document.getElementById("divOptionOverlayContent").innerHTML = strResult
}

//////////
// viewVideo (loadVideo)
//////////

//http://sa.atgstores.com/media/createdvideos/videos/1000/1791/productgroupid450997.flv
//http://sa.atgstores.com/media/createdvideos/videos/0/163/productgroupid486651.flv
//http://sa.atgstores.com/media/createdvideos/videos/0/4/productgroupid140.flv
//http://hi.atgimg.com/img/p400/4/bo205al.jpg
function viewVideo(mediaType, path, code, title, poster, videoType) {
   ////////alert(poster);
    var img;
    if (poster == "") {
        img = document.getElementById("divMainImg").innerHTML.replace(/.*src="([^"]*).*/gi, '$1');
        ////////alert(img);
        //img = img.replace(/([0-9A-Za-z .\/:]*)/gi, '$1');
        img = img.replace(/%20/g, ' ').replace(/[^ a-z0-9:/._-]*/gi, '');
        //http://hi.atgimg.com/img/p400/7/2145_family.jpg
        ////////alert(img);
    }
    else
        img = "http://hi.atgimg.com" + poster;
    ////////alert("MediaType: " + mediaType + "\nPath: " + path + "\nCode: " + code + "\nTitle: " + title + "\nPoster: " + poster);
    ////////alert(img); 
    if (path != "") {
        updateAltImgBorder("");
        zoomOn = false;
        //Hide the image
        document.getElementById("divMainImg").style.display = "none";
        //Hide Treepodia
        document.getElementById("treepodiaPlayer").style.display = "none";
        //Hide Product Banner
        //Show video container
        document.getElementById("player").style.display = "block";
        if (document.getElementById("zoomButton")) {
            document.getElementById("zoomButton").innerHTML = title;
        }

        if (mediaType == "video") {
            ////////alert("video");
            document.getElementById("player").style.paddingTop = "0px"
            document.getElementById("player").innerHTML = ""

            flowplayer("player", "http://hi.atgimg.com/img/media/flowplayer-3.2.7.swf", {
                clip: {
                    autoPlay: true		// aplies to all Clips in the playlist
                },
                playlist: [				// an array of Clip objects
                // show initial image
					{url: 'http://hi.atgimg.com/img/p400/' + strGroupImg, scaling: 'orig' },

                // add video
					{url: 'http://hi.atgimg.com/' + path, scaling: 'fit', autoPlay: false }
				]
            });

            document.getElementById("player").innerHTML = title
        }
        else if (mediaType == "code") {
            ////////alert("code");
            var w = 0;
            var h = 0;
            var reW = new RegExp("width=[^0-9]*([0-9]*)");
            var reH = new RegExp("height=[^0-9]*([0-9]*)");
            var matches = code.match(reW)

            if (matches[1])
                w = matches[1]

            var matches = code.match(reH)

            if (matches[1]) {
                h = matches[1]
                hScale = parseInt(400 / parseInt(w) * h)
            }

            if (w > 0 && h > 0) {
                reW = new RegExp(w, "g");
                reH = new RegExp(h, "g");

                code = code.replace(reW, "400")
                code = code.replace(reH, hScale)
            }

            document.getElementById("player").style.paddingTop = (400 - hScale) / 2 + "px"
            document.getElementById("player").innerHTML = code
        }
        else if (mediaType == "flash") {
            ////////alert("flash");
            ////////alert(img);
            flowplayer("player", 
                {src: "http://hi.atgimg.com/img/media/flowplayer.unlimited-3.2.7.swf", wmode: "transparent"}, 
                { plugins: {
                    controls: {         //The control layout
                        //url: 'http://hi.atgimg.com/img/media/flowplayer.controls-3.2.5.swf',

                        buttonColor: 'rgba(0, 0, 0, 0.9)',
                        buttonOverColor: '#00FF00',
                        backgroundColor: 'transparent',
                        backgroundGradient: 'none',
                        sliderColor: '#0000FF',

                        sliderBorder: '1px solid #808080',
                        volumeSliderColor: '#FFFFFF',
                        volumeBorder: '1px dotted #808080',

                        timeColor: '#000000',
                        durationColor: '#535353'
                    }
                },
                //key: 'b80b380c3a7a4af42c3',       //www.atgstores.com
                //key: 'd31c761f5189b9a3577',       //atgstores.com
                //key: '182e07d2161cb625c20',       //lightinguniverse.com
                //key: '9370f83a2b913eb75f4',       //www.lightinguniverse.com
                //key: '9067796357cb32c28d3',       //blackbox
                key: flowplayerKey,                 //dynamically created key
//                logo: {
//                    url: 'http://hi.atgimg.com/images/layout/atgs_logo.png',
//                    fullscreenOnly: false,
//                    top: '85%',
//                    left: '25%'
//                },
                play: {
                    //url: 'http://hi.atgimg.com/images/layout/atgs_logo.png',
                    opacity: .9,
                    replayLabel: null,
                    width: 40,
                    height: 40
                },
                clip: {
                    autoPlay: true		// aplies to all Clips in the playlist
                },
                canvas: {               //The canvas layout within the container
                    padding: '50px',
                    backgroundGradient: 'none',
                    border: '2px solid #778899'
                },
                screen: {               //The screen layout within the canvas
                    width: 400,
                    height: 400,
                    top: 0,
                    right: 0
                },
                playlist: [				// an array of Clip objects
                    {url: img, scaling: 'fit' },   // show initial image
					{url: path, scaling: 'fit', autoPlay: false}   // add video
				]
            }).ipad();
        }
    }
	if(videoType = 1){
		hasWatchedInternalvideo = true;
   }
}


//////////
// hideOpt
//////////
function hideOpt() {
    document.getElementById("divOptionOverlay").style.display = "none"

    zoomOn = true
}

//////////
// updateLink
//////////
function updateLink(curLink) {
    if (intSelectedSku > 0) {
        curLink.href = curLink.href.replace(/sku=[0-9]*/, "sku=" + intSelectedSku)
    }
    else {
        curLink.href = curLink.href.replace(/sku=[0-9]*/, "sku=" + intBaseSku)
    }
}


//////////
// Wish List
//////////
function addToList() {
    
    ////////alert(intSelectedSku);
    //showOptError();

    var selectedSku;
    var qty;

    //get the product
    if (intSelectedSku > 0) {selectedSku = intSelectedSku;}
    else {selectedSku =  intBaseSku;}

    //get the quantity
    qty = document.getElementById("tbxQty").value.replace(/[^0-9]*/g, "")
    if (qty == "") { qty = 1 }

    //test output
    ////////alert("sku selected: " + selectedSku + " ; qty: " + qty)
    
    //load iframe and pass both variables along
    openPopBox(460, 240, '<iframe style=\'border: none; width: 460px; height: 240px;\' frameborder=\'0\' src=\'/account/showWishLists.aspx?sku=' + selectedSku + '&qty=' + qty + '\' id=\'iLogin\'></iframe>');

}



//////////
// submitQA
//////////
function submitQA() {
    var strMsg = ""

    //Error Checking
    if (document.getElementById("tbxQAQuestion").value.length < 10)
        strMsg = "Your question is too short. (10 characters minimum)<br>"

    if (document.getElementById("tbxQAName").value == "" || document.getElementById("tbxQAEmail").value == "")
        strMsg += "Please provide your name and email so we can email you a response<br>"

    if (strMsg != "") {
        document.getElementById("divQAMsg").innerHTML = "<div style=\"color:#993333;font-weight:bold;margin:10px 0px;\">" + strMsg + "</div>"
    }
    else {
        var s = 0

        if (intSelectedSku > 0)
            s = intSelectedSku
        else
            s = intBaseSku

        document.getElementById("divQAMsg").value = "Type your question here..."
        document.getElementById("divQABox").style.display = "none"

        document.getElementById("divQAMsg").innerHTML = "<div style=\"color:#006600;font-weight:bold;margin:10px 0px;\">Thank you for your question. You should expect a response in 1 to 3 days.</div>"
        var ajaxReqObj = new ajaxRequestObjectCache("/ajax/createSupport.aspx", "s=" + s + "&q=" + document.getElementById("tbxQAQuestion").value + "&n=" + document.getElementById("tbxQAName").value + "&e=" + document.getElementById("tbxQAEmail").value);
        ajaxReqObj.doGetCallback();
    }
}

//////////
// updateSelect
//////////

//function updateSingleSelect(intCurrentSelect) {
//    //if all the options have already been selected, set the current selected option to 0
//    //and then run the rebuild select boxes function - this will clear out the options in the selected
//    //box to show which options can be selected with other options
//  
//    if (document.getElementById("selOpt" + intCurrentSelect).value != 0) {
//        //document.getElementById("selOpt" + intCurrentSelect).selectedIndex = 0;
//        rebuildSelect(intCurrentSelect);
//        //add onmouseouts
//        //document.getElementById("selOpt" + intCurrentSelect).onMouseOut = reselectOption(intCurrentSelect, document.getElementById("selOpt" + intCurrentSelect).selectedIndex);
//    }
//}

//function updateSelectNew(intCurrentSelect){
//    strKey = ""
//	/*rebuildSelect(intCurrentSelect)
//	//Build the key
//	for (var i = 0; i < 8; i++){
//        if (document.getElementById("selOpt" + i)){
//            if (strKey != "")
//				strKey += "::"
//			
//			strKey += document.getElementById("selOpt" + i).value
//		}
//		else
//			break;
//	}

//	if (arrOpt[strKey])
//		updateProdInfo()
//	else
//		clearSelect()*/
//    strKey = rebuildSelect(intCurrentSelect);

//    if (arrOpt[strKey] != undefined) {
//        updateProdInfo()
//    }
//    else {
//        clearSelect()
//    }

//}

///*v2 non-stable rebuildselect */
//var blackedOut;
//var selectedIndexes; //this is an array of the selected optionids used when the user selects a grayed option
//function rebuildSelect(intCurrentSelect){
//    var arrNewOpt = new Array();
//	var arrCurrentSelect = new Array();
//	var intSelectedValue = document.getElementById("selOpt" + intCurrentSelect).value;
//    var intSelectedIndex = document.getElementById("selOpt" + intCurrentSelect).selectedIndex;

//	selectedIndexes = new Array();
//    if (blackedOut != undefined && blackedOut[intSelectedValue] == undefined && intSelectedValue != 0) { //this option is grayedout and should unselect all other boxes
//        for (var i = 0; i < 8 && document.getElementById("selOpt" + i); i++) {
//            selectedIndexes[i] = document.getElementById("selOpt" + i).selectedIndex; //this option was selected            
//            if (i != intCurrentSelect) {
//	            document.getElementById("selOpt" + i).selectedIndex = 0;       
//            }
//	    }
//	}
//	blackedOut = new Array();

//    //there was an option that was selected before user selected gray option. Try to keep option
//    if(selectedIndexes.length != 0){
//        var regString = "";
//        var i = 0;
//        var lastWorkingRegString ="";
//        //var numMatching = 0;
//        var lastWorkingRegString2 ="";
//        //var numMatching2 = 0;
//        //find the most matching preselected options to keep.
//        for (;i < 8 && document.getElementById("selOpt" + i); i++) {
//            if(selectedIndexes[i] != undefined || i == intCurrentSelect){
//                //numMatching++;                
//                if(i != intCurrentSelect){
//                    regString += selectedIndexes[i] + "::";
//                }
//                else{
//                    regString += intSelectedValue + "::";                    
//                }
//            }
//            else {
//                regString += "[0-9]*::";                
//            }

//            if (allSkuString.match(regString)) { //check if this string is matching
//                lastWorkingRegString = regString;
//            }
//        }
//        regString = "";
//        for (; i >= 0; i--) { //iterate backwards to get the opposite case. Just to see if it gets more select boxes selected
//            if(selectedIndexes[i] != undefined || i == intCurrentSelect){
//                //numMatching2++;
//                if(i != intCurrentSelect){
//                    regString = selectedIndexes[i] + "::" + regString;
//                }
//                else {
//                    regString = intSelectedValue + "::" + regString;                    
//                }
//            }
//            else {
//                regString = "[0-9]*::" + regString;                
//            }

//            if (allSkuString.match(regString)) { //check if this string is matching
//                lastWorkingRegString2 = regString;
//            }
//        }


//        //Find the regular expression that got more matches
//        if (lastWorkingRegString2.replace("[0-9]*::", "").split("::").length > lastWorkingRegString.replace("[0-9]*::", "").split("::").length) { //the second for loop got more hits
//            var selectedArr = new Array();
//            selectedArr = lastWorkingRegString2.replace("[0-9]*::", "").split("::");
//            for (i = 0;i < selectedArr.length; i++) {
//                if (selectedArr[i] != "" && i != intCurrentSelect) {
//                    document.getElementById("selOpt" + i).selectedIndex = selectedIndexes[i]; //This select box can be selected with the others
//                }
//            }
//        }
//        else {
//            var selectedArr = new Array();
//            selectedArr = lastWorkingRegString.replace("[0-9]*::", "").split("::");
//            for (i = 0;i < selectedArr.length; i++) {
//                if (selectedArr[i] != "" && i != intCurrentSelect) {
//                    document.getElementById("selOpt" + i).selectedIndex = selectedIndexes[i]; //This select box can be selected with the others
//                }
//            }
//        }
//        //document.getElementById("selOpt" + intCurrentSelect).selectedIndex = intSelectedIndex; //the original resets
//    }

//	//Create Regular Expression
//	var regexString = "";
//	var i = 0; //This will indicate how many selOpts there are
//	for (; i < 8 && document.getElementById("selOpt" + i); i++) {
//        //check if the select box i has a selected value and build the regex pattern
//        if ((intSelectedSku != 0 && intCurrentSelect == i) || document.getElementById("selOpt" + i).value == 0) { //if we're here then the option isnt selected
//	        if (regexString.charAt(regexString.length - 1) != "*") { //this is so we dont have multiple [0-9:]* together
//	            regexString += "[0-9:]*";
//	        }
//	    }
//	    else {
//	        if (i != 0 /*&& document.getElementById("selOpt" + (i + 1))*/) { //Middle option(s)
//	            regexString += "::" + document.getElementById("selOpt" + i).value;
//	        }
//	        else if (i == 0) { //The first option
//	            regexString = /*"^" + */document.getElementById("selOpt" + i).value;
//	        }
//	    }
//	}
//	document.getElementById("divShipping").innerHTML = regexString;

//    var checkerArr = new Array();
//    var a = 0;
//    var arrOptId;
//    //var numOfAvailableSkus = 0;
//    var lastSkuAvailable = 0;
//    for (var keys in arrOpt) {
//        if (keys.match(regexString)) {

//			arrOptId = new Array();
//			arrOptId = keys.split("::")

//			//only insert distinct optionids into the array
//			for (var j = 0; j < arrOptId.length; j++) {
//			    //check if the value is in the hash table which checks for duplicates
//			    if (checkerArr[arrOptId[j]] == undefined) {
//			        checkerArr[arrOptId[j]] = 1;
//			        arrNewOpt[a] = arrOptId[j];
//                    a++;
//			    }
//			}
//		}
//    }

//    //arrNewOpt contains a list of distinct optionids available
//    //Compare all the available option values to the arrNewOptValues
//    var newRegString = "";
//    var regArr = regexString.split("::")
//    for (var i = 0; i < 8 && document.getElementById("selOpt" + i); i++) { //Go through all of the Select boxes
//        var allOpts = document.getElementById("selOpt" + i).getElementsByTagName("option"); //get all of the options in select box i
//        //allOpts = allOpts.sort();
//        var numSelected = 0;
//        var lastOptSelected;
//        for (var j = 1; j < allOpts.length; j++) { //iterate through all of the options in the select boxes
//            for (var a = 0; a < arrNewOpt.length; a++) { //iterate through all of the optionids
//                if (arrNewOpt[a] != undefined && allOpts[j].value == arrNewOpt[a]) { //optionid matches the option
//                    allOpts[j].className = "cbk";
//                    if (intCurrentSelect != i && document.getElementById("selOpt" + i).selectedIndex != allOpts.value) { //make sure this isnt the one that the user just clicked on
//                        numSelected++;
//                        lastOptSelected = j;
//                    }
//                    blackedOut[allOpts[j].value] = 1;
//                    delete arrNewOpt[a];
//                    break; //there can only be 1 matching optionid to each option
//                }
//                else{
//                    /*if (document.getElementById("selOpt" + i).selectedIndex != 0 && document.getElementById("selOpt" + i).selectedIndex == j) {
//                    }*/
//                    if (intCurrentSelect != i) {
//                        allOpts[j].className = "cgl";
//                    }
//                }
//            }
//        }
//        if (numSelected == 1) { //there is only 1 option available/selected
//            document.getElementById("selOpt" + i).selectedIndex = lastOptSelected; //Select an unselected option
//            //change the regexString accr
//            if (i != 0) //the middle/ last options in the regstring
//                newRegString += "::" + document.getElementById("selOpt" + i).value
//            else //the first one
//                newRegString += document.getElementById("selOpt" + i).value
//        }
//        else{
//             if (i != 0) //the middle/ last options in the regstring
//                 newRegString += "::" + document.getElementById("selOpt" + i).value//regArr[i]
//            else //the first one
//                newRegString += document.getElementById("selOpt" + i).value//regArr[i]
//        }
//    }

//    //document.getElementById("divShipping").innerHTML = newRegString;
//    return newRegString;

////    if (regexString.charAt(0) != "[") {
////        //document.getElementById("divShipping").innerHTML = regexString.replace("[:0-9]*", "::" + intSelectedValue);
////        return regexString.replace("[:0-9]*", "::" + intSelectedValue);
////    }
////    else {
////        //document.getElementById("divShipping").innerHTML = regexString.replace("[:0-9]*", intSelectedValue);        
////        return regexString.replace("[:0-9]*", intSelectedValue);
////    }            
////        var returnString = ""
////        if (regexString[0] != "[")
////            returnString = regexString.replace("[:0-9]+?", "::" + intSelectedValue);
////        else
////            returnString = regexString.replace("[:0-9]+?", "^" + intSelectedValue);
////        //remove the ^ from the beginning and the $ from the end
////        return returnString.substring(1, returnString.length - 1)
////    }
////    else { //The customer just selected a grayed out option that does not match with the others selected   
////        return "";
////    }



//    ////////alert("testc" + testc);

//    /*
//	for (var i = 0; i <= 7 && document.getElementById("selOpt" + i); i++) { //run through the select boxes
//        var selCurrent = document.getElementById("selOpt" + i)
//        for (var j = 0; document.getElementById("selOpt" + i).options[j]; j++) { //iterate through the options in each select box. Make them gray
//            
//            
//            
//            
//            //get the element by value
//            if(document.getElementById("selOpt" + i).options[j].value == arrNewOpt[j]
//            
//            
//            if (arrNewOpt[i] && arrNewOpt[i][j]) { //option is available
//                document.getElementById("selOpt" + i).options[j].style.color = "#000";
//            }
//            else { //option is unavailable
//                document.getElementById("selOpt" + i).options[j].style.color = "#CCC";                
//            }
//        }
//    }*/



//    /*//Rebuild Select Boxes
//    for (var i = 0; i <= 7 && document.getElementById("selOpt" + i); i++) {		        
//        if (arrNewOpt[i]) {                
//            if (i != intCurrentSelect || intSelectedValue < 1) {
//		        //Clear Out Current List
//		        var selCurrent = document.getElementById("selOpt" + i)
//				if (selCurrent) {
//		            var optSel = document.createElement("option");
//		            var intOrgLen = selCurrent.length
//		            optSel.text = selCurrent.options[0].text
//		            optSel.value = "0";

//		            //Remove Old Options
//		            selCurrent.options.length = 0;

//		            //Add "Select ..." Text
//		            selCurrent.options.add(optSel);

//		            for (optKey in arrNewOpt[i]) {
//                        var opt = document.createElement("option");

//						opt.text = optKey.replace(/^\s+/, "");
//						opt.value = arrNewOpt[i][optKey];

//						selCurrent.options.add(opt);
//		            }

//		            //If there are less options then we started with we want to add on an item to show all options
//		            if (intOrgLen != selCurrent.length) {
//		                var opt = document.createElement("option");

//		                opt.text = " -- Show All Options -- "
//		                opt.value = "-1"

//		                selCurrent.options.add(opt);

//		                // Only one selectable option left
//		                if (selCurrent.length == 3)
//		                    selCurrent.options[1].selected = true;
//		            }

//		            //Check if an option was already selected for this box and if it can be reselected
//		            var reset = false;
//                    if (arrCurrentSelect[i] != "0" && intSelectedValue > 0) {
//                        for (var j = 0; j < selCurrent.length; j++) {
//		                    if (selCurrent.options[j].value == arrCurrentSelect[i]) {
//		                        selCurrent.options[j].selected = true;
//		                        reset = true;
//                                break;
//		                    }
//                        }
//                    }
//                    /*if (!reset && selCurrent.length > 1) {
//                        document.getElementById("optionResetMessage").style.display = "block";
//                        document.getElementById("optionResetMessage").innerHTML = "One or more of the option boxes have been reset"
//                        document.getElementById("optionResetMessage").style.opacity = 1;
//                        document.getElementById("optionResetMessage").style.filter = 'alpha(opacity=100)'; 
//                        setTimeout("fadeElement('optionResetMessage')", 1500);
//                    }*//*
//		        }
//		    }	
//		}
//	}	
//	*/


//    //Build regex string (the one above puts a [:0-9]+? at the location of the one selected)
//    //var bolKeyFound = false
//    //if (intSelectedSku != 0 && intCurrentSelect.selectedIndex != 0) {
//    //if (regexString[0] != "[")
//        //regexString = regexString.replace("[:0-9]+?", "::" + intSelectedValue);
//    //else
//       // regexString = regexString.replace("[:0-9]+?", "^" + intSelectedValue);
//    //remove the ^ from the beginning and the $ from the end
//   //return regexString.substring(1, regexString.length - 1)

//        /*if (arrOpt[regexString] != undefined) {
//            bolKeyFound = true;
//        }*/
//    //}
//    //return "";
//    /*else if (intSelectedSku == "-1") {
//        bolKeyFound = true;        
//    }*/
//   
//   /* 
//    //Make sure the option we now have selected is valid. If not all the boxes except the one we just selected need to be unselected
//	var keyCurrent = ""
//	//var bolKeyFound = false
//	
//	//Build Key
//	for (var i = 0; i <= 7 && document.getElementById("selOpt" + i); i++) {		
//		var selCurrent = document.getElementById("selOpt" + i)
//		
//		if (selCurrent) {
//			if (keyCurrent != "")
//				keyCurrent += "::"
//				
//			keyCurrent += selCurrent.value
//		}
//		else
//			break;
//	}



//	//Search for Key
//	for (var keys in arrOpt){			
//		if (intSelectedValue == "-1")
//			var regExpCurrent = new RegExp(".*")
//		else
//			var regExpCurrent = new RegExp("^" + keyCurrent.replace(/::0::/gi,"::[^:]*::").replace(/0::/gi,"[^:]*::").replace(/::0/gi,"::[^:]*") + "$", "")
//	
//		if (keys.match(regExpCurrent)){
//                bolKeyFound = true
//				
//				break;
//		}
//	}
//		
//	//Reset dropdowns if key not found
//    if (!bolKeyFound) {
//		for (var i = 0; i <= 7; i++){		
//			if (i != intCurrentSelect) { 				
//				var selCurrent = document.getElementById("selOpt" + i)
//				
//				if (selCurrent)
//					selCurrent.options[0].selected = true;
//				else
//					break;
//			}
//		}				
//	}*/
//}

//////////
// updateSelect
//////////
function updateSelectNew(intCurrentSelect) {
    strKey = ""

    rebuildSelect(intCurrentSelect)

    //Build the key
    for (var i = 0; i < 8; i++) {
        if (document.getElementById("selOpt" + i)) {
            if (strKey != "")
                strKey += "::"

            strKey += document.getElementById("selOpt" + i).value
        }
        else
            break;
    }

    if (arrOpt[strKey]){
        updateProdInfo();
		resetCoordOption(strKey);
	}
    else
        clearSelect()
		
	
	
}

//////////
// rebuildSelect
//////////
function rebuildSelect(intCurrentSelect) {
    var arrNewOpt = new Array();
    var arrCurrentSelect = new Array();
    var intSelectedValue = document.getElementById("selOpt" + intCurrentSelect).value

    //Save Currently Selected Options
    for (var i = 0; i <= 7; i++) {
        var selCurrent = document.getElementById("selOpt" + i)

        if (!selCurrent)
            break

        if (selCurrent.selectedIndex && selCurrent.options[selCurrent.selectedIndex].value != "0") {
            arrCurrentSelect[i] = selCurrent.options[selCurrent.selectedIndex].value
        }
        else
            arrCurrentSelect[i] = "0"
    }

    //Find all options which contain this option
    for (var keys in arrOpt) {
        //var regExpCurrent = new RegExp(strKey.replace(/^0::/gi,"[^:]*::").replace(/::0::/gi,"::[^:]*::").replace(/::0$/gi,"::[^:]*"))
        if (intSelectedValue == "-1")
            var regExpCurrent = new RegExp(".*")
        else
            var regExpCurrent = new RegExp("^" + document.getElementById("selOpt" + intCurrentSelect).value + "::|::" + document.getElementById("selOpt" + intCurrentSelect).value + "::|::" + document.getElementById("selOpt" + intCurrentSelect).value + "$", "gi")

        if (keys.match(regExpCurrent)) {
            var arrOptValue = new Array();
            var arrOptId = new Array();

            arrOptValue = arrOpt[keys].osum.split(",")
            arrOptId = keys.split("::")

            for (var j = 0; j < arrOptValue.length; j++) {
                if (!arrNewOpt[j]) {
                    var arrNewVal = new Array();

                    arrNewOpt[j] = arrNewVal
                }

                arrNewOpt[j][arrOptValue[j]] = arrOptId[j]
            }
        }
    }

    //Rebuild Select Boxes
    for (var i = 0; i <= 7; i++) {
        if (arrNewOpt[i]) {
            if (i != intCurrentSelect || intSelectedValue < 1) {
                //Clear Out Current List
                var selCurrent = document.getElementById("selOpt" + i)

                if (selCurrent) {
                    var optSel = document.createElement("option");
                    var intOrgLen = selCurrent.length

                    optSel.text = selCurrent.options[0].text
                    optSel.value = "0";

                    //Remove Old Options
                    selCurrent.options.length = 0;

                    //Add "Select ..." Text
                    selCurrent.options.add(optSel);

                    for (optKey in arrNewOpt[i]) {
                        var opt = document.createElement("option");

                        opt.text = optKey.replace(/^\s+/, "");
                        opt.value = arrNewOpt[i][optKey];

                        selCurrent.options.add(opt);
                    }

                    //If there are less options then we started with we want to add on an item to show all options
                    if (intOrgLen != selCurrent.length) {
                        var opt = document.createElement("option");

                        opt.text = " -- Show All Options -- "
                        opt.value = "-1"

                        selCurrent.options.add(opt);

                        // Only one selectable option left
                        if (selCurrent.length == 3)
                            selCurrent.options[1].selected = true;
                    }

                    //Check if an option was already selected for this box and if it can be reselected
                    if (arrCurrentSelect[i] != "0" && intSelectedValue > 0) {
                        for (var j = 0; j < selCurrent.length; j++) {
                            if (selCurrent.options[j].value == arrCurrentSelect[i]) {
                                selCurrent.options[j].selected = true;
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    //Make sure the option we now have selected is valid. If not all the boxes except the one we just selected need to be unselected
    var keyCurrent = ""
    var bolKeyFound = false

    //Build Key
    for (var i = 0; i <= 7; i++) {
        var selCurrent = document.getElementById("selOpt" + i)

        if (selCurrent) {
            if (keyCurrent != "")
                keyCurrent += "::"

            keyCurrent += selCurrent.value
        }
        else
            break;
    }

    //Search for Key
    for (var keys in arrOpt) {
        if (intSelectedValue == "-1")
            var regExpCurrent = new RegExp(".*")
        else
            var regExpCurrent = new RegExp("^" + keyCurrent.replace(/::0::/gi, "::[^:]*::").replace(/0::/gi, "[^:]*::").replace(/::0/gi, "::[^:]*") + "$", "")

        if (keys.match(regExpCurrent)) {
            bolKeyFound = true

            break;
        }
    }

    //Reset dropdowns if key not found
    if (!bolKeyFound) {
        for (var i = 0; i <= 7; i++) {
            if (i != intCurrentSelect) {
                var selCurrent = document.getElementById("selOpt" + i)

                if (selCurrent)
                    selCurrent.options[0].selected = true;
                else
                    break;
            }
        }
    }
}

function optHigh(curImg) {
    curImg.style.border = "2px solid #336699"
    curImg.style.padding = "1px"
}

//////////
// setFinish
//////////
function setFinish(strFinish) {
    var selFinish = document.getElementById("selFinish")
    //////alert(selFinish);

    if (selFinish) {
        strFinish = trim(strFinish)

        if (strFinish == "") {
            selFinish.selectedIndex = 0;
        }
        else {
            for (var i = 0; i < selFinish.length; i++) {
                if (selFinish.options[i].value.toLowerCase().replace(/[^A-Za-z0-9 ]/gi, " ") == strFinish.toLowerCase().replace(/[^A-Za-z0-9 ]/gi, " ")) {
                    selFinish.options[i].selected = true
                    break;
                }
            }

            var divMiniOpt = document.getElementById("divMiniOpt")

            if (divMiniOpt) {
                var arrImg = divMiniOpt.getElementsByTagName("img")

                for (var i = 0; i < arrImg.length; i++) {
                    if (arrImg[i].alt.toLowerCase().replace(/[^A-Za-z0-9 ]/gi, " ") == strFinish.toLowerCase().replace(/[^A-Za-z0-9 ]/gi, " ")) {
                        optHigh(arrImg[i])
                        break;
                    }
                }
            }
        }
    }
}

//////////
// trim
//////////
function trim(stringToTrim) {
    return stringToTrim.replace(/^\s+|\s+$/g, "");
}

//////////
// clearOptHigh
//////////
function clearOptHigh() {
    if (document.getElementById("divMiniOpt")) {
        var divMiniOpt = document.getElementById("divMiniOpt")
        var arrImg = divMiniOpt.getElementsByTagName("img")

        for (i = arrImg.length - 1; i >= 0; i--) {
            if (arrImg[i].className == "bBox") {
                arrImg[i].style.border = "1px solid #CCC"
                arrImg[i].style.padding = "2px"
            }
        }
    }

    setFinish("")
}

//////////
// optLarge
//////////
function optLarge(curOpt, pos) {
    var optL = document.getElementById("optL")

    optL.innerHTML = "<img id=\"optLImg\" src=\"" + curOpt.src.replace("mini", "image") + "\" width=\"200px\" height=\"200px\">" + curOpt.alt + "<img src=\"http://hi.atgimg.com/images/layout/whtSel.gif\" class=\"pa\" style=\"top:-10px;left:94px;\">"
    optL.style.display = "block"

    if (pos < 19) {
        optL.style.left = (pos * 28) - 118 + "px"
        optL.style.top = "35px"
    }
    else {
        optL.style.left = ((pos - 18) * 28) - 118 + "px"
        optL.style.top = "70px"
    }
}

//////////
// rateReview
//////////
function rateReview(intReviewId, intHelpful, curObject) {
    var ajaxReqObj = new ajaxRequestObject("/ajax/reviewReview.aspx", "reviewId=" + intReviewId + "&helpful=" + intHelpful);
    ajaxReqObj.doGetCallback();
    curObject.parentNode.innerHTML = "<span style='color: green'>Thank you for rating this review.</span>"
}

//////////
// rateAnswer
//////////
function rateAnswer(intQuestionId, intAnswerId, intHelpful, intReport, curObject) {
    var ajaxReqObj = new ajaxRequestObject("/ajax/rateAnswer.aspx", "questionId=" + intQuestionId + "&answerId=" + intAnswerId + "&helpful=" + intHelpful + "&report=" + intReport);
    ajaxReqObj.doGetCallback();
    curObject.parentNode.innerHTML = "<span style='color: green'>Thank you for giving feedback on this answer.</span>"
}

//////////
// saveRecent
//////////
function saveRecent(strSKU, strGroupId, strPrice, strMfr, strImg) {
    var recent = readCookie("recentView");
    var strCookieValue = recent;
    var curProd = strGroupId + "|" + strMfr + "/" + strImg + "~";
    if (strCookieValue != null) {
        //check if current product already found in recent viewed list
        var foundIndex = -1;
        foundIndex = strCookieValue.indexOf(curProd);
        if (foundIndex > -1)
            strCookieValue = strCookieValue.replace(curProd, "");
        //insert current prod at top
        strCookieValue = curProd + strCookieValue;
        //check if there are more than 5 products in queue
        var arr = strCookieValue.split("~");
        var count = arr.length;
        if (count > 11) {
            //select top 10 only
            var i = 0;
            var temp = "";
            for (i = 0; i < 11; i++) {
                var t = arr[i] + "~";
                temp = temp + t;
            }
            strCookieValue = temp;
        }

    }
    else {
        strCookieValue = strGroupId + "|" + strMfr + "/" + strImg + "~";
    }
    //Remove Extra blank values
    strCookieValue = strCookieValue.replace(" ", "");
    SetMyCookie("recentView", strCookieValue, 90);
}

//////////
// SetMyCookie
//////////
function SetMyCookie(cookieName, cookieValue, exp) {
    var today = new Date();
    var expire = new Date();
    if (exp == null || exp == 0)
        exp = 1;
    expire.setTime(today.getTime() + 3600000 * 24 * exp);
    document.cookie = cookieName + "=" + cookieValue + ";path=/;expires=" + expire.toTimeString();
}

//////////
// OpenClearanceAjax
//////////
function openClearanceAjax(clearanceSku) {

    openPopBox(100, 100, "<div style='margin:auto; text-align: center;line-height: 140px;'><img src='/images/loading.gif' align='middle'/></div>");
    var ajaxReqObj;
    if(clearanceSku == 0){
        ajaxReqObj = new ajaxRequestObjectCache("/ajax/clearanceUpdatedQty.aspx", "v=3&sku=" + intSelectedSku, writeDetail);
    }
    else{
        ajaxReqObj = new ajaxRequestObjectCache("/ajax/clearanceUpdatedQty.aspx", "v=3&sku=" + clearanceSku, writeDetail);        
    }
    ajaxReqObj.doGetCallback();
}

//////////
// writeAjaxToViewPage
//////////
function writeDetail(strData) {
    if (strData != "" && document.getElementById("popBox").style.display != "none") {
        openPopBox(600, 146, strData);
    }
}

//////////
// showHideElement --Hides or shows the given id
//////////
function showHideElement(id) {
    if (document.getElementById(id).style.display == "none")
        document.getElementById(id).style.display = "block";
    else
        document.getElementById(id).style.display = "none"
}

//////////
// changeTitle -- removes title of "More Clearance Information"
//////////
function changeTitle() {
    document.getElementById("MoreLessTitle").innerHTML = "";
}

//////////
// addToCartClearance
//////////
function addToCartClearance(sku) {
    var link = strSecurePath + "/cart/addToCart.aspx?"
    var newPageLocation;
    if (sku != "" && sku != 0) {
        newPageLocation = link + "sku=" + sku + "&qty=" + document.getElementById('clearanceQty').options[document.getElementById('clearanceQty').selectedIndex].value + "&clearance=1" + getABTestCookieInfo();
    }
    else if (intSelectedSku != 0 && intSelectedSku != "") {
        newPageLocation = link + "sku=" + intSelectedSku + "&qty=" + document.getElementById('clearanceQty').options[document.getElementById('clearanceQty').selectedIndex].value + "&clearance=1" + getABTestCookieInfo();
        
    }

    window.location = newPageLocation;
}


//////////
// addToCartCoord
//////////
function addToCartCoord(prefix) {
	var intToTrim = 5;
	if(prefix == undefined){
		intToTrim = 4;
		prefix = "";
	}

    var i = 0;
    var checkCorrect = true;
    var skus = "";
    
	if (document.getElementById(prefix + "coorSel999") != null && document.getElementById(prefix + "coorSel999").selectedIndex != 0) {
        skus = document.getElementById(prefix + "coorSel999").options[document.getElementById(prefix + "coorSel999").selectedIndex].getAttribute("name");
    }
    else{
        skus = intSelectedSku;
    }
    
    var qtys = document.getElementById(prefix + "coordQty999").value
    if(qtys == 0 || skus == 0 || (document.getElementById(prefix + "coorSel999") != null && document.getElementById(prefix + "coorSel999").selectedIndex == 0)){
        checkCorrect = false;
        document.getElementById(prefix + "coorDiv999").style.border = "3px solid #660000";
    }

    skus += ",";
    qtys += ",";

    document.getElementById(prefix + "coordError").style.display = 'none';
	var bolShowPopBox = false; //gets set to true only if a selected groupid has more than 1 sku
	
	for (var i = 1; i < document.getElementById(prefix + "shipSim").getElementsByTagName("input").length; i+=2) { //every other input is the checkbox
        var groupid = document.getElementById(prefix + "shipSim").getElementsByTagName("input")[i].id.substring(intToTrim, document.getElementById(prefix + "shipSim").getElementsByTagName("input")[i].id.length)
		document.getElementById(prefix + "coorDiv" + groupid).style.border = "none";
		
		if (document.getElementById(prefix + "cBox" + groupid).checked && ((document.getElementById(prefix + "coorSel" + groupid) && document.getElementById(prefix + "coorSel" + groupid).selectedIndex == 0) || document.getElementById(prefix + "coordQty" + groupid).value == 0) && document.getElementById(prefix + "coordQty" + groupid) > 0) {
            document.getElementById(prefix + "coorDiv" + groupid).style.border = "3px solid #660000";
            checkCorrect = false;
        }
        else if (document.getElementById(prefix + "cBox" + groupid).checked && document.getElementById(prefix + "coordQty" + groupid).value > 0 && document.getElementById(prefix + "coordQty" + groupid).value != "") {
            if(!bolShowPopBox && document.getElementById(prefix + "skuCount" + groupid) && parseInt(document.getElementById(prefix + "skuCount" + groupid).innerHTML) > 1){
				bolShowPopBox = true;
			}
			
			if (document.getElementById(prefix + "coorSel" + groupid) != null) { //We have a select box to choose a sku from
                if(document.getElementById(prefix + "coorSel" + groupid).selectedIndex != 0){
					skus += document.getElementById(prefix + "coorSel" + groupid).options[document.getElementById(prefix + "coorSel" + groupid).selectedIndex].getAttribute("name") + ",";
					qtys += document.getElementById(prefix + "coordQty" + groupid).value + ",";
				}
				else
				{
					document.getElementById(prefix + "coorDiv" + groupid).style.border = "3px solid #660000";
					checkCorrect = false;
				}
            }
            else {
                skus += document.getElementById(prefix + "coorDiv" + groupid).getAttribute("name") + ",";
                qtys += document.getElementById(prefix + "coordQty" + groupid).value + ",";
            }   
        }
	}
	
	
	
	
    // //Run through all checkBoxes
    // while (document.getElementById(prefix + "cBox" + i) != null) {
        // document.getElementById(prefix + "coorDiv" + i).style.border = "none";
        // if (document.getElementById(prefix + "cBox" + i).checked && (document.getElementById(prefix + "coorSel" + i) != null && document.getElementById(prefix + "coorSel" + i).selectedIndex == 0 || document.getElementById(prefix + "coordQty" + i).value == 0)) {
            // document.getElementById(prefix + "coorDiv" + i).style.border = "3px solid #660000";
            // checkCorrect = false;
        // }
        // else if (document.getElementById(prefix + "cBox" + i).checked && document.getElementById(prefix + "coordQty" + i).value > 0 && document.getElementById(prefix + "coordQty" + i).value != "") {
            // if (document.getElementById(prefix + "coorSel" + i) != null) { //We have a select box to choose a sku from
                // skus += document.getElementById(prefix + "coorSel" + i).options[document.getElementById(prefix + "coorSel" + i).selectedIndex].getAttribute("name") + ",";
                // qtys += document.getElementById(prefix + "coordQty" + i).value + ",";
            // }
            // else {
                // skus += document.getElementById(prefix + "coorDiv" + i).getAttribute("name") + ",";
                // qtys += document.getElementById(prefix + "coordQty" + i).value + ",";
            // }   
        // }
        // i++;
    // }

    if (!checkCorrect) {
        document.getElementById(prefix + "coordError").style.display='block';
        return false;
    }
    else if(bolShowPopBox && prefix !== ""){ //we dont want to show the popBox if we're already showing it
		var ajaxReqObj = new ajaxRequestObject("/ajax/coordItemAddToCart.aspx", "sku=" + skus.substring(0, skus.length - 1) + "&qty=" + qtys.substring(0, qtys.length - 1) + "&groupid=" + intGId + getABTestCookieInfo(), openCoordAddToCartPopBox);
		//alert("/ajax/coordItemAddToCart.aspx?sku=" + skus.substring(0, skus.length - 1) + "&qty=" + qtys.substring(0, qtys.length - 1) + "&groupid" + intGId + getABTestCookieInfo());
		ajaxReqObj.doGetCallback();
	}else{ //No Errors, proceed to checkout
		var accSkip = "";
		if(prefix == 1)
			accSkip = "&accSkip=true"; //Skip the accessories section
        var cartloc = strSecurePath + "/cart/addToCart.aspx?sku=" + skus.substring(0, skus.length - 1) + "&coorQty=" + qtys.substring(0, qtys.length - 1) + getABTestCookieInfo() + accSkip;
		window.location = cartloc;
    }
}
//////////
// openCoordAddToCartPopBox 
//////////
function openCoordAddToCartPopBox(strResult){
		//alert(strResult);
		openPopBox(900,500, strResult)
		eval(document.getElementById("divJS").innerHTML);
}

//////////
// updateSelect
//////////
function resetCoordOption(strKey){
//If we came in here, the main product options were just changed and the coordItems needs to be updated
	if(document.getElementById("0shipSim") && document.getElementById("0coordSelOption")){ //Shop Similar Items
		selectCoordOption(document.getElementById("0coorSel999"), strKey)
	}
	if(document.getElementById("1shipSim") && document.getElementById("1coordSelOption")){ //Shop Similar Items
		selectCoordOption(document.getElementById("1coorSel999"), strKey)
	}
	if(document.getElementById("2shipSim") && document.getElementById("2coordSelOption")){ //Shop Similar Items
		selectCoordOption(document.getElementById("2coorSel999"), strKey)
	}
}

//////////
// selectCoordOption
//////////
function selectCoordOption(selectElement, strKey){
	if(strKey == 0){
		selectElement.selectedIndex = 0;
	}
	else{
		var arrOptionsInCoord = selectElement.getElementsByTagName("option");
		for(var i = 1; i< arrOptionsInCoord.length; i++){
			if(arrOptionsInCoord[i].getAttribute("name") == arrOpt[strKey].sku){
				selectElement.selectedIndex = i;
				selectElement.onchange();
				break;
			}
		}
	}
}


//////////
// updateCoordPrice
//////////
function updateCoordPrice(price, num, prefix) {
    if(prefix == undefined)
		prefix = "";
		
	if (price == 0 && document.getElementById(prefix + "price" + num)) {
		if(document.getElementById(prefix + "price" + num).getAttribute("name").indexOf('-') != -1){ //Need to add a min + max price
			var dblMin = document.getElementById(prefix + "price" + num).getAttribute("name").split('-')[0];
			var dblMax = document.getElementById(prefix + "price" + num).getAttribute("name").split('-')[1];			
			document.getElementById(prefix + "price" + num).innerHTML = toCurrency(parseFloat(dblMin) * parseFloat(document.getElementById(prefix + "coordQty" + num).value)) + "-" + toCurrency(parseFloat(dblMax) * parseFloat(document.getElementById(prefix + "coordQty" + num).value));
		}
		else{				
			var intPrice = parseFloat(document.getElementById(prefix + "price" + num).getAttribute("name")) * parseFloat(document.getElementById(prefix + "coordQty" + num).value)
			if(intPrice > 0)
				document.getElementById(prefix + "price" + num).innerHTML = toCurrency(intPrice);
		}
	}
    else{
        var intPrice = parseFloat(price) * parseFloat(document.getElementById(prefix + "coordQty" + num).value)
		if(intPrice >= 0)
			document.getElementById(prefix + "price" + num).innerHTML = toCurrency(intPrice);
		else
			document.getElementById(prefix + "price" + num).innerHTML = toCurrency(0);
	}
	
	if(parseFloat(document.getElementById(prefix + "coordQty" + num).value) < 1){
		document.getElementById(prefix + "cBox" + num).checked = false;
	}
}

//////////
// updateCoordTotal
//////////
function updateCoordTotal(prefix) {
	var toTrim = 5; //the number used to help to get the groupid (need to splice it out of the id)
	if(prefix == undefined){
		prefix = ""; //The only time this will be empty is during the addToCartPopBox
		toTrim = 4
	}
    var i = 0;
    var totalPriceLow;
	var totalPriceHigh;
	totalPriceLow = parseFloat(document.getElementById(prefix + "price999").getAttribute("name")) * parseFloat(document.getElementById(prefix + "coordQty999").value);
    totalPriceHigh = totalPriceLow; //set them equal to each other because the first item doesnt have a min/max price
	if (document.getElementById(prefix + "coorSel999") != null && document.getElementById(prefix + "coorSel999").selectedIndex > 0){
        totalPriceLow = parseFloat(document.getElementById(prefix + "coorSel999").options[document.getElementById(prefix + "coorSel999").selectedIndex].value) * parseFloat(document.getElementById(prefix + "coordQty999").value);
		totalPriceHigh = totalPriceLow;	
	}
    //Value = price
    //Name = sku
    for (var i = 1; i < document.getElementById(prefix + "shipSim").getElementsByTagName("input").length; i+=2) { //every other input is the checkbox
        if (document.getElementById(prefix + "shipSim").getElementsByTagName("input")[i].checked) { //check if it's checked
            //get the id
            var groupid = document.getElementById(prefix + "shipSim").getElementsByTagName("input")[i].id.substring(toTrim, document.getElementById(prefix + "shipSim").getElementsByTagName("input")[i].id.length)
			
			var selectBoxId = prefix + "coorSel" + groupid;
			if (document.getElementById(selectBoxId)) { //Selectbox available
                totalPriceLow += parseFloat(document.getElementById(prefix + "coorSel" + groupid).options[document.getElementById(prefix + "coorSel" + groupid).selectedIndex].value) * parseFloat(document.getElementById(prefix + "coordQty" + groupid).value);
				totalPriceHigh += parseFloat(document.getElementById(prefix + "coorSel" + groupid).options[document.getElementById(prefix + "coorSel" + groupid).selectedIndex].value) * parseFloat(document.getElementById(prefix + "coordQty" + groupid).value);; //set them equal to each other because select boxes dont have a min or max.
			}
            else { //no selectBox
				var dblPriceOfItem = document.getElementById(prefix + "price" + groupid).getAttribute("name")
				if(dblPriceOfItem.indexOf('-') == -1){ //check if there is a min/ max price. If so then we need to split it
					totalPriceLow += parseFloat(dblPriceOfItem) * parseFloat(document.getElementById(prefix + "coordQty" + groupid).value);
					totalPriceHigh += parseFloat(dblPriceOfItem) * parseFloat(document.getElementById(prefix + "coordQty" + groupid).value);;
				}
				else{ //There is a min/max price
					totalPriceLow += parseFloat(dblPriceOfItem.split('-')[0]) * parseFloat(document.getElementById(prefix + "coordQty" + groupid).value);
					totalPriceHigh += parseFloat(dblPriceOfItem.split('-')[1]) * parseFloat(document.getElementById(prefix + "coordQty" + groupid).value);
				}
			}
        }    
    }
    if(totalPriceLow == totalPriceHigh){
		document.getElementById(prefix + "coorTotalPrice").innerHTML = toCurrency(totalPriceLow);
		document.getElementById(prefix + "coordWarn").style.display = "none";
	}
	else{
		document.getElementById(prefix + "coorTotalPrice").innerHTML = toCurrency(totalPriceLow) + "-" + toCurrency(totalPriceHigh);
		document.getElementById(prefix + "coordWarn").style.display = "";
	}
}

//////////
// showOpt
//////////
function showOpt(intOpt, intPos){	
	//Temp Box
	openPopBox(900,330, "<h2>Loading...</h2>")  

	var ajaxReqObj = new ajaxRequestObjectCache("/ajax/optDisplay.aspx", "groupId=" + intGId + "&option=" + intOpt + "&pos=" + intPos, displayImg);
    ajaxReqObj.doGetCallback();
}

//////////
// displayImg
//////////
function displayImg(strResult){
	openPopBox(900,330, strResult)  
}

//////////
// updateOption
//////////
function updateOption(strValue, intOption){
	var selCurrent = document.getElementById("selOpt" + intOption)

	for (var i = 0; i < selCurrent.length; i++){					
		if (selCurrent.options[i].value == strValue){
			selCurrent.options[i].selected = true;				
			break;
		}
	}

	updateSelectNew(intOption)
}

//////////
// setOptionKey
//////////
function setOptionKey(strSetKey){
    var arrKey = new Array()
    if (strSetKey != "") {
        arrKey = strSetKey.split("::")
        for (var i = 0; i <= arrKey.length - 1; i++) {
            if (document.getElementById("selOpt" + i)) {
                var selCurrent = document.getElementById("selOpt" + i)
				for (var j = 0; j < selCurrent.length; j++){
					if (selCurrent.options[j].value == arrKey[i]){						
                        selCurrent.options[j].selected = true;	
						break;
					}
				}
			}
		}
	}
	
	strKey = strSetKey
	if (arrOpt[strKey])
		updateProdInfo()
	else
		clearSelect()
}

//////////
// upImgTab
//////////
function upImgTab(tab){
    var iTab = document.getElementById("iTab")	
	var vTab = document.getElementById("vTab")	
	var divMainImg = document.getElementById("divMainImg")	
	var player = document.getElementById("player")	
	var treepodiaPlayer = document.getElementById("treepodiaPlayer")	
	
	var divAltImg = document.getElementById("divAltImg")	
	var divAltVideo = document.getElementById("divAltVideo")	

    var divZoomButton = document.getElementById("imgZoomButton");	
    var divReportButton = document.getElementById("vidReportButton");

    var partNumber = document.getElementById("spnPartNumber");

	if (tab == "v"){
        if (document.getElementById("prodBanner") != null)
            document.getElementById("prodBanner").style.display = "none";
		zoomOn = false;
		iTab.className = "iTabOff";
		vTab.className = "vTabOn";
		
		divMainImg.style.display = "none";
		divAltImg.style.display = "none";
		player.style.display = "block";
		divAltVideo.style.display = "block";
        divZoomButton.style.display = "none";
        divReportButton.style.display = "block";
        partNumber.style.display = "none";
		loadDefVideo();
	}
	else{
        if (document.getElementById("prodBanner") != null)
        document.getElementById("prodBanner").style.display = "block";

		zoomOn = true;
		iTab.className = "iTabOn";
		vTab.className = "vTabOff";
		
		divMainImg.style.display = "block";
		divAltImg.style.display = "block";
		player.style.display = "none";
		treepodiaPlayer.style.display = "none";
		divAltVideo.style.display = "none";
        divZoomButton.style.display = "block";
        divReportButton.style.display = "none";
        partNumber.style.display = "block";
	}
}

//////////
// showCutOffTime
//////////
function showCutOffTime() {
    //returns true so the lead time part won't run on load
    var d = new Date();
    //////alert(d);
    //////alert(d.getTimezoneOffset());
    var custPSTHour = d.getHours() - (d.getTimezoneOffset() / 60) + 7;
    var time = arrOpt[strKey].shipTimeCutOff.split(":");
    if (custPSTHour < time[0] && d.getDay() != 0 && d.getDay() != 6) { //the customers time (PST) isnt past the cut off time for mfrs (PST)
        var toOutPut = "Order by <span class='fntsb'>"
        
        var ampm = "am "
        if (time[0] > 11) { //Convert from military to normal
            if(time[0] != 12)
				toOutPut += (time[0] - 12);
            else
				toOutPut += time[0];
			ampm = "pm ";
        }
        else {
            toOutPut += time[0];
        }

        if (time[1] != 0) { //Handle the minutes
            toOutPut += ":" + time[1];
        }

        toOutPut += ampm + "PST</span> for same-day shipping (Mon-Fri)"
        document.getElementById("tdShipInfo").innerHTML = toOutPut;
        document.getElementById("tdShipInfo").style.display = "";        
        return true;
    }
}

//////////
// openWhatsThis
//////////
function openWhatsThis(toOpen){
    openPopBox(100, 100, "<div style='margin:auto; text-align: center;line-height: 140px;'><img src='/images/loading.gif' align='middle'/></div>");
    var ajaxReqObj = new ajaxRequestObjectCache("/support/deliveryoptions.aspx", "expedite=" + toOpen, showWhatsThis);
    ajaxReqObj.doGetCallback();
}

//////////
// showWhatsThis
//////////
function showWhatsThis(strData) {
    if (strData != "" && document.getElementById("popBox").style.display != "none") {
        if(strData.length < 1500)
            openPopBox(600, 250, strData);
        else
            openPopBox(600, 650, strData);            
    }
}

//////////
// openShipEstimate
//////////
function openShipEstimate() {
    openPopBox(100, 100, "<div style='margin:auto; text-align: center;line-height: 140px;'><img src='/images/loading.gif' align='middle'/></div>");
    var ajaxReqObj = new ajaxRequestObjectCache("/support/shipEstimate.aspx", "", showShipEstimate);
    ajaxReqObj.doGetCallback();
}

//////////
// showShipEstimate
//////////
function showShipEstimate(strData) {
    openPopBox(450, 565, strData);
}


//////////
// Customer Service Notes
//////////
//function openInternalNotes(sku) {
//    var ajaxReqObj = new ajaxRequestObjectCache("/ajax/prodNote.aspx", "sku=" + sku, showProdNotes);
//    ajaxReqObj.doGetCallback();
//}

//function showProdNotes(strData) {
//    document.getElementById("internalNotes").innerHTML = strData;
//}

function submitNote(ts, userIP, sku) {
    ////////alert("HIIIIIIII");
    ////////alert(userIP);
    var note = document.getElementById("addNotesTxt").value.toString();
    document.getElementById("addNotesTxt").value = "";

    ////////alert("blackbox/ajax/saveProductNoteAjax.aspx?note=" + note.replace(/&/g, escape('&')).replace(/#/g, escape('#')).replace(/\+/g, '%2B').replace(/"/g, escape('"')).replace(/</g, escape('<')).replace(/>/g, escape('>')) + "&userIP=" + userIP + "&prodId=" + sku);
    var ajaxReqObj = new ajaxRequestObject("/ajax/saveProductNoteAjax.aspx", "note=" + note.replace(/&/g, escape('&')).replace(/#/g, escape('#')).replace(/\+/g, '%2B').replace(/"/g, escape('"')).replace(/</g, escape('<')).replace(/>/g, escape('>')) + "&userIP=" + userIP + "&prodId=" + sku, showNote);
    ajaxReqObj.doGetCallback();
}

function showNote(strInfo) {
    ////////alert(strInfo);
    var args = strInfo.split("| ");
    ////////alert(args[0] + "<br />" + args[1] + "<br />" + args[2] + "<br />" + args[3]);

    var tbody = document.getElementById("divATGInfo");

    var noteBox = document.createElement("div");
    noteBox.id = "note" + args[0];
    tbody.appendChild(noteBox);
    noteBox = document.getElementById("note" + args[0]);
    //sbATGInfo.Append("<div id=""note" & dtr("noteId") & """ style=""width:280px;border-top:1px dotted grey;overflow:auto"">" & dtr("note") & "<br /><strong class=""gutIn"">- " & dtr("createStamp").ToString().Split(" ")(0).Replace("-", "/") & "</strong><div style=""display:none"">" & dtr("userIP") & "</div><a href="""" onclick=""deleteNote(" & dtr("noteId") & "); return false;"" style=""text-decoration:none;font-size:12px;float:right"">Delete</a><br /><br /></div>")
    noteBox.innerHTML = args[1] + "<br /><strong class=\"gutIn\">- " + args[3] + "</strong></strong><div style=\"display:none\">" + args[2] + "</div><a href=\"\" onclick=\"deleteNote(" + args[0] + "); return false;\" style=\"text-decoration:none;font-size:12px;float:right\">Delete</a><br /><br />";
    //noteBox.innerHTML = args[1] + "<br /><div class=\"gutIn\" style=\"width:240px;float:left\">" + args[3] + "<br /><strong>- IP: " + args[2] + "</strong><a href=\"\" onclick=\"deleteNote(" + args[0] + "); return false;\" style=\"text-decoration:none;font-size:12px;float:right\">Delete</a><br /><br /></div>";
    noteBox.style.width = "280px";
    noteBox.style.display = "block";
    noteBox.style.borderTop = "1px dotted grey";
    noteBox.style.overflow = "auto";
}

function deleteNote(noteId) {
    document.getElementById("note" + noteId.toString()).style.display = "none";

    ////////alert("blackbox/ajax/deleteProductNoteAjax.aspx?noteId=" + noteId);
    var ajaxReqObj = new ajaxRequestObject("/ajax/deleteProductNoteAjax.aspx", "noteId=" + noteId, "");
    ajaxReqObj.doGetCallback();
}

//Shipping Pricing
function showZipInfo() {
    var zipSpn = document.getElementById("zipSpn");
    if (zipSpn) {
        var zip = readCookie("custzipcode");
        
        if (!zip) { //customer has not entered a zipCode
            zipSpn.innerHTML = "<a href='/ajax/findZip.aspx' class='fnts' style= 'margin-left:4px;' onClick='openZipPop();return false;'>Update shipping prices</a>"
        }
        else { //the customer has already provided a zipCode
            ajaxUpdateShip(zip)
        }
    }
}
function openZipPop() {
    intIndexOfSelectShip = document.getElementById("selShip").selectedIndex;
    openPopBox(144, 55, "<h2 style='background:none;'>Your ZIP Code</h2><input class='l' type='text' id='zipInput' style='width:58px'/> <span class='btnSml l' onClick='submitZipInfo()' style='margin-left:4px;margin-top:2px;'>Update</span><span id='zipHid' style='display:none;'></span>")
    document.getElementById("zipInput").focus();
}

function submitZipInfo() {
    SetCookie("custzipcode", document.getElementById("zipInput").value, 30); //set the cookie on the current domain
    //ajaxUpdateShip(document.getElementById("zipInput").value); //send the request to get the price
    window.location = strSecurePath + "/ajax/setZip.aspx?v=3&zip=" + document.getElementById("zipInput").value + "&url=" + escape(window.location.href.replace("#", "") + "&selindex=" + document.getElementById("selShip").selectedIndex);
    
    //document.getElementById("zipIframe").src = strSecurePath + "/ajax/setZip.aspx?v=3&zip=" + document.getElementById("zipInput").value;
    
    //document.getElementById("zipHid").innerHTML = "<iframe src='" + strSecurePath + "/ajax/setZip.aspx?v=3&zip=" + document.getElementById("zipInput").value + "' width='230px' height='50px' scrolling='no' frameBorder='0'></iframe>"
    ////////alert(document.getElementById("zipHid").innerHTML);
    //closePopBox();
}


function ajaxUpdateShip(zip) {
    if (strKey && arrOpt[strKey].shipSelect) { //we've already saved this information
        changeShipPrice(arrOpt[strKey].shipSelect);
    }
    else {
        document.getElementById("zipSpn").innerHTML = "<img src='/images/loadgray.gif' />";
        if(!zip)
            zip = readCookie("custzipcode")
        var ajaxReqObj;
		//////alert("1");
        if (intSelectedSku != 0)
            ajaxReqObj = new ajaxRequestObjectCache("/ajax/getShipPrice.aspx", "zip=" + zip + "&sku=" + intSelectedSku, changeShipPrice);
        else
            ajaxReqObj = new ajaxRequestObjectCache("/ajax/getShipPrice.aspx", "zip=" + zip + "&sku=" + intBaseSku, changeShipPrice);
        //////alert("2");
		ajaxReqObj.doGetCallback();
    }
}
function changeShipPrice(strData) {
	//////alert(strData + "3");
	if(strKey){
        arrOpt[strKey].shipSelect = strData;
	}
    if (strData != "") {	
		//////alert(document.getElementById("divSelShip").innerHTML);
		document.getElementById("divSelShip").innerHTML = strData;
		//////alert(document.getElementById("divSelShip").innerHTML);
		document.getElementById("zipSpn").innerHTML = "<span id='zipSpn'><a href='http://www.atgstores.com/support/deliveryoptions.aspx?expedite=1' style='padding-left:5px' onclick='openWhatsThis(1);return false;' class='fnts'>What's this?</a></span><br /><br />"
        document.getElementById("divSelShip").selectedIndex = window.location.href.substring(window.location.href.indexOf("&selindex=") + 10, window.location.href.indexOf("&selindex=") + 11);
    }
}

function openMfrInfo() {
	var ajaxReqObj = new ajaxRequestObjectCache("/ajax/mfrReport.aspx", "mfrid=" + intMfrId, showMfrReport);
    ajaxReqObj.doGetCallback();
}
function showMfrReport(strData) {
    document.getElementById("mfrReport").innerHTML = strData;
}

function updateClearanceCartButton(val, sku) {
    if (val == 'new') {
        document.getElementById("CbtnAddToCart").onclick = function () { addToCart(0) }
        return;
    }
    document.getElementById("CbtnAddToCart").onclick = function () { addToCartClearance(sku) }
}

//////////
// showMoreCoord
//////////
function showMoreCoord(idNum, intType){
	document.getElementById(intType + "hiddenCoord" + idNum).style.display = "";
	document.getElementById(intType + "linkMoreCoord" + idNum).style.display = "none";
	// var randomnumber = Math.floor(Math.random()*100000)
	// for(var i = randomnumber.toString().length; i<6; i++){
		// randomnumber += "0"
	// }
	// document.getElementById("reFeWrapper").style.border = "1px solid #" + randomnumber;
}

//////////
// leaveThisLast
//////////
setOptionKey(optionKey);
saveRecent(sRecent[0], sRecent[1], sRecent[2], sRecent[3], sRecent[4]);
if (isCanadianSite == 0) {
    showZipInfo();
}

openMfrInfo();

if (document.getElementById("lnkAddToCart")) {
    document.getElementById("lnkAddToCart").href = "#";
}

