﻿var Shop_mAppRoot;          // The absolute path to the application root

var Shop_mPageBody;        // Reference to scrollable section of all pages

var Shop_mFixedBar;

var Shop_mLoadedHeight = 36;
var Shop_mImageSpacing = 40;
var Shop_mHideStages = 4;

var Shop_mFloatingItemType;
var Shop_mFloatingRequestType;
var Shop_mFloatingItemID;   // The stock item which the current floating image belongs to
var Shop_mFloatingSuffixID;
var Shop_mFloatingImage;    // The currently displayed floating image
var Shop_mLoadingImage;     // Loading image to display before real image has loaded
var Shop_mDisplayedFloatingImage; // Reference to the currently displayed image: Either the loading image or the real image
var Shop_mHideFloatingImage;// The timeout to hide the floating image
var Shop_mHideFloatingImageStage;// The current stage of hiding the floating image
var Shop_mAlignFloatingImage;// The timeout to aligne the floating image to the bottom of the screen
var Shop_mStopAlignImage;   // Flag to stop checking for image alignment
var Shop_mFloatingImageElement;
var Shop_mTooltipElement;

var Shop_mDelaySrcElement;  // The element which started the hover
var Shop_mDelayX;           // The position of the element
var Shop_mDelayY;
var Shop_mDelayRequestType;
var Shop_mDelayItemType;    // Is the item a stock item or suffix
var Shop_mDelayItemID = 0;  // The ID of the item to be shown
var Shop_mDelaySuffixID = 0;
var Shop_mDelayTimer;       // The timer to show the image once the mouse has been over the code for long enough
var Shop_mShownItemType;
var Shop_mShownItemID = 0;  // The item currently displayed by the delay call

var Shop_mPopupRequestInProgress = 0;   // Flag to ensure that only one request to the service is made at a time
var Shop_mQueuedPopupRequestType;
var Shop_mQueuedPopupRequestID;         // ID of the next item to request from the service
var Shop_mQueuedPopupTimer;             // Timer to space out requests to the service

var Shop_mLastSelected;     // The last selected checkbox, used for shift select of stock items

// Set up page on load
function Shop_OnLoad ( ) {
    Shop_SetupAppRoot();
    Shop_SetupFixedBar();
    Shop_CreateFloatingImages ( );
}

// Set up the scrollable area of the page
function Shop_SetupAppRoot ( ) {
    try {
        Shop_mAppRoot = document.getElementById ( 'ShopAppRoot' ).getElementsByTagName ( "SPAN" )[0].getAttribute ( "ApplicationRoot" );
    } catch ( e ) {
        Shop_mAppRoot = "/";
    }
    
    // Store reference to scrollable area
    Shop_mPageBody = document.getElementById ( 'PageBody' );
}

function Shop_SetupFixedBar() {
    Shop_mFixedBar = document.getElementById("FixedBar");
    if (!Shop_mFixedBar) return;

    if (window.addEventListener) {
        window.addEventListener("scroll", Shop_AlignFixedBar, false);
    } else {
        window.attachEvent("onscroll", Shop_AlignFixedBar);
    }
}

function Shop_AlignFixedBar() {
    var pageTop = Shop_GetPageTop();
    var parentTop = Shop_mFixedBar.offsetParent.offsetTop;
    var relativeTop = pageTop - parentTop;

    Shop_mFixedBar.style["top"] = ( (relativeTop < 0) ? 0 : relativeTop ) + "px";
}

function Shop_CreateFloatingImage ( element ) {
    // Create a single hidden image
    var image = document.createElement ( element );
    image.className = "Popup";
    image.style["display"] = "none";

    return image;
}

function Shop_CreateFloatingImages ( ) {
    // Create the required hidden images
    Shop_mLoadingImage = Shop_CreateFloatingImage ( "IMG" );
    Shop_mLoadingImage.src = Shop_mAppRoot + "Images/Loading.gif";
    
    // Add the hidden images to the document
    Shop_mPageBody.appendChild ( Shop_mLoadingImage );

    Shop_mFloatingItemID = 0;
    Shop_mFloatingSuffixID = 0;
}

function Shop_ResetFloatingImage ( image, x ,y ) {
    // Reset the display properties of a hidden image
    image.style["opacity"] = 1;
    image.style["filter"] = "alpha(opacity=100)";
    image.style["left"] = x + "px";
    image.style["top"] = y + "px";
    image.style["visibility"] = "hidden";
    image.style["display"] = "block";
}

