﻿/* JS to handle new Add to Basket function */    
    
var gBuffer = new Array();
var gDiscountBuffer = new Array();
var gAdding = false;
var gTimeout = null;
var gAddImage = null;
var gPageNotSaved = false;

// Set up the 'Before Unload' handler; note, not all browsers support this
try
{   
    addEvent(window, 'load', loadHandler );
    window.onbeforeunload = beforeUnloadHandler;
}
catch(e)
{
}


function addEvent( obj, type, fn ) {
    if (obj.addEventListener) {
        obj.addEventListener( type, fn, false );
    } else if (obj.attachEvent )    {
        obj['e'+type+fn] = fn;
        obj[type+fn] = function() { obj['e'+type+fn]( window.event ); }
        obj.attachEvent( 'on'+type, obj[type+fn] );
    }
}


function Register()
{
    window.location = '/account/loginregister/registrationrequired.aspx?ReturnUrl=' + escape(window.location.pathname + window.location.search);
}


function MarkFormAsDirty()
{
    var dirtyInput = document.getElementById('hdnDirty');
    
    if (dirtyInput)
        dirtyInput.value = '1';
}

function beforeUnloadHandler()
{
    if (gPageNotSaved)
    {
        return 'You have not saved your changes; if you do not save them they will be lost.';
    }

    if (gBuffer.length > 0 || gAdding)
    {
        if(!gAdding)
        {
            // Must be unprocedded clicks, flush the buffer...
            // Cancle the previous update
            if (gTimeout != null)
            {
                clearTimeout(gTimeout);
            }
            
            // Start a new update countdown for 10ms time
            gTimeout = setTimeout("sendPump()", 10);
        }
        
        return 'Your trolley is still being updated; please wait a few moments and try again';
    }
    else
        MarkFormAsDirty();
}

// Check if the page has bee loaded from the cache and is dirty; if so refresh it.
function loadHandler()
{
    var dirtyInput = document.getElementById('hdnDirty');
    
    if (!dirtyInput)
    {
        return;
    }
    
    if (dirtyInput.value == '1')
    {
        window.location.reload(true);
    }
}

// Reset the page not saved flag
function resetPageNotSaved()
{
    gPageNotSaved = false;
}


// Class to store selected product details.
function ActionClass()
{   
    var productVariantID = '';
    var productID = '';
    var deleted = false;
    var basket = '';
    var hiddenFieldID = '';
    var discountUrl = false;
    var originalValueElementID = '';
    
    this.GetproductVariantID = GetproductVariantID;
    this.SetproductVariantID = SetproductVariantID;
    this.GetproductID = GetproductID;
    this.SetproductID = SetproductID;
    this.Getdeleted = Getdeleted;
    this.Setdeleted = Setdeleted;
    this.GetHiddenFieldID = GetHiddenFieldID;
    this.SetHiddenFieldID = SetHiddenFieldID;
    this.Getbasket = Getbasket;
    this.Setbasket = Setbasket;
    this.toString = toString;
    this.GetDiscountUrl = GetDiscountUrl;
    this.SetDiscountUrl = SetDiscountUrl;
    this.HasDiscounts = HasDiscounts;
    this.SetoriginalValueElementID = SetoriginalValueElementID;
    this.GetoriginalValueElementID = GetoriginalValueElementID;
    this.GetValue = GetValue;
    
    function GetproductVariantID()
    {
        return productVariantID;
    }
    
    function SetproductVariantID(value)
    {
        productVariantID = value;
    }
    
    function GetproductID()
    {
        return productID;
    }
    
    function SetproductID(value)
    {
        productID = value;
    }
    
    function Getdeleted()
    {
        return deleted;
    }
    
    function Setdeleted(value)
    {
        deleted = value;
    }
    
    function GetHiddenFieldID()
    {
        return hiddenFieldID;
    }
    
    function SetHiddenFieldID(value)
    {
        hiddenFieldID = value;
    }
    
    function Getbasket()
    {
        return basket;
    }
    
    function Setbasket(value)
    {
        basket = value;
    }
    
    function GetDiscountUrl()
    {
        return discountUrl;
    }
    
    function SetDiscountUrl(value)
    {
        discountUrl = value;
    }

    function HasDiscounts()
    {
        return !(discountUrl == '' || discountUrl == null);
    }
    
    function GetoriginalValueElementID()
    {
        return originalValueElementID;
    }
    
    function SetoriginalValueElementID(value)
    {
        originalValueElementID = value;
    }
    
    function GetValue()
    {
        var retVal = parseInt(document.getElementById(hiddenFieldID).value);
        if (isNaN(retVal)) retVal = 0;
        return (retVal);
    }
    
    function toString()
    {
        return productID + '|' + productVariantID + '|' + GetValue() + ':'; 
    }
}       

