var fGettingProductInfo = false;
var fDelayedAddToCart   = false;
var iDelayedInCart      = 0;
var iDelayedInventory   = 0;
var fDelayedSubmit      = false;
var fDelayedCheckout    = false;
var fAddingToCart       = false;

var objImageS        = null;
var objImageD        = null;
var iImageIndex      = 0;
var iImageItemID     = 0;
var iVariantItemID   = 0;
var sImageVariantIDs = "";
var sImageVariants   = "";

function Product_ViewDetails(iItemID)
{
    Redirect(sViewProductDetailsPage + iItemID, false);
}

function Product_ViewGallery(iItemID, iWidth, iHeight)
{
    var iFixSize = ((iWidth <= 0) && (iHeight <= 0)) ? 1 : 0;
    
    if (iWidth <= 0)
        iWidth = 640;

    if (iHeight <= 0)
        iHeight = 480;
        
    if (iVariantItemID > 0)
        iItemID = iVariantItemID;
        
    centeredPopEx(sViewProductGalleryPage + iItemID + "&FixSize=" + iFixSize, true, "", iWidth, iHeight, "yes");
}

function Product_Variant(iItemID, iVariant)
{
    return document.getElementById("variant_" + iItemID + "_" + iVariant);
}

function Product_CheckSelectioin(iItemID)
{
}

function Product_GetDefValue(obj)
{
    return GetAttribute(obj, "DefValue");
}