function Shop_ResetDelayTimer ( ) {
    // Stop the delay timer and start it again
    if ( Shop_mDelayTimer ) {
        window.clearTimeout ( Shop_mDelayTimer );
    }
    Shop_mDelayTimer = window.setTimeout ( Shop_DelayShowHide, 250 );
}

function Shop_ShowImage ( e ) {
    // Store the details and start the delay timer
    
    // Find the delay element
    Shop_mDelaySrcElement = e.srcElement || e.target;
    if (Shop_mDelaySrcElement.nodeType == 3) { // This is a text node
        Shop_mDelaySrcElement = Shop_mDelaySrcElement.parentNode;
    }
    if ( Shop_mDelaySrcElement.className != "ImageHover" ) {
        Shop_mDelaySrcElement = Shop_mDelaySrcElement.parentNode;
    }

    var coSource = e.srcElement || e.target;
    
    Shop_mDelayX = Shop_mImageSpacing;
    Shop_mDelayY = 0;

    do {
        Shop_mDelayX += coSource.offsetLeft;
        Shop_mDelayY += coSource.offsetTop;
    } while (coSource = coSource.offsetParent);

    // Find the item ID for this element
    var itemType = "StockItem";
    var itemID = Shop_mDelaySrcElement.getAttribute("StockItemID");
    Shop_mDelaySuffixID = 0;
    if (!itemID) {
        itemID = Shop_mDelaySrcElement.getAttribute("SwatchID");
        itemType = "Swatch";
        Shop_mDelaySuffixID = Shop_mDelaySrcElement.getAttribute("SuffixID"); 
    }
    if (!itemID) {
        itemID = Shop_mDelaySuffixID;
        itemType = "Suffix"; 
    }

    Shop_mDelayItemID = itemID;
    Shop_mDelayItemType = itemType;
    Shop_mDelayRequestType = (Shop_mDelaySrcElement.getAttribute("Discount") == "True") ? "discount" : "image";
    
    if ( ! itemID ) Shop_mDelayItemID = 0;
    
    // Start the delay timer
    Shop_ResetDelayTimer ( );
}

function Shop_HideImage ( ) {
    // Clear the delay stock item ID and start the delay timer
    Shop_mDelayItemID = 0;
    Shop_ResetDelayTimer ( );
}

function Shop_DelayShowHide ( ) {
    // The delay timer has fired
    if ( Shop_mDelayItemID != Shop_mShownItemID || Shop_mDelayItemType != Shop_mShownItemType ) {
        // The stock item ID is now not the same as the currently shown item
        Shop_mShownItemID = Shop_mDelayItemID;
        Shop_mShownItemType = Shop_mDelayItemType;
        
        if ( ! Shop_mDelayItemID ) {
            // There is no delay item, hide the currently shown item
            Shop_DelayHideImage ( );
        } else {
            // There is a delay item, show it
            Shop_DelayShowImage ( );
        }
    }
}

function Shop_ResetTooltip() {
    if (Shop_mTooltipElement) {
        Shop_mTooltipElement.setAttribute("title", Shop_mTooltipElement.getAttribute("PreviousTitle"));
    }
}