// Find and return the item from the array; if the item does not exist create it and add to the array.
function getArrayItem(variantID, basket)
{
    var item = null;

    if (!gBuffer)
        gBuffer = new Array();
     
    // Cycle through the buffer   
    for (pos = 0; pos < gBuffer.length; pos++)
    {
        if (gBuffer[pos].GetproductVariantID() == variantID
            &&
            gBuffer[pos].Getbasket() == basket)
            {
                item = gBuffer[pos];
                break;
            }
    }
    
    if (!item)
    {
        item = new ActionClass();
        item.SetproductVariantID(variantID);
        item.Setbasket(basket);
        gBuffer.push(item);
    }
    
    return item;
} 

// Called from table JS
// Handles the user changing the quantity of an item in the trolley. If a trolly add then also handles discounts
function touchItemInArray(productID, variantID, deleted, basket, hiddenFieldID, discountUrl, originalValueElementID)
{
    var item = getArrayItem(variantID, basket);
    item.SetproductID(productID);
    item.SetHiddenFieldID(hiddenFieldID);
    item.SetoriginalValueElementID(originalValueElementID);
    item.Setdeleted(deleted);
    
    // Cancle the previous update
    if (gTimeout != null)
    {
        clearTimeout(gTimeout);
    }
    
    // Check to see if the value of this element is greater than the previous value (we are ading)
    var originalValElement = document.getElementById(originalValueElementID);
    var originalVal = parseInt(originalValElement.value);
    if (isNaN(originalVal)) originalVal = 0;
    
    if (originalVal < item.GetValue())
    {
        // this is adding
        if (discountUrl != null && discountUrl != '' && basket == '')
        {
            // Adding a discount, do it now
            item.SetDiscountUrl(discountUrl);
            // Start a new update countdown - almost insatant as a discount has been added
            gTimeout = setTimeout("sendPump()", 10);
        }
        else
        {
            // No discount, take a second before updating
            item.SetDiscountUrl(null);
            // Start a new update countdown
            gTimeout = setTimeout("sendPump()", 500);
        }
    }
    else
    {
        // This is removing products, do not add the discount
        item.SetDiscountUrl(null);
        // Start a new update countdown
        gTimeout = setTimeout("sendPump()", 500);
    }
    
    // Change the background
    selectBackground();
}

var tempImageUsed = false;
// Changes the background colour of the summary
function selectBackground()
{
    if(!document.getElementById('tsLeft'))
        return;
    document.getElementById('tsLeft').src = '/images/trolleysummary/highlighted/left.gif';
    document.getElementById('tsBackground1').style.backgroundImage = 'url(/images/trolleysummary/highlighted/background.gif)';
    document.getElementById('tsBackground2').style.backgroundImage = 'url(/images/trolleysummary/highlighted/background.gif)';
    document.getElementById('tsDivider').src = '/images/trolleysummary/highlighted/divider.gif';
    document.getElementById('tsRight').src = '/images/trolleysummary/highlighted/right.gif';
    document.getElementById('tsIcon').src = '/images/trolleysummary/highlighted/trolleyicon.gif';
    
    // show a temp image whilst we wait for updated image (same amount but green background)
    if (tempImageUsed)
        return;
        
    var gTempCallImage = document.getElementById('gTempCallImage');
    
    var gCallImage = document.getElementById('gCallImage');
    if (gCallImage == null) 
	    gCallImage = document.getElementById('gCallImage2');

	if (gCallImage != null && gTempCallImage != null)	{
        gCallImage.src = gTempCallImage.src
        tempImageUsed = true
    }
    
}