function Product_AddToCart(iItemID, iInCart, iInventory, fVariant, fSubmit, fCheckout)
{
    if (fAddingToCart || fGettingProductInfo)
        return;

    ClearError();
    
    var sVariants    = "";
    var fErrorHeader = true;
    var fErrorOk     = false;
    var sOptions     = "";
    var fInStock     = iInventory > 0;
    
    if (fVariant)
    {
        var iVariant;
        var iSelCount  = 0;
        var sMissingOptions = "";
        var objVariant      = null;
        var sWebEnabled     = null;
        var sInStock        = null;
        var fNeedInfo       = false;
        
        for (iVariant = 0; iVariant < 3; iVariant++)
        {
            objVariant = Product_Variant(iItemID, iVariant);
            
            if (objVariant == null)
            {
                if (iVariant == 0)
                {
                    // This occurs in Teaser mode, when AddToCart clicked on item with Variants
                    // But, teaser mode was not displaying the items variants, so, we go to Details
                    // View where Variants are available
                    Product_ViewDetails(iItemID);
                    fSubmit = false;
                    break;
                }
            }
            
            if (sVariants != "")
                sVariants += "\t";
            sVariants += (objVariant == null) ? "" : objVariant.value;
            
            if (objVariant != null)
            {
                if (iVariant == 0)
                {
                    sWebEnabled = GetAttribute(objVariant, "WebEnabled");
                    sInStock    = GetAttribute(objVariant, "InStock");
                    iInCart     = parseInt(GetAttribute(objVariant, "InCart"));
                    iInventory  = parseInt(GetAttribute(objVariant, "Inventory"));
                }

                if ((objVariant.options.selectedIndex <= 0) && (objVariant.options.length > 1))
                {
                    if (sMissingOptions != "")
                        sMissingOptions += ", ";
                    sMissingOptions += GetAttribute(objVariant, "variant");
                }
                else
                {
                    if (sOptions != "")
                        sOptions += ", ";
                    sOptions += GetAttribute(objVariant, "variant") + ": " + objVariant.value;
                }
            }
        }
        
        if (sMissingOptions != "")
        {
            AddError("Select product options: " + sMissingOptions);
        }            
        else if (sWebEnabled == null)
        {
            // Variant lists all with only 1 item, thus, no selection could hvae been made, 
            // so, no onchange event for list, thus, no info was ever requested, so, we have to do it now
            fDelayedAddToCart = true;
            iDelayedInCart    = iInCart;
            iDelayedInventory = iInventory;
            fDelayedSubmit    = fSubmit;
            fDelayedCheckout  = fCheckout;
            Product_OnVariantChange(iItemID);
            return;
        }
        else if (sWebEnabled != "1")
        {
            fErrorHeader = false;
            AddErrorEx(sProductNotAvailableMsg + "\r\n\r\n" + sOptions, false);
        }
        else
        {
            fInStock = sInStock == "1";
            sOptions = "\r\n\r\n" + sOptions;
        }
    }

    var iQuantity   = 1; 
    var objQuantity = document.getElementById("quantity_" + iItemID);
    
    if (objQuantity != null)
    {
        trim(objQuantity);
        
        if (objQuantity.value != "")
        {
            var sDefValue = Product_GetDefValue(objQuantity).toLowerCase();
            
            if ((sDefValue != "") && (objQuantity.value.toLowerCase() == sDefValue))
            {
                if (!ValidateNumberMM(objQuantity, "", ""))
                    objQuantity.value = 1;
            }
        }
        else
        {
            objQuantity.value = 1;
        }
            
        if (CheckNumberValueMM(objQuantity, true, 1, ""))
        {
            AddError("Quantity value is invalid");
            fErrorOk = false;
        }
        else
        {
            iQuantity = parseInt(objQuantity.value);
        }
    }
    
    if (!HasError())
    {
        var iExceedsInventory = iInventory - (iQuantity + iInCart);
        
        if (!fInStock || (iExceedsInventory < 0))
        {
            // For none variant items, check if we allow out of stock purchases
            if (fPromptIfOOS)
            {
                fErrorHeader = false;
                
                var iActualQuantity = iQuantity;
                var sMsg            = sProductOutOfStockMsg + sOptions;
                
                if (true)
                {
                    // Here due to attempting to add more items that are in inventory for an instock item
                    sMsg += "\r\n\r\nCart " + (fAcceptIfOOS ? "will" : "would") + " exceed inventory by " + Math.abs(iExceedsInventory);
                    if (fAcceptIfOOS)
                    {
                        iActualQuantity = iQuantity + iExceedsInventory;
                        
                        if (iActualQuantity > 0)
                            sMsg += "\r\n" + "Only " + (iQuantity + iExceedsInventory) + " will be added to your cart";
                    }
                }
                
                AddErrorEx(sMsg, false);
                fErrorOk = fAcceptIfOOS;
            }
        }                        
    }
                
    if (HasError())
        DisplayErrorEx(fErrorHeader);
    
    if (fSubmit && (fErrorOk || !HasError()))
    {
        if (iQuantity == 0)
        {
            iQuantity = 1;
        }            
        else if (!fAcceptIfOOS && (iQuantity > iInventory))
        {   
            iQuantity = iInventory;
        }
            
        document.frmProducts.AddToCart.value = iItemID;
        document.frmProducts.Variants.value  = sVariants;
        
        if (document.frmProducts.AddQuantity != null)
            document.frmProducts.AddQuantity.value = iQuantity;

        if (document.frmProducts.BuyNow != null)
            document.frmProducts.BuyNow.value = fCheckout ? 1 : 0;

        fAddingToCart = true;
        document.frmProducts.submit();
    }        
}

function Product_GetImageObject(iItemID, iIndex)
{
    return document.getElementById("productimage-" + iItemID + "-" + iIndex);
}

function Product_GetBackgroundImage(obj)
{
    var sImage = obj.style.backgroundImage;
    var iS     = sImage.indexOf("(");
    var iE     = sImage.indexOf(")");
    
    return sImage.substr(iS + 1, iE - iS - 1).toLowerCase();
}

function Product_IsImageTag(obj)
{
    return obj.tagName.toLowerCase() == "img";
}

function Product_GetImage(objImage)
{
    var sImage;
    
    if (Product_IsImageTag(objImage))
    {
        sImage = objImage.src;
    }
    else
    {
        sImage = Product_GetBackgroundImage(objImage);
    }
    return sImage;
}

function Product_SetImage(objImage, sImage)
{
    if (Product_IsImageTag(objImage))
    {
        objImage.src = sImage;
    }
    else
    {
        objImage.style.backgroundImage = "url(" + sImage + ")";
    }
}