function Shop_DelayShowImage ( ) {
    if ( ! Shop_mLoadingImage ) {
        // The floating image has not yet been set up, stop
        return;
    }

    Shop_ResetTooltip();
    
    // Get the Stock Item to show the image for
    var srcElement = Shop_mDelaySrcElement;
    Shop_mTooltipElement = srcElement;
    srcElement.setAttribute("PreviousTitle", srcElement.title);
    srcElement.setAttribute("title", "");
    
    // Stop any pending timer to remove the image
    if ( Shop_mHideFloatingImage ) {
        window.clearTimeout ( Shop_mHideFloatingImage );
        Shop_mHideFloatingImage = 0;
    }

    if ( Shop_mFloatingItemID != Shop_mDelayItemID || Shop_mFloatingItemType != Shop_mDelayItemType || Shop_mFloatingRequestType != Shop_mDelayRequestType ) {
        // The floating image is not for this stock item, load the image
        if ( Shop_mFloatingImage ) {
            Shop_mPageBody.removeChild ( Shop_mFloatingImage );
        }
        
        // Create a DIV to hold the image and the popup details
        Shop_mFloatingImage = Shop_CreateFloatingImage ( "DIV" );
        // Catch mouse entry into the DIV, using the appropriate method for the browser
        if ( window.addEventListener ) {
            Shop_mFloatingImage.addEventListener ( "mouseover", Shop_EnterFloating, false );
            Shop_mFloatingImage.addEventListener ( "mouseout", Shop_HideImage, false );
        } else {
            Shop_mFloatingImage.attachEvent ( "onmouseover", Shop_EnterFloating );
            Shop_mFloatingImage.attachEvent ( "onmouseout", Shop_HideImage );
        }
        Shop_mPageBody.appendChild ( Shop_mFloatingImage );
        
        // Create the IMG element and request the image
        if ( Shop_mDelaySrcElement.getAttribute ( "Image" ) == "True" ) {
            Shop_mFloatingImageElement = document.createElement ( "IMG" );
            Shop_mFloatingImage.appendChild ( Shop_mFloatingImageElement );
            
            Shop_mFloatingImageElement.src = Shop_mAppRoot + "Handlers/" + Shop_mDelayItemType + "Image.ashx?" + Shop_mDelayItemType + "ID=" + Shop_mDelayItemID;
        } else {
            Shop_mFloatingImageElement = null;
        }

        // Request the details from the service
        if (Shop_mDelayItemType != 'Swatch') {
            Shop_RequestPopupDetails(Shop_mDelayItemID, Shop_mDelayItemType, Shop_mDelayRequestType);
        } else {
            Shop_RequestPopupDetails(Shop_mDelaySuffixID, 'Suffix', Shop_mDelayRequestType);
        }
        
        // Store the ID of the requested item
        Shop_mFloatingItemID = Shop_mDelayItemID;
        Shop_mFloatingSuffixID = Shop_mDelaySuffixID;
        Shop_mFloatingItemType = Shop_mDelayItemType;
        Shop_mFloatingRequestType = Shop_mDelayRequestType;
    }
    
    // Reset display properties
    var x = Shop_mDelayX + Shop_mImageSpacing;
    var y = Shop_mDelayY;
    
    Shop_ResetFloatingImage ( Shop_mLoadingImage, x, y );
    Shop_ResetFloatingImage ( Shop_mFloatingImage, x, y );
    
    // Show the loading image
    Shop_mDisplayedFloatingImage = Shop_mLoadingImage;
    
    // Use a timer to switch to the full image when it is loaded
    Shop_mStopAlignImage = 0;
    if ( ! Shop_mAlignFloatingImage ) {
        Shop_mAlignFloatingImage = window.setInterval ( Shop_AlignImage, 100 );
    }
}

function Shop_EnterFloating ( ) {
    // Prevent the popup from being hidden when the mouse enters it
    Shop_mDelayItemID = Shop_mFloatingItemID;
    Shop_mDelaySuffixID = Shop_mFloatingSuffixID;
    Shop_mDelayItemType = Shop_mFloatingItemType;
}

function Shop_RequestPopupDetails ( itemID, itemType, requestType ) {
    // Request the item details from the service
    if ( Shop_mPopupRequestInProgress ) {
        // A request is already in progress, store the ID
        // Only one item can be displayed at once so if another request was already
        // queued it is overwriten with the new request
        Shop_mQueuedPopupRequestID = itemID;
        Shop_mQueuedPopupRequestType = itemType;
    } else {
        // A request is not in progress, request the details from the service
        Shop_mPopupRequestInProgress = 1;

        var stockItemID = (itemType == 'StockItem') ? itemID : 0;
        var suffixID = (itemType == 'Suffix') ? itemID : 0;
        if (requestType == "image" && StockItemService.GetPopupDetails) {
            StockItemService.GetPopupDetails( stockItemID, suffixID, Shop_PopupRequestComplete, Shop_PopupRequestError);
        } else if (requestType == "discount" && StockItemService.GetDiscountDetails) {
            StockItemService.GetDiscountDetails( stockItemID, suffixID, Shop_PopupRequestComplete, Shop_PopupRequestError);
        }
    }
}

function Shop_ProcessQueuedPopupRequest ( ) {
    //Check if a request has been queued and make the request if it has
    var itemID = Shop_mQueuedPopupRequestID;
    
    // Reset the flags
    Shop_mQueuedPopupRequestID = 0;
    Shop_mPopupRequestInProgress = 0;
    if ( itemID ) {
        // Make the request
        Shop_RequestPopupDetails(itemID, Shop_mQueuedPopupRequestType );
    }
}

function Shop_CheckQueuedPopupRequest ( ) {
    // The previous service request has completed. Start a timer to space out the request
    // for the queued item
    window.setTimeout ( Shop_ProcessQueuedPopupRequest, 500 );
}

