// 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
// 30 Sep 2010	Colin Turner		 Corrected error messages and sequence of basket and error message output.

// 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;
}

function AddPartsToBasket(partId, quantity) 
{
	quantity = quantity || 1;
	$.ajax( {
		url : $("input[name='addToBasketUrl']").val(),
		data : { partId: partId, quantity: quantity },
        type : "post",
		                		
		error : function() {
			alert('Unable to add the part to the basket.');
        },

        success : function(responseText) {

			// Get the contents of the basket from the call
			var basketDiv = $(responseText).filter(function() {
				return $(this).is(".left_nav_basket");
			});
			
			var errorMessage = $(responseText).filter(function() {
				return $(this).is("#ErrorMessage");
			}).text();
			
			// Replace the basket contents
			if (basketDiv.length > 0) {
			
				$(".left_nav_basket").replaceWith(basketDiv);
				
				if (errorMessage.length > 0) {
					alert('Unable to add the part(s) to the basket. ' + errorMessage);
				}
			}
			else {			
				alert('Unable to add the part(s) to the basket. ' + errorMessage);
			}
        }
   });
}

function AddPartsToBasketFromUnity(partNo, quantity) 
{
	quantity = quantity || 1;
	$.ajax( {
		url : $("input[name='addToBasketUrl']").val(),
		data : { partNo: partNo, quantity: quantity },
        type : "post",
		                		
		error : function() {
			// Send the message back to the unity model.
			GetUnity().SendMessage("PlayerCamera", "BasketUpdateFail", "An error occured adding the items to the basket.");
        },

        success : function(responseText) {

			// Get the contents of the basket from the call
			var basketDiv = $(responseText).filter(function() {
				return $(this).is(".left_nav_basket");
			});
			
			var errorMessage = $(responseText).filter(function() {
				return $(this).is("#ErrorMessage");
			}).text();
			
			// Replace the basket contents if there is anything to show.
			if (basketDiv.length > 0) {
			
				$(".left_nav_basket").replaceWith(basketDiv);
			}
			
			if (errorMessage.length > 0) {
							
				GetUnity().SendMessage("PlayerCamera", "BasketUpdateFail", errorMessage);
			}
			else {
			
				GetUnity().SendMessage("PlayerCamera", "BasketUpdateSuccess", "Items added to the basket.");
			}	
        }
   });
}