function Product_CompareImage(objImage, sImage)
{
    var sImageCur = Product_GetImage(objImage);
    
    return sImage.toLowerCase() == sImageCur.toLowerCase();
}

function Product_ResetImage(objImage)
{
    if (objImage != null)
    {
        var sOrgImage = GetAttribute(objImage, "OrgImage");
        
        if (sOrgImage != null)
        {
            if (!Product_CompareImage(objImage, sOrgImage))
                Product_SetImage(objImage, sOrgImage);
        }                            
    }            
}

function Product_InitImage(objImage)
{
    if (objImage != null)
    {
        var sOrgImage = GetAttribute(objImage, "OrgImage");

        if ((sOrgImage == null) || (sOrgImage == ""))
            SetAttribute(objImage, "OrgImage", Product_GetImage(objImage));
    }
}

function Product_UpdateImage(objImage)
{
    if (objImage != null)
    {
        var sImage      = GetAttribute(objImage, sImageVariantIDs);
        var sWebEnabled = GetAttribute(objImage, sImageVariantIDs + "_WebEnabled");
        var sInStock    = GetAttribute(objImage, sImageVariantIDs + "_InStock");
        var sInCart     = GetAttribute(objImage, sImageVariantIDs + "_InCart");
        var sInventory  = GetAttribute(objImage, sImageVariantIDs + "_Inventory");
        var objVariant  = Product_Variant(iImageItemID, 0);
        
        SetAttribute(objVariant, "WebEnabled", sWebEnabled);
        SetAttribute(objVariant, "InStock",    sInStock);
        SetAttribute(objVariant, "InCart",     sInCart);
        SetAttribute(objVariant, "Inventory",  sInventory);
        
        if (sImage == "0")                
        {
            // retrieved image but it did not exist
            Product_ResetImage(objImage);    
        }                
        else
        {
            Product_SetImage(objImage, sImage);
        }            
    }        
}

function Product_UpdateItemInfo(objVariant, sItem, fConvert)
{
    var sValue = GetAttribute(objVariant, sImageVariantIDs + "_" + sItem);
    
    if ((sValue != "") && (sValue != null))
    {
        var rSpans = document.getElementsByTagName("SPAN");
        
        if ((rSpans != null) && (rSpans.length > 0))
        {
            var sClass = "product-" + sItem + "-" + iImageItemID;
            var iSpan;
            
            for (iSpan = 0; iSpan < rSpans.length; iSpan++)
            {
                if (rSpans[iSpan].className.substr(0, sClass.length) == sClass)
                {
                    if (fConvert)
                        sValue = unescape(sValue);
                        
                    rSpans[iSpan].innerHTML = sValue;
                }                    
            }            
        }                
    }        
}

function Product_UpdateInfo()
{
    var objVariant = Product_Variant(iImageItemID, 0);
    
    iVariantItemID = parseInt(GetAttribute(objVariant, sImageVariantIDs + "_VItemID"));
    
    Product_UpdateItemInfo(objVariant, "Title",           true);           
    Product_UpdateItemInfo(objVariant, "Price",           false);           
    Product_UpdateItemInfo(objVariant, "MSRP",            false);            
    Product_UpdateItemInfo(objVariant, "PriceL1",         false);         
    Product_UpdateItemInfo(objVariant, "PriceL2",         false);         
    Product_UpdateItemInfo(objVariant, "PriceL3",         false);         
    Product_UpdateItemInfo(objVariant, "LookupCode",      true);      
    Product_UpdateItemInfo(objVariant, "DescriptionWeb",  true);  
    Product_UpdateItemInfo(objVariant, "Description",     true);
    Product_UpdateItemInfo(objVariant, "Description1",    true);    
    Product_UpdateItemInfo(objVariant, "Description2",    true);    
    Product_UpdateItemInfo(objVariant, "Description3",    true);    
    Product_UpdateItemInfo(objVariant, "Description4",    true);    
    Product_UpdateItemInfo(objVariant, "FullDescription", true); 
    Product_UpdateItemInfo(objVariant, "Inventory",       false);        
    Product_UpdateItemInfo(objVariant, "GalleryCnt",      false);        
    Product_UpdateItemInfo(objVariant, "Total",           false);        
    Product_UpdateItemInfo(objVariant, "Quantity",        false);        
}

