﻿
///
/// global variables
///

var postcodeFiredArray = new Array();
var isClicked = false; // for double click disable function


///
/// Init function
///

function GlobalInit() {

    AutoPostcodeInputFiringInit();
    TextBoxPlaceholderTextReplacementInit('#newsletter INPUT.txtBox', "Enter your email address");
    TextBoxPlaceholderTextReplacementInit('#comingSoon INPUT.txtBox', "Enter your email address");
    TextBoxPlaceholderTextReplacementInit('#search INPUT.txtBox', "Enter keywords");

    // stylize the dropdown menu            
    $('ul.menuLinks').superfish(); // superfish superfish, she's superfishy....yow!

    // add classes to dynamic drop down A links
    $('UL.menuLinks > LI > A.AspNet-Menu-Link[title="Fitness & Sport"]:first').addClass('fitnessSport');
    $('UL.menuLinks > LI > A.AspNet-Menu-Link[title="Health & Beauty"]:first').addClass('healthBeauty');
    $('UL.menuLinks > LI > A.AspNet-Menu-Link[title="At Home"]:first').addClass('atHome');
    $('UL.menuLinks > LI > A.AspNet-Menu-Link[title="Kitchen"]:first').addClass('kitchen');
    $('UL.menuLinks > LI > A.AspNet-Menu-Link[title="DVDs & Media"]:first').addClass('dvdsMedia');
    $('UL.menuLinks > LI > A.AspNet-Menu-Link[title="Accessories & Replacement Parts"]:first').addClass('accRepParts');

    // add classes to LI elements
    $('UL.menuLinks > LI > A.AspNet-Menu-Link[title="Fitness & Sport"]:first').parent().addClass('fitnessSport');
    $('UL.menuLinks > LI > A.AspNet-Menu-Link[title="Health & Beauty"]:first').parent().addClass('healthBeauty');
    $('UL.menuLinks > LI > A.AspNet-Menu-Link[title="At Home"]:first').parent().addClass('atHome');
    $('UL.menuLinks > LI > A.AspNet-Menu-Link[title="Kitchen"]:first').parent().addClass('kitchen');
    $('UL.menuLinks > LI > A.AspNet-Menu-Link[title="DVDs & Media"]:first').parent().addClass('dvdsMedia');
    $('UL.menuLinks > LI > A.AspNet-Menu-Link[title="Accessories & Replacement Parts"]:first').parent().addClass('accRepParts');

    // "add to cart" handling
    $('LI.addToCart A').click(function(e) {
        e.preventDefault();
    });

    /*
    // close modal
    $('#cartAddTo UL.action LI.noThx A').click(function(e) {
        $.modal.close();
    });
    */
}