function Shop_PopupRequestComplete ( result ) {
    // The result has been received from the serivce succesfully, process it
    if (
        ( Shop_mFloatingItemType == 'StockItem' && result.StockItemID == Shop_mFloatingItemID ) 
        || ( ( Shop_mFloatingItemType == 'Suffix' || Shop_mFloatingItemType == 'Swatch' ) && result.SuffixID == Shop_mFloatingSuffixID )
    ) {
        // The result was for the currently displayed item
        
        // Create a DIV to hold the result content
        var popupContent = document.createElement ( "DIV" );
        popupContent.className = "PopupDetails";
        
        popupContent.innerHTML = result.Content;
        
        // Insert the DIV into the popup
        Shop_mFloatingImage.insertBefore ( popupContent, Shop_mFloatingImage.firstChild );    
    }
    
    // Check if there is a queued popup request
    Shop_CheckQueuedPopupRequest ( );
}

function Shop_PopupRequestError ( result ) {
    // The result was received with an error, just check if there is a queued popup request
    Shop_CheckQueuedPopupRequest ( );
}

function Shop_ClearAlignTimer ( ) {
    // Stop the timer ensuring the popup is displayed on the screen and reset the timer
    window.clearInterval ( Shop_mAlignFloatingImage );
    Shop_mAlignFloatingImage = 0;
    Shop_mStopAlignImage = 0;
}

function Shop_GetPageTop ( ) {
    var pageTop = 0;
    if (typeof window.pageYOffset != 'undefined') pageTop = window.pageYOffset;
    if (typeof document.documentElement.scrollTop != 'undefined' && document.documentElement.scrollTop > 0) pageTop = document.documentElement.scrollTop;
    if (typeof document.body.scrollTop != 'undefined' && document.body.scrollTop > 0) pageTop = document.body.scrollTop;
    
    return pageTop;
}

function Shop_AlignImage() {
    if ( Shop_mFloatingImage.offsetHeight > Shop_mLoadedHeight ) {
        // Some results have been received, show them and hide the loading image
        Shop_mLoadingImage.style["display"] = "none";
        Shop_mDisplayedFloatingImage = Shop_mFloatingImage;
        
        if ( 
            ! Shop_mFloatingImageElement 
            || (
                Shop_mFloatingImageElement.offsetHeight > Shop_mLoadedHeight 
                && ! Shop_mPopupRequestInProgress 
            )
        ) {
            // The image and details have loaded, stop the timer
            Shop_ClearAlignTimer ( );
        }
    }
    if ( Shop_mStopAlignImage ) {
        // Image is hiding, make no further checks
        Shop_ClearAlignTimer ( );
    }
    
    // Get the position of the image and the bottom of the scrolling div
    var y = Shop_mDisplayedFloatingImage.offsetTop;
    var x = Shop_mDisplayedFloatingImage.offsetLeft;
    var imgBottom = y + Shop_mDisplayedFloatingImage.offsetHeight;
    var imgRight = x + Shop_mDisplayedFloatingImage.offsetWidth;

    var divRight = Shop_mPageBody.offsetWidth + Shop_mPageBody.offsetLeft;
    
    var pageTop = Shop_GetPageTop ( );
    
    var divBottom = pageTop + document.documentElement.clientHeight;
    if (divBottom < Shop_mDelayY) divBottom = document.documentElement.scrollHeight;
    
    if ( imgBottom > divBottom ) {
        // The image is below the bottom of the div, move it up
        y -= imgBottom - divBottom + 10;
    }
    
    if ( imgRight > divRight ) {
        x -= Shop_mDisplayedFloatingImage.offsetWidth + Shop_mImageSpacing * 2;
    }
    
    // Set the image position
    Shop_mDisplayedFloatingImage.style["top"] = y + "px";
    Shop_mDisplayedFloatingImage.style["left"] = x + "px";
    Shop_mDisplayedFloatingImage.style["visibility"] = "visible";
}

function Shop_DelayHideImage ( ) {
    if ( ! Shop_mDisplayedFloatingImage ) {
        // No image displayed yet, stop
        return;
    }

    Shop_ResetTooltip();
    
    // Begin hiding the image
    Shop_mHideFloatingImageStage = Shop_mHideStages + 1;
    Shop_mHideFloatingImage = window.setTimeout ( Shop_CompleteHideImage, 50 );
    
    // Stop checking if the image has loaded
    if ( Shop_mAlignFloatingImage ) {
        Shop_mStopAlignImage = 1;
    }
}