function Product_GetImages()
{
    // See if we already retrieved this image
    var objImage = (objImageS != null) ? objImageS : objImageD;
    var sImage   = GetAttribute(objImage, sImageVariantIDs);

    if ((sImage == null) || (sImage == ""))
    {
        var iCartID = (document.frmProducts.CartID == null) ? 0 : document.frmProducts.CartID.value;
            
        // Have not retrieved this image yet
        fGettingProductInfo = true;
        
        var sEscaped = escape(sImageVariants);
        
        ExecutePage(sGetVariantImagePage + iImageItemID + "&CartItems=" + escape(sCurCartItems) + "&Variants=" + escape(sImageVariants));
    }                
    else 
    {
        Product_UpdateImage(objImageS);
        Product_UpdateImage(objImageD);
        Product_UpdateInfo();
    }        
}

function Product_OnVariantChange(iItemID)
{
    objImageS        = null;
    objImageD        = null;
    iImageItemID     = iItemID;
    iVariantItemID   = 0;
    sImageVariants   = "";
    sImageVariantIDs = "vi";

    var iVariant;
    var fPartialSelection = false;
    
    for (iVariant = 0; iVariant < 3; iVariant++)
    {
        var objVariant = Product_Variant(iItemID, iVariant);
        
        if (objVariant != null)
        {
            fPartialSelection = (objVariant.selectedIndex < 0) || ((objVariant.selectedIndex == 0) && (objVariant.options.length > 1));
            if (fPartialSelection)
                break;

            if (iVariant == 0)
            {
                SetAttribute(objVariant, "WebEnabled", "");
                SetAttribute(objVariant, "InStock",    "");
                SetAttribute(objVariant, "InCart",     "");
                SetAttribute(objVariant, "Inventory",  "");
            }                
        }
                
        if (sImageVariants != "")
            sImageVariants += "\t";

        sImageVariants   += (objVariant == null) ? ""  : objVariant.value;
        sImageVariantIDs += "-" + ((objVariant == null) ? "0" : objVariant.selectedIndex);
    }

    objImageS = Product_GetImageObject(iImageItemID, 1);
    objImageD = Product_GetImageObject(iImageItemID, 2);

    Product_InitImage(objImageS);
    Product_InitImage(objImageD);
        
    if (fPartialSelection)
    {
        Product_ResetImage(objImageS);
        Product_ResetImage(objImageD);
    }
    else
    {
        Product_GetImages();
    }
}    

function Product_SetVariantImage
(
    objImage, 
    sImage, 
    fWebEnabled, 
    iInCart,
    iInventory
)
{
    if (objImage != null)
    {
        var fInStock    = iInventory > 0;
        var sWebEnabled = fWebEnabled ? "1" : "0";
        var sInStock    = fInStock    ? "1" : "0";
        
        SetAttribute(objImage, sImageVariantIDs, (sImage == "") ? "0" : sImage);
        SetAttribute(objImage, sImageVariantIDs + "_WebEnabled", sWebEnabled);
        SetAttribute(objImage, sImageVariantIDs + "_InStock",    sInStock);
        SetAttribute(objImage, sImageVariantIDs + "_InCart",     iInCart);
        SetAttribute(objImage, sImageVariantIDs + "_Inventory",  iInventory);
        
        var objVariant = Product_Variant(iImageItemID, 0);
        
        SetAttribute(objVariant, "WebEnabled", sWebEnabled);
        SetAttribute(objVariant, "InStock",    sInStock);
        SetAttribute(objVariant, "InCart",     iInCart);
        SetAttribute(objVariant, "Inventory",  iInventory);
        
        if (sImage == "")
        {
            Product_ResetImage(objImage);
        }            
        else if (!Product_CompareImage(objImage, sImage))
        {
            Product_SetImage(objImage, sImage);
        }            
    }        
}