// Array proccessing pump; processes the array contents and starts the update
function sendPump()
{
    gTimeout = null;
    
    var headerClient = 'SHC_TSC';
    var bTrolley = true;

    if (gAdding)
        return;

    if (gBuffer.length == 0)
        return;
        
    // Process the array, five items at a time
    var gAddImageSrc = '/catalog/AddMultiTrolley.aspx?';
    
    // Add some uniqueness to the url to avoid browser caching issues
	var currentDate = new Date();
	var uniqueValue = Date.UTC(currentDate.getYear(), currentDate.getMonth(), currentDate.getDay(), currentDate.getHours(), currentDate.getMinutes(), currentDate.getSeconds(), currentDate.getMilliseconds());
	gAddImageSrc += 'uv=' + uniqueValue;
	
	// ASSUMPTION - ONLY ONE BASKET PER PAGE AT THE MOMENT
    var basketName = gBuffer[0].Getbasket();
    
    if (basketName != '')
    {
        // adding to a basket, not the trolley
        gAddImageSrc += '&shoppingList=' + encodeURI(basketName);
        
        // Hand the url over to the image, so that it requests the add to trolley
	    //gAddImage = new Image();
	    var gCallImage = document.getElementById('gAddToBasketImage');
	    
	    bTrolley = false;
    }
	
	else
	{
	    // Hand the url over to the image, so that it requests the add to trolley
	    //gAddImage = new Image();
	    var gCallImage = document.getElementById('gCallImage');
	    if (gCallImage == null) 
	        gCallImage = document.getElementById('gCallImage2');
	        
	    //gCallImage = new Image();
	        
	    bTrolley = true;
	}
	   
	gAddImage = gCallImage;
	
	if (gCallImage == null)
	    gCallImage = new Image();
	
	
	var tempBuffer = new Array();
    var max = gBuffer.length;
    var unprocessedVars = '';
    
    if (!gDiscountBuffer)
        gDiscountBuffer = new Array();
    
    
    var lineDelta = 0;
    var productDelta = 0;
    
    // Cycle through the buffer   
    for (pos = 0; pos < max; pos++)
    {
        var item = gBuffer.shift();
        
        //if (item.Getbasket() == '')
        //{
            unprocessedVars += item.toString();
            
            // Update the rows and line items counts
            var originalElement = document.getElementById(item.GetoriginalValueElementID());
            
            //alert (originalElement.value);
            
            var itemValue = parseInt(item.GetValue());
            var originalValue = parseInt(originalElement.value);
            
            if (isNaN(itemValue)) itemValue = 0;
            if (isNaN(originalValue)) originalValue = 0;
            
            if(item.Getdeleted() == 'False')
            {
            
            if (originalValue == 0)
            {
                // We are moddifiying a row with no previous value
                if (itemValue != 0)
                {
                    lineDelta++; // increment the row count
                    productDelta += itemValue; //increment the product count;
                }   
            }
            else
            {
                // We are moddifiying a row with a previous value
                if (itemValue != 0)
                {
                    //ROWCOUNT - NO CHANGE
                    //alert ('No line change, product delta = ' + (itemValue - originalValue));
                    productDelta += (itemValue - originalValue); //increment the product count
                }
                else
                {
                    // removing a row
                    //alert ('Line count reduced by 1, product delta = ' + (itemValue - originalValue));
                    lineDelta--; // decrement the row count
                    productDelta += (itemValue - originalValue); //increment the product count
                }
            }  
            }         
            
            // update the original value
            originalElement.value = itemValue;
            
        //}
        //else
        //    tempBuffer.push(item);
            
            
        // If the item has discounts, push it onto that buffer too
        if (item.HasDiscounts())
            gDiscountBuffer.push(item);
    }
    
             
       
    // Update the minitrolley values
    // Get references to the products/lines elements to update them
    if(lineDelta != 0 && bTrolley)
    {
	    var hidLinesElement = document.getElementById(headerClient + "_hidLines");
        var linesElement = document.getElementById(headerClient + "_lblLines");
        
        if (linesElement == null)
            linesElement = document.getElementById(headerClient + "_lblLines2");
            
        hidLinesElement.value = +hidLinesElement.value + +lineDelta;
        linesElement.innerHTML = '(' + hidLinesElement.value + ' lines)';
    }

    // Add quantity to the products total
    if(productDelta != 0 && bTrolley)
    {
        var hidProductsElement = document.getElementById(headerClient + "_hidProducts");
        var productsElement = document.getElementById(headerClient + "_lblProducts");   
        
        if (productsElement == null)
            productsElement = document.getElementById(headerClient + "_lblProducts2");
        
        hidProductsElement.value = +hidProductsElement.value + +productDelta;
        productsElement.innerHTML = hidProductsElement.value;
    }

	
	//alert (unprocessedVars);
	
	gAddImageSrc += "&VARS=" + unprocessedVars
	
	gBuffer = tempBuffer;
	
	if (bTrolley)
	    gCallImage.onload = function (){ onAddImageLoaded('SHC_TSC') };
	else
	    gCallImage.onload = function (){ onAddToBasketImageLoaded() };
	
	gCallImage.src = gAddImageSrc;
	
	gAdding = true;
	
    return;
    
    
    // Cycle through the discount buffer and render that too
    //for (pos = 0; pos < gDiscountBuffer.length; pos++)
    //{
        //textbox.value += " -- Discounts: " + gDiscountBuffer[pos].GetproductVariantID();
    //}
}