function HeadingImageReplacement() {

    $('H1.main').each(function(i) {
        var text = $(this).text();
        switch (text.toLowerCase()) {
            case "fitness & sport":
                $(this).addClass('fitnessAndSport');
                break;
            case "home fitness equipment":
                $(this).addClass('homeFitnessEquipment');
                break;
            case "golf equipment":
                $(this).addClass('golfEquipment');
                break;
            case "fitness accessories":
                $(this).addClass('fitnessAccessories');
                break;
            case "health & beauty":
                $(this).addClass('healthAndBeauty');
                break;
            case "pedicure":
                $(this).addClass('pedicure');
                break;
            case "skincare":
                $(this).addClass('skincare');
                break;
            case "beauty innovations":
                $(this).addClass('beautyInnovations');
                break;
            case "beauty accessories":
                $(this).addClass('beautyAccessories');
                break;
            case "at home":
                $(this).addClass('atHome');
                break;
            case "grow herbs & veggies":
                $(this).addClass('growHerbsAndVeggies');
                break;
            case "storage":
                $(this).addClass('storage');
                break;
            case "home comfort":
                $(this).addClass('homeComfort');
                break;
            case "lighting & electrical":
                $(this).addClass('lightingAndElectrical');
                break;
            case "outdoor & diy":
                $(this).addClass('outdoorsAndDiy');
                break;
            case "pest control":
                $(this).addClass('pestControl');
                break;
            case "cleaning":
                $(this).addClass('cleaning');
                break;
            case "for pets":
                $(this).addClass('forPets');
                break;
            case "for kids":
                $(this).addClass('forKids');
                break;
            case "kitchen":
                $(this).addClass('kitchen');
                break;
            case "kitchen innovations":
                $(this).addClass('kitchenInnovations');
                break;
            case "cookware":
                $(this).addClass('cookware');
                break;
            case "crockery":
                $(this).addClass('crockery');
                break;
            case "knives/cutlery":
                $(this).addClass('knivesCutlery');
                break;
            case "kitchen accessories":
                $(this).addClass('kitchenAccessories');
                break;                
            case "outdoors & diy":
                $(this).addClass('outdoorsAndDiy');
                break;            
            case "accessories & replacement parts":
                $(this).addClass('accParts');
                break;
            case "aerogarden":
                $(this).addClass('aeroGarden');
                break;
            case "go duster":
                $(this).addClass('goDuster');
                break;
            case "gale force max":
                $(this).addClass('galeForceVaccum');
                break;
            case "pedegg":
                $(this).addClass('pedEgg');
                break;
            case "pedi paws":
                $(this).addClass('pediPaws');
                break;                
            case "special offers":
                $(this).addClass('specialOffers');
                break;
            case "customers top 10":
                $(this).addClass('customersTopTen');
                break;
            case "as seen on tv":
                $(this).addClass('asSeenOnTv');
                break;
            case "clearance":
                $(this).addClass('clearance');
                break;
            case "products a to z":
                $(this).addClass('productAtoZ');
                break;
            case "coming soon":
                $(this).addClass('comingSoon');
                break;
            case "new":
                $(this).addClass('new');
                break;
            case "what's hot":
                $(this).addClass('whatsHot');
                break;
            case "dvds & media":
                $(this).addClass('dvdsMedia');
                break;
        }
    });

}

function ShowAddToCart(marketingItemId) {
    ShowAddToCartEditPopup('/AddToCart.aspx?id=' + marketingItemId);
}

function ShowAddToCartWithCrossSell(marketingItemId, crossSellOfMarketingItemId, crossSellTypeId) {
    ShowAddToCartEditPopup('/AddToCart.aspx?id=' + marketingItemId + '&csmi=' + crossSellOfMarketingItemId + '&csti=' + crossSellTypeId);
}

function ShowEditCart(cartItemId) {
    ShowAddToCartEditPopup('/EditCart.aspx?cid=' + cartItemId);
}

function ShowAddToCartEditPopup(url) {

    // Call service
    $.ajax({
        type: "GET",
        url: url,
        data: "",
        dataType: "html",
        success: function(msg) {
            $('DIV.modalContainer').html(msg);
        }
    });

    topPos = "20%";
    width = "589px";
    height = "500px";
    var border = '3px solid #ABA9AA';

    // do the modal stuff
    $.extend($.modal.defaults, {
        position: [topPos, ],
        containerCss: { width: width, height: height }
    });
    $.extend($.modal.defaults, {
        containerCss: { width: width, height: height, border: border }
    });

    $('DIV.modalContainer').modal(
    {
        // modal option: on Open
        onOpen: function(dialog) {
            dialog.overlay.fadeIn('slow', function() {
                dialog.container.fadeIn('slow', function() {
                    dialog.data.fadeIn('slow');
                });
            });
        },
        // modal option: on Close
        onClose: function(dialog) {
            dialog.data.fadeOut('slow', function() {
                dialog.container.fadeOut('slow', function() {
                    dialog.overlay.fadeOut('slow', function() {
                        $.modal.close(); // must call this!
                    });
                });
            });
        }
    });

    // use the wider button
    $('#simplemodal-container a.modalCloseImg').addClass('modalCloseImg2');
}


function AddToCart(marketingItemId, offerGroupCode, paymentOptionId, selectedProds, crossSellOfMarketingItemId, crossSellTypeId) {
    $.ajax({
        type: "POST",
        url: "/Services/Cart.asmx/AddToCart",
        data: "{marketingItemId: " + marketingItemId + ", offerCode: '" + offerGroupCode + "', paymentOptionId: " + paymentOptionId + ", productData: '" + selectedProds + "', crossSellOfMarketingItemId: " + crossSellOfMarketingItemId + ", crossSellTypeId: " + crossSellTypeId + " }",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            ShowConfirmation(msg.d, marketingItemId, false);
        }
    });
    ResetQtySelects();
}