function Product_SetVariantInfo
(
    sVItemID,
    sTitle,         
    sPrice,         
    sMSRP,          
    sPriceL1,
    sPriceL2,
    sPriceL3,
    sLookupCode,    
    sDescriptionWeb,
    sDescription1,   
    sDescription2,   
    sDescription3,   
    sDescription4,   
    sFullDescription,
    sInventory,
    sGalleryCnt,
    sTotal,
    sQuantity
)
{
    var objVariant = Product_Variant(iImageItemID, 0);
    
    SetAttribute(objVariant, sImageVariantIDs + "_VItemID",         sVItemID);         
    SetAttribute(objVariant, sImageVariantIDs + "_Title",           sTitle);         
    SetAttribute(objVariant, sImageVariantIDs + "_Price",           sPrice);         
    SetAttribute(objVariant, sImageVariantIDs + "_MSRP",            sMSRP);          
    SetAttribute(objVariant, sImageVariantIDs + "_PriceL1",         sPriceL1);
    SetAttribute(objVariant, sImageVariantIDs + "_PriceL2",         sPriceL2);
    SetAttribute(objVariant, sImageVariantIDs + "_PriceL3",         sPriceL3);
    SetAttribute(objVariant, sImageVariantIDs + "_LookupCode",      sLookupCode);    
    SetAttribute(objVariant, sImageVariantIDs + "_DescriptionWeb",  sDescriptionWeb);
    SetAttribute(objVariant, sImageVariantIDs + "_Description",     sDescription1);
    SetAttribute(objVariant, sImageVariantIDs + "_Description1",    sDescription1);   
    SetAttribute(objVariant, sImageVariantIDs + "_Description2",    sDescription2);   
    SetAttribute(objVariant, sImageVariantIDs + "_Description3",    sDescription3);   
    SetAttribute(objVariant, sImageVariantIDs + "_Description4",    sDescription4);   
    SetAttribute(objVariant, sImageVariantIDs + "_FullDescription", sFullDescription);
    SetAttribute(objVariant, sImageVariantIDs + "_Inventory",       sInventory);
    SetAttribute(objVariant, sImageVariantIDs + "_GalleryCnt",      sGalleryCnt);
    SetAttribute(objVariant, sImageVariantIDs + "_Total",           sTotal);
    SetAttribute(objVariant, sImageVariantIDs + "_Quanity",         sQuantity);
    
    Product_UpdateInfo();
}

function Product_GotProductInfo
(
    iItemID, 
    iVItemID, 
    fWebEnabled, 
    fInStock, 
    sImages,
    sTitle,         
    sPrice,         
    sMSRP,          
    sPriceL1,
    sPriceL2,
    sPriceL3,
    sLookupCode,    
    sDescriptionWeb,
    sDescription1,   
    sDescription2,   
    sDescription3,   
    sDescription4,   
    sFullDescription,
    sInventory,
    sGalleryCnt,
    sTotal,
    sQuantity
)
{
    var sImageS = "";
    var sImageD = "";
    
    if (sImages != "")
    {
        var rsImages = sImages.split("\t");
        
        sImageS = rsImages[0];
        sImageD = rsImages[1];
    }        
    
    Product_SetVariantImage(objImageS, 
                            sImageS, 
                            fWebEnabled, 
                            parseInt(sQuantity),
                            parseInt(sInventory));
                            
    Product_SetVariantImage(objImageD, 
                            sImageD, 
                            fWebEnabled, 
                            parseInt(sQuantity),
                            parseInt(sInventory));
    
    Product_SetVariantInfo(iVItemID,
                           sTitle,         
                           sPrice,         
                           sMSRP,          
                           sPriceL1,
                           sPriceL2,
                           sPriceL3,
                           sLookupCode,    
                           sDescriptionWeb,
                           sDescription1,   
                           sDescription2,   
                           sDescription3,   
                           sDescription4,   
                           sFullDescription,
                           sInventory,
                           sGalleryCnt,
                           sTotal,
                           sQuantity);
                           
    fGettingProductInfo = false;
    if (fDelayedAddToCart)
    {
        fDelayedAddToCart = false;
        Product_AddToCart(iItemID, iDelayedInCart, iDelayedInventory, true, fDelayedSubmit, fDelayedCheckout);
    }
}

