// Documentation
//
// 16 Jul 2008  Tomasz Izydorczyk    Adjusted to the ASP ProductCompare page functionality.
// 21 Jul 2008  Ralph Barton         Legacy Basket Enabled test now done as string
// 25 Jul 2008  Ralph Barton         Added AddToBasketInit and AddToBasketSimple functions.
// 01 Dec 2008  John Foster          Bug 20082: Work around for webkit bug

// Define global javascript variables for adding to basket
var _returnUrl = '';
var _legacyBasketEnabled = false;

function AddToBasketInit(returnUrl, legacyBasketEnabled)
{
    _returnUrl = returnUrl;
    _legacyBasketEnabled = legacyBasketEnabled;
}

function AddToBasketSimple(partId, quantity)
{
    AddToBasketWithQuantity(partId, quantity, _returnUrl, _legacyBasketEnabled);
}

// Modifies the page's Form action to post to the basket with the product ID and quantity to add.
function AddToBasket(partID, qtyID, returnUrl, legacyBasketEnabled) {
	var quantity = document.getElementById(qtyID).value;
	AddToBasketWithQuantity(partID, quantity, returnUrl, legacyBasketEnabled);
}


function AddToBasketWithQuantity(partID, qty, returnUrl, legacyBasketEnabled)
{
    // Convert value to lower case string so we know the type
    legacyBasketEnabled = legacyBasketEnabled.toString().toLowerCase();
    
    if (legacyBasketEnabled == 'true') 
    {
        AddToLegacyAspBasket(partID, qty, returnUrl);
    }
    else
    {
        AddToDotNetBasket(partID, qty, returnUrl);
    }
}

function AddToLegacyAspBasket(partID, qty, returnUrl)
{
    // Submitting to the ASP legacy basket
    document.getElementById("inpAction").value = 'AddItem';
    document.getElementById("inpItemType").value = 'Part';
    document.getElementById("inpPartID").value = partID;
    document.getElementById("inpQuantity").value = qty;
    document.getElementById("inpReturnLocation").value = returnUrl;
    // Submit the aspnetForm
    theForm.action = 'ShoppingBasket.asp?step=1&mode=add';
    if (navigator.userAgent.toLowerCase().indexOf("webkit") != -1) {
        setTimeout(function() { theForm.submit(); }, 1);
    }
    else {
        theForm.submit();
    }
}

function AddToDotNetBasket(partID, qty, returnUrl)
{
    // Get the basket url that is stored in the form
    var basketUrl = unescape(document.forms[0].basketUrl.value);

    // Derive the complete basket url taking into account existing QS values
    var separator = "?";
    var separatorIndex = basketUrl.indexOf(separator); 
    if (separatorIndex >= 0) separator = "&";  
    var completeUrl = basketUrl + separator + "pid=" + partID + "&qty=" + qty;

    // Set the returnUrl if there is one
    if (returnUrl.length > 0) {
	    completeUrl = completeUrl + '&returnURL=' + encodeURIComponent(returnUrl);
    }

    window.location.href = completeUrl;
}