function UpdateCart(marketingItemId, offerGroupCode, paymentOptionId, selectedProds, shoppingCartItemIds, crossSellOfMarketingItemId, crossSellTypeId) {
    $.ajax({
        type: "POST",
        url: "/Services/Cart.asmx/UpdateCart",
        data: "{marketingItemId: " + marketingItemId + ", offerCode: '" + offerGroupCode + "', paymentOptionId: " + paymentOptionId + ", productData: '" + selectedProds + "', shoppingCartItemIds: '" + shoppingCartItemIds + "', crossSellOfMarketingItemId: " + crossSellOfMarketingItemId + ", crossSellTypeId: " + crossSellTypeId + " }",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            ShowConfirmation(msg.d, marketingItemId, true);
        }
    });
    ResetQtySelects();
}


function ShowConfirmation(errorMsg, marketingItemId, isUpdateConfirmMsg) {

    // config
    topPos = "17%";
    width = "589px";
    height = "500px";
    var border = '3px solid #ABA9AA';

    // prepare output
    var strOutput = '';
    var hasError = (errorMsg != null && errorMsg != '');
    if (hasError) { // there's an error
        topPos = "25%";
        height = "200px";
        strOutput += '<div id="productAdded">';
        strOutput += '<h2>Please try again</h2>';
        strOutput += '<p>Sorry - there appears to be a technical glitch. Please try again.</p>';
        strOutput += '<ul class="action"><li class="back"><a href="#" class="simplemodal-close">Back</a></li></ul>';
        strOutput += '</div>';
        ShowConfirmationOutput(strOutput, topPos, width, height, border, hasError);
    }
    else {
        var confirmMsg = isUpdateConfirmMsg ? 'Your cart has been updated.' : 'Your item has been added to your cart.';
        var returnLinks = '<li class="back"><a href="#" class="simplemodal-close">Back to Shopping</a></li><li class="proceed"><a href="/Shopping-Cart.aspx">Proceed to Checkout</a></li>';
        if (isUpdateConfirmMsg)
            returnLinks = '<li class="proceed"><a href="#" class="simplemodal-close">Continue</a></li>'

        // cross sell info?
        $.ajax({
            type: "GET",
            url: "/AddToCartConfirmationPageCrossSell.aspx?id=" + marketingItemId,
            data: "",
            dataType: "html",
            success: function(msg) {

                strOutput += '<div id="productAdded">';
                strOutput += '<h2>' + confirmMsg + '</h2>';
                strOutput += '<ul class="action">' + returnLinks + '</ul>';
                strOutput += '</div>';
                strOutput += msg;

                ShowConfirmationOutput(strOutput, topPos, width, height, border, hasError);

            }
        });
        
    }
}