function Product_SetVariantValue(iItemID, iVariant, sValue)
{
    var objVariant = Product_Variant(iItemID, iVariant);
    
    if (objVariant != null)
    {
        if (objVariant.options.length == 1)
        {
            objVariant.value = sValue;
        }
        else
        {
            // We don't just assign value Attribute of list, since first item has value of zero, which may match
            // an actual variantitem, so, we just run though the list, starting with the first item
            var i;
               
            for (i = 1; i < objVariant.options.length; i++)
            {
                if (objVariant.options[i].value == sValue)
                {
                    objVariant.options.selectedIndex = i;
                    break;
                }
            }
        }            
    }             
}

function Product_OnSwatchClick(iItemID, sDim1, sDim2, sDim3)
{
    Product_SetVariantValue(iItemID, 0, sDim1);
    Product_SetVariantValue(iItemID, 1, sDim2);
    Product_SetVariantValue(iItemID, 2, sDim3);
 
    Product_OnVariantChange(iItemID);

    window.scrollTo(0, 0);
    
    var objQuantity = document.getElementById("quantity_" + iItemID);
    
    if (objQuantity != null)
    {
        objQuantity.focus();
    }
}

function Product_QuantityOnFocus(obj)
{
    var sDefValue = Product_GetDefValue(obj).toLowerCase();
    
    if (sDefValue != "")
    {
        var sValue = trimEx(obj.value, false).toLowerCase();
    
        // If not a numeric def value, clear its contents
        if ((sValue == sDefValue) && !ValidateNumberMM(obj, "", ""))
            obj.value = "";
    }        
}

function Product_QuantityOnBlur(obj)
{
    var sValue = trimEx(obj.value, false).toLowerCase();
    
    if (sValue == "")
        obj.value = Product_GetDefValue(obj);
}

function Product_QuantityOnKeyDown(obj, evt, iItemID, iQuantity, iInventory, fVariant)
{
    evt = GetEventObj(evt);
    
    if ((evt != null) && (evt.keyCode == 13))
        Product_AddToCart(iItemID, iQuantity, iInventory, fVariant, true, false);
        
    return true;        
}

function Product_OnRolloverUpdateTarget(sSource, objSource, objTarget)
{
    var sCurSource = GetAttribute(objTarget, "Source");
    
    if (sCurSource != "")
    {   
        var objLastSource = document.getElementById(sCurSource);
        
        if (objLastSource != null)
            objLastSource.innerHTML = objTarget.innerHTML;
    }
    
    objTarget.innerHTML = objSource.innerHTML;
    objSource.innerHTML = "";
    
    SetAttribute(objTarget, "Source", sSource);
}

function Product_OnRolloverMouseOver(sSource, sTarget)
{
    var objSource = document.getElementById(sSource);
    var objTarget = document.getElementById(sTarget);
    
    if (objSource != null)
    {
        var fLocked = GetAttribute(objTarget, "Locked") == "1";
        
        if (!fLocked)
            Product_OnRolloverUpdateTarget(sSource, objSource, objTarget);
    }
}

var objLastRolloverSource = null;

function Product_OnRolloverOnClick(sSource, sTarget)
{
    var objSource = document.getElementById(sSource);
    var objTarget = document.getElementById(sTarget);
    
    if (objSource != null)
    {
        var fToggle = objLastRolloverSource == objSource;
        var fLocked = GetAttribute(objTarget, "Locked") == "1";
        
        if (fToggle)
            SetAttribute(objTarget, "Locked", fLocked ? 0 : 1);
        else if (!fLocked)
            SetAttribute(objTarget, "Locked", 1);
        
        Product_OnRolloverUpdateTarget(sSource, objSource, objTarget);
        objLastRolloverSource = objSource;
    }        
}