/*
	Callback when the remote call image finishes loading for trolley adds
*/
function onAddImageLoaded(headerClient)
{
    var succeeded = (gAddImage.width == 65);
	//var newLine = (gAddImage.height == 13);
	
	if (!succeeded)
	    window.location.reload(true);
	    
	gAdding = false;
	
	//Check to see if the buffer is empty
	if (gBuffer.length == 0)
	{
	    // Empty buffer, check the discount buffer
	    if (gDiscountBuffer.length > 0)
	    {
	        //redirect to the first discount
	        var item = gDiscountBuffer[0];
	        
	        window.location.href=(item.GetDiscountUrl());
	    }
	}
	else
	{
	    // there are still items in teh buffer, start the 5 second countdown again
        if (gTimeout != null)
        {
            clearTimeout(gTimeout);
        }
        
        // Start a new update countdown
        gTimeout = setTimeout("sendPump()", 10);
	}
}

/*
	Callback when the remote call image finishes loading for basket adds
*/
function onAddToBasketImageLoaded(headerClient)
{
    var succeeded = (gAddImage.width == 65);
	//var newLine = (gAddImage.height == 13);
	
	if (!succeeded)
	    window.location.reload(true);
	    
	gAdding = false;
	
	//Check to see if the buffer is empty
	if (gBuffer.length != 0)
	{
	    // there are still items in teh buffer, start the 5 second countdown again
        if (gTimeout != null)
        {
            clearTimeout(gTimeout);
        }
        
        // Start a new update countdown
        gTimeout = setTimeout("sendPump()", 100);
	}
}


// Add quantity to list event handler
function AQTL(controlName, columnName, row)
{

    // BSLC_0_QuantityInTrolley_d
    
    var textboxId = controlName + '_' + row + '_QuantityInTrolley_d';
    var quantityId = controlName + '_' + row + '_' + columnName + '_d';
    var textbox = document.getElementById(textboxId);
    
    //alert (textboxId);
    //alert (quantityId);
    
    if (textbox == null)
        return;
    
    var tbValue = parseInt(textbox.value);
    if (isNaN(tbValue)) tbValue = 0;
        
    var quantityElement = document.getElementById(quantityId);
        
        
    var quantity = parseInt(quantityElement.innerHTML);
    if (isNaN(quantity)) quantity = 0;
 
    
 
    tbValue += quantity;
    
    textbox.value = tbValue;
    
    // Manualy fire the keyup event
    if (textbox.dispatchEvent)
    {
        // supports standard events
        if( window.KeyEvent ) 
        {
            var evObj = document.createEvent('KeyEvents');
            evObj.initKeyEvent( 'keyup', true, true, window, false, false, false, false, 13, 0 );
        }
        else
        {
            var evObj = document.createEvent('UIEvents');
            evObj.initUIEvent( 'keyup', true, true, window, 1 );
            evObj.keyCode = 13;
        }
        textbox.dispatchEvent(evObj);
    }
    else
    {
        // IE events
        if( document.createEvent )
        {
            var evObj = document.createEvent('KeyEvents');
            evObj.initEvent( 'keyup', true, false );
            textbox.dispatchEvent(evObj);
        } 
        else if( document.createEventObject ) 
        {
            textbox.fireEvent('onkeyup');
        }
    }
}


// JS to update the colour of rows bassed on quanity values
function UpdateRowColours (quantityElement, updateRed, updateGreen)
{
    if (updateRed == 0 && updateGreen == 0)
        return;
        
    itemValue = parseInt(quantityElement.value);
    if (isNaN(itemValue)) itemValue = 0;
    
    //alert (quantityElement.value + ' : ' + updateRed + ' : ' + updateGreen);
    
    if (itemValue == 0)
    {
        // a 0 item value
        if (updateRed == 1)
        {
            // set the row to be red
            quantityElement.parentNode.parentNode.className = 'productHighlightRed';
        }
        else
        {
            // set the row to be empty
            quantityElement.parentNode.parentNode.className = '';
        }
    }
    else
    {
        // a positive item value
        if (updateGreen == 1)
        {
            // set the row to be green
            quantityElement.parentNode.parentNode.className = 'productHighlightGreen';
        }
        else
        {
            // set the row to be empty
            quantityElement.parentNode.parentNode.className = '';
        }
    }
    
    // update "in trolley" status
    var labels = quantityElement.parentNode.getElementsByTagName('span');
    if(labels.length == 1)
    {
        if(itemValue > 0)
            labels[0].style.visibility = "visible";
        else
            labels[0].style.visibility = "hidden";
    }
}