function ShowConfirmationOutput(strOutput, topPos, width, height, border, hasError) {

    // insert
    $('DIV.modalContainer').html(strOutput);

    // do the modal stuff
    $.extend($.modal.defaults, {
        position: [topPos, ],
        containerCss: { width: width, height: height }
    });
    $.extend($.modal.defaults, {
        containerCss: { width: width, height: height, border: border }
    });

    $('DIV.modalContainer').modal(
    {
        // modal option: on Open
        onOpen: function(dialog) {
            dialog.overlay.fadeIn('slow', function() {
                dialog.container.fadeIn('slow', function() {
                    dialog.data.fadeIn('slow');
                });
            });
        },
        // modal option: on Close
        onClose: function(dialog) {
            dialog.data.fadeOut('slow', function() {
                dialog.container.fadeOut('slow', function() {
                    dialog.overlay.fadeOut('slow', function() {
                        $.modal.close(); // must call this!
                    });
                });
            });
        }
    });

    // use the wider button
    $('#simplemodal-container a.modalCloseImg').addClass('modalCloseImg2');

    if (!hasError) {
        $('#simplemodal-container A.simplemodal-close').click(function(e) {
            window.location.href = window.location.href.replace(/#.*/, '');
        });
    }

}


function TextBoxPlaceholderTextReplacementInit(selector, text) {
    $(selector).val(text);
    $(selector).focus(function(e) {
        if ($(this).val() == text)
            $(this).val('');
    });
    $(selector).blur(function(e) {
        if ($(this).val() == '')
            $(this).val(text);
    });
}

function ShowPhotoEnlarged(e) {
    e.preventDefault();
    var uri = (e.target.getAttribute("href")) ? e.target.getAttribute("href") : e.target.parentNode.getAttribute("href");
    var myWin = window.open("/ImageEnlarged.aspx?i=" + uri, 'enlarged', 'width=532,height=412,location=no,status=no,resizable=no,menubar=no,titlebar=no');
    myWin.focus();
}

function OpenReceiptWindow(orderGuid, isOrderProcessed) {
    var myWin = window.open("OrderReceipt.aspx?g=" + orderGuid + "&p=" + (isOrderProcessed ? 1 : 0) + "", "receipt", 'width=800,height=412,location=yes,status=no,resizable=yes,menubar=yes,titlebar=no,scrollbars=yes');
    myWin.focus();
}

function ShowPopup(e, url, width, maxHeight) {

    if (e != null)
        e.preventDefault();
    
    var heightFraction = 0.85;
    var height = (heightFraction * 100) + '%';
    var windowHeight = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
    var iframeHeight = (windowHeight * (heightFraction - 0.1)).toFixed(0);
    var containerHeight = (heightFraction * windowHeight).toFixed(0);

    if (maxHeight != null && containerHeight > maxHeight) {
        height = maxHeight + "px";
        iframeHeight = maxHeight - 60;
    }

    var border = '3px solid #ABA9AA';
    var iframeCode = '<iframe src="' + url + '" height="' + iframeHeight + '" width="' + (width - 10) + '" frameborder="0"></iframe>';

    width = width + "px";
    $('DIV.modalContainer').html(iframeCode);
    $.extend($.modal.defaults, {
        position: ["15%", ],
        containerCss: { width: width, height: height }
    });
   
    $.extend($.modal.defaults, {
        containerCss: { width: width, height: height, border: border }
    });
    
}


/**
 ** Postcode textbox input autofiring 
 */
function AutoPostcodeInputFiringInit() {
    $('INPUT.postcodeInput').each(function(i) {
        postcodeFiredArray[i] = false;
        $(this).keyup(function(e) {
            postcodeFiredArray[i] = false;
            if (e.target.value.length == 4) {
                $('#' + e.target.id + " ~ INPUT:image").trigger('click');
                postcodeFiredArray[i] = true;
            }
        });
        $(this).blur(function(e) {
            if (e.target.value.length == 4 && postcodeFiredArray[i] == false) {
                $('#' + e.target.id + " ~ INPUT:image").trigger('click');
                postcodeFiredArray[i] = true;
            }
        });
    });
}


///
/// Other functions
///

function ConfirmDelete() {
    return confirm("Do you really want to delete this?");
}

function FixLeftFloatingProblem() {
    var currentPos = 0;
    var itemIndex = 0;
    var breakPoint = 0;
    $('DIV.productItem').each(function(e) {
        var pos = $(this).position();
        if (currentPos == pos.left) { // same!
            breakPoint = itemIndex;
            return false;
        }
        currentPos = pos.left;
        itemIndex++;
    });
    if (breakPoint > 1) {
        var firstProd = $('DIV.productItem:eq(' + (breakPoint - 1) + ')');
        var secondProd = $('DIV.productItem:eq(' + (breakPoint - 2) + ')');
        firstProd.height(secondProd.height() + 5);
        FixLeftFloatingProblem(); // some recursive goodness :)
    }
}

///
/// Disallow multiple button clicks on the page
///
function DisableButtonMultiClick(buttonId) {
    $('#' + buttonId).dblclick(function(e) {
        e.preventDefault();
    });
    $('#' + buttonId).click(function(e) {
        if (isClicked)
            e.preventDefault();
        else
            isClicked = true;
    });
}