function Shop_CompleteHideImage ( ) {
    // Hide the image in stages, gradually reducing the opacity
    
    if ( Shop_mDelayItemID ) {
        // There is a shown item, stop trying to hide the item
        Shop_DelayShowHide ( );
        return;
    }
    
    Shop_mHideFloatingImageStage --;
    if ( Shop_mHideFloatingImageStage > 0 ) {
        // Set the opacity
        Shop_mDisplayedFloatingImage.style["opacity"] = Shop_mHideFloatingImageStage / Shop_mHideStages;
        Shop_mDisplayedFloatingImage.style["filter"] = "alpha(opacity=" + (Shop_mHideFloatingImageStage * 100 / Shop_mHideStages ) + ")";
        Shop_mHideFloatingImage = window.setTimeout ( Shop_CompleteHideImage, 50 );
    } else {
        // The image is now invisible, hide it completely
        Shop_mDisplayedFloatingImage.style["display"] = "none";
    }
}

function Shop_OpenSubwindow(url) {
    window.open(url);
    return false;
}

function Shop_SetupDefaultLink(elemId) {
    // Add a click method to the specified element if it does not already have one
    // This allows the link to act as a default button in Firefox and WebKit
    var elem = document.getElementById(elemId);
    if (elem && !elem.click) {
        elem.click = function() { window.location = elem.href; }
    }
}

function Shop_SelectCode ( e ) {
    // Catch check of selection checkbox on code list to allow shift select
    
    // Find the target element
    var srcElement = e.srcElement || e.target;
    
    if ( Shop_mLastSelected && e.shiftKey ) {
        // An check box has already been selected on this page and the shift key has been held down
        
        // Setup
        var mainContent = document.getElementById ( 'PageContent' );
        var elements = mainContent.getElementsByTagName ( 'INPUT' );
        var check = srcElement.checked;
        var inSelection = 0;
        
        // Loop through all input elements
        for ( var index = 0; index < elements.length; index ++ ) {
            var element = elements[index];
            if ( element.type == 'checkbox' ) {
                // This is a checkbox
                
                if ( ! inSelection ) {
                    // We have not found the begining of the selection yet
                    if ( element == srcElement || element == Shop_mLastSelected ) {
                       // This element is the begining of the selection, flag it
                       inSelection = 1;
                       element.checked = check;
                    }
                } else {
                    // We are now in the selection area, set the checkbox
                    element.checked = check;
                    if ( element == srcElement || element == Shop_mLastSelected ) {
                       // This is the end of the selection, stop the loop
                       break;
                    }
                }
            }
        }
    }
    
    // Store the element as the last selected
    Shop_mLastSelected = srcElement;
}

function Shop_TrackDownload(elem) {
    try {
        pageTracker._trackEvent(document.title, 'Download', document.title + ' - ' + elem.getAttribute('DownloadName'));
    } catch (e) {
    }
}

function Shop_TrackTrans() {
    try {
        var transDetails = document.getElementById("TransDetails").getElementsByTagName("SPAN")[0];
        var transItems = document.getElementById("TransItems").getElementsByTagName("SPAN");

        var basketID = transDetails.getAttribute("CCLBasketID");
        pageTracker._addTrans(
            basketID, "",
            transDetails.getAttribute("CCLTotal"),
            transDetails.getAttribute("CCLTax"),
            transDetails.getAttribute("CCLDelivery"),
            transDetails.getAttribute("CCLTown"),
            transDetails.getAttribute("CCLCounty"),
            transDetails.getAttribute("CCLCountry")
        );

        for (var i = 0; i < transItems.length; i++) {
            var transItem = transItems[i];
            pageTracker._addItem(
                basketID,
                transItem.getAttribute("CCLCode"),
                transItem.getAttribute("CCLSection"),
                transItem.getAttribute("CCLDescription"),
                transItem.getAttribute("CCLPrice"),
                transItem.getAttribute("CCLQuantity")
            );
        }

        pageTracker._trackTrans();
    } catch (e) {
    }
}

// Validate the card number checksum
function CardNumberValidator_ClientValidate ( sender, e ) {
    var cardNumber = e.Value;
    var digit = 0;
    var sum = 0;
    var even = false;

    // Assume number is not valid
    e.IsValid = false;

    // Get rid of spaces before performing the checksum
    cardNumber = cardNumber.replace ( / /g, "" );
    if ( cardNumber.length < 13 ) return;
    

    // Checksum the number
    for ( var index = cardNumber.length - 1; index >= 0; index-- ) {
        try {
            digit = parseInt ( cardNumber.charAt(index) );
        } catch ( exception ) {
            // This digit did not parse as an int, stop
            return;
        }

        if ( even ) {
            // Multiply even digits by 2
            digit *= 2;
            if ( digit > 9 ) {
                // Result is over 9, reduce to a single digit
                digit -= 9;
            }
        }
        // Add this digit to the total
        sum += digit;
        even = !even;
    }

    // Checksum completed, see if the number is a multiple of 10
    e.IsValid = ( sum > 0 && sum % 10 == 0 );
}

