﻿/*
    Date Created:   March 2010
    Author:         Nick Coleman
    Content:        Functions which operate the kitbag store
    Pre-Requisites: jquery-1.4.1.js or greater
                    kb_library.js
                    disable_ui.js + jquery.blockUI.js ( these two files enable the interface to be blocked)
    Notes:          This file should be minified before deployment using ajax minifier in deployment project,
                    http://javascriptcompressor.com/ or http://javascript.crockford.com/jsmin.html.
                    It is best to run through jslint prior to minifying
*/

var KB = new KitbagObjects("kitbag");

var header = {

    curMenu: {},

    init: function() {

        var nav = $("#headerNav");
        var sitelinks = $("li", "#navSite");
        var deplinks = $("a", "#navTopDeps");
        var navmenus = $(".navMenu", "#navDepartment");
        
        var url = document.location.href; //Force Christmas background image when on Christmas pages - this is temporary
        if (url.indexOf("23848=christmas") > -1) {
            $('#sitebg').css('background-image', 'url("/stores/kitbag/artwork/common/interface/xmas_background.jpg")');
            $('#sitebg').css('background-attachment', 'fixed');                        
        }
        
        if (document.location.protocol == "https:") {
            deplinks.each(function() {
                var href = $(this).attr("href");
                $(this).attr("href", "http://" + document.location.hostname + href.substr(href.indexOf("/stores/")));
            });
            sitelinks.find("a").each(function() {
                var href = $(this).attr("href");
                $(this).attr("href", "http://" + document.location.hostname + href.substr(href.indexOf("/stores/")));
            });
        }

        sitelinks.live("mouseenter", function() {
            $(this).addClass("navSiteOver");
        }).live("mouseleave", function() {
            $(this).removeClass("navSiteOver");
        });

        deplinks.live("mouseenter", function() {
            $(this).addClass("siteNavActive");
            if ($.browser.msie && $.browser.version == "6.0") {

            } else {
                header.curMenu = navmenus.eq(deplinks.index($(this)));
                if (header.curMenu.html() != null) {
                    var locleft = $(this).position().left;
                    var overflow = (990 + $("#navDepartment").position().left) - (header.curMenu.width() + locleft);
                    if (overflow < 0) { locleft = locleft + overflow; }
                    header.curMenu.css("left", locleft).fadeIn(200);
                }
            }
        }).live("mouseleave", function(event) {
            if ($.browser.msie && $.browser.version == "6.0") {
                $(this).removeClass("siteNavActive");
            } else {
                if (!$(event.relatedTarget).hasClass("navMenu") && $(event.relatedTarget).parents(".navMenu").length == 0) {
                    if (typeof (header.curMenu) !== "undefined") { header.curMenu.hide(0); }
                    $(this).prev().css("visibility", "hidden");
                    $(this).removeClass("siteNavActive").css("opacity", 1);
                }
            }
        });

        navmenus.live("mouseleave", function(event) {
            deplinks.removeClass("siteNavActive").css("opacity", 1);
            $(this).hide(0);
        });

        $("#txt_search").focus(function() {
            if (this.defaultValue == this.value) { this.value = ""; }
        }).blur(function() {
            if (this.value == "") { this.value = this.defaultValue; }
        });

        $("#img_search").click(function(e) {
            if ($("#txt_search").attr("value") != "") { window.location.href = '/stores/kitbag/products/product_browse.aspx?free_text=' + encodeURIComponent($("#txt_search").attr("value")); }
        });
        $("#txt_search").keypress(function(event) {
            if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {
                event.preventDefault();
                window.location.href = '/stores/kitbag/products/product_browse.aspx?free_text=' + encodeURIComponent($(this).attr("value"));
                return false;
            } else {
                return true;
            }
        });
    },

    setBG: function() {
        $("#promoimage, #sitebg").height($("#pageContainer").height());
    }
};

var home = {
    imgID: {},
    timer: {},
    links: {},

    showImages: function(pane) {
        if (pane.data("images") != "true") {
            pane.find("img").each(function() {
                var curImg = $(this);
                $(new Image()).load(function() {
                    curImg.css("visibility", "visible").attr("src", $(this).attr("src"));
                }).attr("src", "http://images.kitbag.com/" + $(this).attr("rel") + "?width=" + $(this).width() + "&height=" + $(this).height() + "&quality=90");
            });
            pane.data("images", "true");
        }
    },

    init: function() {

        // Initiate tabs effect for merch zone
        $("#hpMz").kb_tabs({ 'tabEffect': 'scroll' });

        // Load images in first merch zone
        home.showImages($(".tabpane", "#hpMz").eq(0));

        // When a tabheader is clicked load the product images for that zone
        $(".tabheader a", "#hpMz").mousedown(function() {
            var ind = $(".tabheader a").index($(this));
            home.showImages($(".tabpane", "#hpMz").eq(ind));
        });

        // Initiate sign up plugin for newsletter area
        $("#hpSignUp").kb_signup({ 'welcomeurl': '/stores/kitbag/welcome.aspx' });

        // Equalise heights of sidebanners and 'follow us' area to maintain layout
        $("#hpSideBnrs .lpBnr span").kb_equaliseHeights({ 'minHeight': 30 });
        $("#hpSideBnrs .lpBnr, .hpFollowUs").kb_equaliseHeights({ 'minHeight': 200 });

        // Set up rollover images for brand area
        $("#brandmap area").mouseenter(function() {
            $("#brandHeader img").attr("src", "artwork/common/home/" + $(this).attr("id") + "_lrg.gif");
            $("#brandHeader span").html($(this).attr("alt"));
        });

        $("a", "#hpSideBnrs").click(function() { sc_trackLink('HPSideBnr' + $("a", "#hpSideBnrs").index(this), 'eVar6'); });
        $("a", "#hpBtmBnrs").click(function() { sc_trackLink('HPBottomBnr' + $("a", "#hpBtmBnrs").index(this), 'eVar6'); });
    },

    initCarousel: function() {
        home.imgID = 0;
        $("#promoimage").data("animating", false).queue(function() {
            $(this).css("background", "url(" + tlma[0].image + ") top center no-repeat"); $(this).dequeue();
        }).show().queue(function() { $(this).height($("#pageContainer").height()); $(this).dequeue() });

        $("#navbarnext").click(function() {
            clearTimeout(home.timer);
            home.tlmFireRotate();
        });

        if (tlma[0].desc == '') {
            $("#promodescbg, #promodesc").hide(0);
        } else {
            $("#promodescbg").css("opacity", 0.5).show();
            $("#promodesc").show(0).children("span").html(tlma[0].title);
            $("#hpTopBnr").attr("href", tlma[0].link).attr("title", tlma[0].desc);
            $("#promodesc").find("a").attr("href", tlma[0].link).html(tlma[0].desc);
        }
        home.links = $("a", "#navbarlinks");
        home.links.filter(":not(:first)").fadeTo(200, 0.6);
        home.links.live("mouseenter", function() { if (home.links.index($(this)) != home.imgID) { $(this).addClass("promoimageselected").fadeTo(50, 1) } });
        home.links.live("mouseleave", function() { if (home.links.index($(this)) != home.imgID) { $(this).removeClass("promoimageselected").fadeTo(50, 0.6) } });
        home.links.show();
        $("a.promoimage", "#hpTopBnrs").click(function() { sc_trackLink('HPTopBnr' + $("a.promoimage", "#hpTopBnrs").index(this), 'eVar6'); });
    },

    tlmRotate: function() {
        home.timer = setTimeout(function() { home.tlmFireRotate(); }, 8000);
    },

    tlmFireRotate: function() {
        if ($("#promoimage").data("animating") == false) {
            home.imgID += 1;
            if (home.imgID == tlma.length) { home.imgID = 0 }
            var nextImage = tlma[home.imgID].image;
            $(new Image()).load(function() {
                home.changeImg();
            }).attr('src', nextImage);
        }
    },

    changeImg: function() {
        $("#promoimage").data("animating", true).height($("#pageContainer").height());
        var nextPromo = tlma[home.imgID];
        $("#promoimage").fadeOut(800, function() {
            home.links.eq(home.imgID - 1).removeClass("promoimageselected").fadeTo(200, 0.6);
            home.links.eq(home.imgID).addClass("promoimageselected").fadeTo(200, 1);
            $(this).css("background", "url(" + nextPromo.image + ") top center no-repeat").fadeIn(800, function() {
                $(this).data("animating", false);
            });
            $("#hpTopBnr").attr("href", nextPromo.link).attr("title", nextPromo.desc);
            if (nextPromo.desc == '') {
                $("#promodescbg, #promodesc").hide(0);
            } else {
                $("#promodescbg, #promodesc").show(0);
                $("#promodesc").children("span").html(nextPromo.title);
                $("#promodesc").find("a").attr("href", nextPromo.link).html(nextPromo.desc);
            }
        })

        home.tlmRotate();
    }
};

// Handles all operations on the browse/landing pages
var browse = {
    init: function() {

        // Initiate tabs effect for merch zone
        $(".browseMz", "#productBrowseContent").kb_tabs({ 'tabEffect': 'scroll', 'tabClass': '.browseMz' });

        // Initiate sign up plugin for newsletter area
        $("#navSU").kb_signup({ 'welcomeurl': '/stores/kitbag/welcome.aspx' });

        // Equalise heights of banners' span areas to maintain layout
        $(".lpBnr span:not(.closespeech)").kb_equaliseHeights({ 'minHeight': 15 });

        // Equalise heights of description areas to maintain layout
        $(".productListLink", ".browseResults").kb_equaliseHeights({ 'minHeight': 55 });

        // Blocks navigation and results while paging
        $(".paging a").click (function() { showProgress() });

        // Handles clicks on the refinements
        var refs = $(".refinementPanel .refinement", "#productBrowseContainer");
        refs.children("a").click(function(evt) {
            evt.preventDefault();
            $(this).parent().next().slideToggle(250);
        });

        // Handles colour swatches
        $(".colourway a").mouseover(function() {
            // Identify the current Item
            var listItem = $(this).parents(".productListItem")
            // Identify the image that needs to be changed
            var listImg = listItem.find(".productListImage img");
            // Identify the description that needs changing
            var listDesc = listItem.children(".productListLink").find("a");
            // Identify the price that needs changing
            var listPrice = listItem.children(".productListPrice").find("span:last");

            var origdata = new Object;
            origdata.img = listImg.attr("src");
            origdata.desc = listDesc.html();
            origdata.price = listPrice.html();
            if (!listItem.data("orig")) {
                listItem.data("orig", origdata);
            }

            var prodDetail = window['colour' + $(this).attr("rel")];
            listImg.attr("src", prodDetail.ImageURL);
            listDesc.html(prodDetail.Description);
            listPrice.html(prodDetail.PriceString);
        });

        $(".productListColours").mouseleave(function(event) {
            var listItem = $(this).parents(".productListItem");
            var listImg = listItem.find(".productListImage img");
            var orig = listItem.data("orig");
            if (orig && orig.img != listImg.attr("src")) {
                listImg.fadeTo(200, 0.5, function() {
                    $(this).attr("src", orig.img).fadeTo(600, 1);
                    listItem.find(".productListLink a").html(orig.desc);
                    listItem.find(".productListPrice span:last").html(orig.price);
                });
            }
        });

    }
};

function showProgress() {
    $('#productBrowseNav').block({ message: '<img src="/stores/kitbag/artwork/common/interface/loader_v1.gif" />', overlayCSS: { backgroundColor: '#fff', opacity: 0.6} });
    $('.productListImage').block({ message: '<img src="/stores/kitbag/artwork/common/interface/loader_v1.gif" />', overlayCSS: { backgroundColor: '#fff', opacity: 0.6} });
}

var productplus = {

    img: {},

    init: function() {
        $(".ppimg").click(function(evt) {
            evt.preventDefault;
            var ppArea = $(this).parents(".ppItem");
            ppArea.addClass("ppSelected").siblings(".ppItem").removeClass("ppSelected");
            productplus.img = ppArea.find(".ppImg").attr("src");
            KB.Services.Product().SetProductPlus($(this).attr("rel"), ppArea.find(".ppVariation").val(), productplus.onPPComplete, productplus.onError);
        });
        $("#ppSelectedInfo").live("click", function() {
            KB.Services.Product().RemoveProductPlus(productplus.onPPRemoveComplete, productplus.onError);
        })
    },

    onPPComplete: function(result) {
        result = result.replace("[IMG]", "<img src='" + productplus.img + "' alt='' />");
        $("#ppSelectedInfo").slideUp(400).queue(function() { $(this).html(result + "<br/><a><img src='/stores/kitbag/artwork/english/interface/buttons/button_cancel.gif' /></a>").dequeue(); }).slideDown(400);
    },

    onPPRemoveComplete: function(result) {
        $("#ppSelectedInfo").slideUp(400).queue(function() { $(".ppItem").removeClass("ppSelected"); $(this).html("<p>You have not yet made a selection</p>").dequeue(); }).slideDown(200);
    },

    onError: function(result) {
        $("#ppSelectedInfo").html("Unfortunately a problem occured, please try again or come back later when the problem will hopefully be resolved");
    }
};


function s7jsonResponse(obj, reqId) {

    var i = ""; //Iterator for the main for loop 
    var x = 0; // conditional variable for the while loop is always set as the index of the next semi colon (indicating another image in the image set) in the json response currently evaluated 
    var y = 0; // variable set to the index of the next comma in the json response evaluated
    var count = 0;
    
    for (i in obj) {
        //Step through the imageset JSON array in a for loop 
        x = obj[i].indexOf(";", 0); // Look for the first occurence of ; which denotes a swatch image 
        y = obj[i].indexOf(",", 0); // Look for the first occurence of , which denotes an alternate image 
        if (y == -1) { // If there are no specified swatch images 
            y = obj[i].length; // Set the y index to the end of the array 
        }

        //Start a while loop to go through each JSON response loop is active as long as there's a , in the json response
        while (x > 0) {
            count++;
            var imgname = obj[i].substring(x + 1, y).replace("Findel/", "");
            imgname = imgname.substring(imgname.indexOf("-") + 1)
            var kbimgname = productdetail.ImageURL.substring(productdetail.ImageURL.lastIndexOf("/") + 1, productdetail.ImageURL.lastIndexOf("-") + 1) + imgname;
            $("<img/>").data("imgname", kbimgname).attr("src", "http://findel.scene7.com/is/image/Findel/" + kbimgname + "?layer=comp&wid=90&hei=90&fmt=jpeg&qlt=90,0&op_sharpen=0&resMode=sharp&op_usm=1.0,1.0,8,0&iccEmbed=0").appendTo("#pdMultiImages");
            //$("<img/>").data("imgname", kbimgname).attr("src", "http://images.kitbag.com/" + kbimgname + ".jpg?width=90&height=90&quality=95").appendTo("#pdMultiImages");
            if (count == 4) { break }
            x = obj[i].indexOf(";", y); //x is incremented to the next occurence of a comma that comes after the occurence of a semi-colon. If there is no other comma then kick out of the while loop and return
            y = obj[i].indexOf(",", y + 1);
            if (y == -1) { y = obj[i].length; }
        }
    }

    if (count < 2) {
        $("#pdMultiImages").hide(0);
    }
}
var sizechart_viewer = {

    load: function(element) {
        if (!KB.Cache.Get("chart")) {
            $.get("/stores/kitbag/help/size_chart.htm", function(data) {
                KB.Cache.Set("chart", data);
                $(element).html(data);
                $("#sizecharttabs").kb_tabs();
            });
        }
    }
};

/*************************************************************************************************************
//Name: ProductDetailsOptions
//Description: 
//This object is used to initialise a 'proddetails' object. All the common proddetails logic has been moved to
//common/scripts/productdetails.js.
**************************************************************************************************************/

var productDetailOptions = {

    pdAreaSelector: "#pdInfo",
    pdSignUpOptions: { 'welcomeurl': '/stores/kitbag/welcome.aspx' },
    
    /*********************************************************************************************************
    //Name: OnInit
    //Description: Called by proddetails.Init() to perform any site specific initialisation. 
    **********************************************************************************************************/
    OnInit: function() { }
};

var basket = {

    init: function() {
        $("#basketRight").kb_accordian({ 'grow': true });
        $(".productListATB").click(function(evt) {
            // stop the postback
            evt.preventDefault();
            // disable the user interface
            EnableUI.Toggle(false);

            // set the active product
            var activeProduct = $(this).parents(".productListItem");

            // get the pid from the rel attribute which is set in the code behind
            var pid = $(this).attr("rel");
            var vid = 0;
            // if there is a size dropdown for this product set vid to the selected value
            if (activeProduct.find(".productListSizes").get(0)) {
                vid = parseInt(activeProduct.find(".productListSizes").val(), 10);
            }
            // Add the product to the basket
            KB.Services.Product().AddToBasket(pid, vid, 0, '', '', 0, basket.onATBComplete, basket.onError);
        });
        $(".shiplink").live("mousedown", function() {
            $(this).queue(function() { $('#deliveryinfo div.content').kb_content({ 'branch': 892, 'leaf': 'shipping_info_44' }); $(this).dequeue; });
        });
        $("#returnslink").live("mousedown", function() {
            $(this).queue(function() { $('#returnsinfo div.content').kb_content({ 'branch': 437, 'leaf': 'Paragraph_kitbag' }); $(this).dequeue; });
        });
        $(".removeItem").live("click", function(evt) {
            evt.preventDefault();
            basket.feedback($(this), "Please wait while this item is removed from your basket");
            __doPostBack($(this).attr("name"), '');
        });
        $(".decreaseItem, .increaseItem").live("click", function() {
            basket.feedback($(this), "Please wait while this item is updated");
            __doPostBack($(this).attr("name"), '');
        });
        basket.giftWrap.init();
    },

    refreshContents: function() {
        __doPostBack($("div[id*=up_basket]").attr('id'), 'BasketRefresh');
    },

    feedback: function(element, text) {
        var row = element.parents("tr");
        row.find("td:gt(0)").remove();
        row.find("td:first").css("background-color", "#F2F2F2");
        row.append("<td colspan='6' align='center' style='background-color:#F2F2F2'><img src='/stores/kitbag/artwork/common/interface/loader_bar_v1.gif' alt='loading' /><p>" + text + "</p></td>");
    },

    onATBComplete: function(result) {
        if (result) {
            var bskItem = $("." + result.ProductID + result.VariationID);
            var content = "<td align='center' valign='middle' style='background-color:#F2F2F2;height:105px;width:120px;'><img src='http://images.kitbag.com/" + result.ImageName + "?width=100&amp;height=100' alt='" + result.Description + "' style='height:100px;width:100px;border-width:0px;' /></td><td colspan='6' align='center' style='background-color:#F2F2F2'><img src='/stores/kitbag/artwork/common/interface/loader_bar_v1.gif' alt='loading' /><p>Please wait while <em>'" + result.Description + "'</em> is added to your basket</p></td>"
            if (bskItem.length > 0) {
                bskItem.html(content);
            } else {
                bskItem = $("<tr style='display:none' />").html(content).fadeIn(600).appendTo($(".basketContents"));
            }
            var curY = bskItem.offset().top + bskItem.height();

            // If the item being added is not on the page scroll the page, once the product is added to the basket update the basket by refeshing the updatepanel
            if (parseInt(curY, 10) > $(window).height() + $(window).scrollTop()) {
                $('html,body').animate({ scrollTop: (curY - $(window).height()) + 10 }, 500, function() { basket.refreshContents(); });
            } else {
                basket.refreshContents();
            }
        } else {
            alert("There was a problem adding the current selection to the basket");
            EnableUI.Toggle(true);
        }
    },

    onError: function(result) {
        alert("Unfortunately an error has occured, please try again");
        EnableUI.Toggle(true);
    },

    giftWrap: {

        init: function() {

            // enable the checkboxes and everytime a partial postback is done. can't use pageLoad otherwise enabled too soon
            basket.giftWrap.enableGWCheckBoxes();
            var scmanager1 = Sys.WebForms.PageRequestManager.getInstance();
            scmanager1.add_endRequest(function(sender, e) {
                basket.giftWrap.enableGWCheckBoxes();
            });

            // allows user to enter/edit or remove gift wrap
            $(".chkGiftWrap").live("click", function(evt) {
                var chkbox = $(this).find("input");
                // show gift wrap popup
                shadowViewer.highlight({ 'resourceURL': '/stores/kitbag/help/giftwrap/giftwrap_enter.htm', 'width': 640, 'height': 550 });
                $(".gw_charsmax").text(KB.GiftWrap.taglength);
                if (chkbox.is(':checked')) {
                    $(".gw_text").data("bskItem", $(this).attr("rel")).focus();
                    $(".gw_add").show();
                } else {
                    $(".gw_text").data("bskItem", $(this).attr("rel")).attr("readonly", "true").val($('.giftwrapmsg' + $(this).attr("rel")).html().replace(KB.GiftWrap.emptymsg, ""));
                    $(".gw_remove").show();
                }
                $(".gw_cancel").data({ "chkBoxID": chkbox.attr("id") });
                basket.giftWrap.giftTagCalculateChars();
                $(".gw_price").html("£" + KB.GiftWrap.price);
            });

            $(".editGiftTag").live("click", function(evt) {
                shadowViewer.highlight({ 'resourceURL': '/stores/kitbag/help/giftwrap/giftwrap_enter.htm', 'width': 640, 'height': 550 });
                $(".gw_charsmax").text(KB.GiftWrap.taglength);
                $(".gw_text").data("bskItem", $(this).attr("rel")).show().val($('.giftwrapmsg' + $(this).attr("rel")).html().replace(KB.GiftWrap.emptymsg, "")).focus();
                $(".gw_edit").show();
                basket.giftWrap.giftTagCalculateChars();
            });
            $(".gw_info").live("click", function() {
                shadowViewer.highlight({ 'resourceURL': '/stores/kitbag/help/giftwrap/giftwrap_info.htm', 'width': 520, 'height': 310 });
                $(".gw_price").html("£" + KB.GiftWrap.price);
            });
            $(".gw_cancel").live("click", function() {
                shadowViewer.hide();
                var chkbox = $("#" + $(this).data("chkBoxID")).eq(0);
                if (chkbox.attr('checked')) {
                    chkbox.attr('checked', false);
                } else {
                    chkbox.attr('checked', true);
                }
            });
            $(".gw_add").live("click", function() {
                if ($(".gw_text").eq(0).val().length > KB.GiftWrap.taglength) {
                    basket.giftWrap.giftTagCalculateChars();
                } else {
                    // disable the user interface
                    EnableUI.Toggle(false);
                    // add gift wrap to basket line
                    KB.Services.Basket().InsertPrintingItem($(".gw_text").data("bskItem"), 16, 1, KB.GiftWrap.name, 0, KB.GiftWrap.price, basket.giftWrap.giftWrapAddedSuccess, basket.giftWrap.giftWrapError);
                }
            });
            $(".gw_edit").live("click", function() {
                var tagMSG = $(this).siblings(".gw_text").eq(0).val();
                if (tagMSG.length > KB.GiftWrap.taglength) {
                    basket.giftWrap.giftTagCalculateChars();
                } else {
                    // disable the user interface
                    EnableUI.Toggle(false);
                    // add gift wrap to basket line
                    KB.Services.Basket().UpdatePrintingItem($(".gw_text").data("bskItem"), 17, tagMSG, basket.giftWrap.giftWrapSuccess, basket.giftWrap.giftWrapError);
                }
            });
            $(".gw_remove").live("click", function() {
                // disable the user interface
                EnableUI.Toggle(false);
                // remove gift wrap from basket line
                KB.Services.Basket().RemovePrintingItem($(".gw_text").data("bskItem"), 17, basket.giftWrap.giftTagRemovedSuccess, basket.giftWrap.giftWrapError);
            });
            $(".gw_removeall").live("click", function() {
                // disable the user interface
                EnableUI.Toggle(false);
                // remove all gift wrap from basket
                KB.Services.Basket().RemovePrintingItemsByType(17, basket.giftWrap.giftTagAllRemovedSuccess, basket.giftWrap.giftWrapError);
            });
            $(".gw_cancelcountry").live("click", function() {
                shadowViewer.hide();
                var countrydd = $(".countrySelector");
                if (countrydd.length > 0) {
                    $(".countrySelector option[value='204']").attr('selected', 'selected');
                    basket.refreshContents();
                }
            });
            $("body").delegate(".countrySelector", "change", function(evt) {
                var countries = KB.GiftWrap.countries.split(",");
                var selectedCountry = $(".countrySelector").eq(0).val();
                var hasGiftWrapping = $(".chkGiftWrap input:checked").length;
                if (hasGiftWrapping > 0 && $.inArray(selectedCountry, countries) < 0) {
                    // if gift wrapping has been added and ship country is not in list
                    shadowViewer.highlight({ 'resourceURL': '/stores/kitbag/help/giftwrap/giftwrap_restrictions.htm', 'width': 520, 'height': 310 });
                }
            });
            $(".gw_text").live("keydown", function() {
                var tagMSG = $(".gw_text").eq(0);
                if (tagMSG.val().length > KB.GiftWrap.taglength) {
                    return false;
                }
            }).live("keyup", function() {
                var tagMSG = $(".gw_text").eq(0);
                tagMSG.val(tagMSG.val().substring(0, KB.GiftWrap.taglength));
                basket.giftWrap.giftTagCalculateChars();
            });

        },

        enableGWCheckBoxes: function() {
            // enable check boxes as click event has been initialised
            $(".chkGiftWrap input").attr('disabled', false);
            $(".chkGiftWrap").attr('disabled', false);
        },

        giftTagCalculateChars: function() {
            var tagMSG = $(".gw_text").eq(0).val();
            $(".gw_charsused").html(tagMSG.length);
            $(".gw_charsremaining").html(KB.GiftWrap.taglength - tagMSG.length);
        },

        giftWrapSuccess: function(result) {
            basket.feedback($(".chkGiftWrap[rel='" + $(".gw_text").data("bskItem") + "']"), "Altering gift wrap selection on this item");
            shadowViewer.hide({ 'callback': basket.refreshContents() });
        },

        giftWrapError: function(result) {
            alert("There was a problem with the operation");
            EnableUI.Toggle(true);
        },

        giftWrapAddedSuccess: function(result) {
            KB.Services.Basket().InsertPrintingItem($(".gw_text").data("bskItem"), 17, 1, $(".gw_text").eq(0).val(), 0, 0, basket.giftWrap.giftWrapSuccess, basket.giftWrap.giftWrapError);
        },

        giftTagRemovedSuccess: function(result) {
            KB.Services.Basket().RemovePrintingItem($(".gw_text").data("bskItem"), 16, basket.giftWrap.giftWrapSuccess, basket.giftWrap.giftWrapError);
        },

        giftTagAllRemovedSuccess: function(result) {
            KB.Services.Basket().RemovePrintingItemsByType(16, basket.giftWrap.giftWrapSuccess, basket.giftWrap.giftWrapError);
        }
    }
};

var orderDetails = {

    showInvalidGiftWrapMsg: function() {
        shadowViewer.highlight({ 'resourceURL': '/stores/kitbag/help/giftwrap/giftwrap_restrictions.htm', 'width': 520, 'height': 310 });
    }

}

$(document).ready(function() {

    if (typeof (Sys) !== "undefined") {
        var scmanager = Sys.WebForms.PageRequestManager.getInstance();

        scmanager.add_endRequest(function(sender, e) {
            Cufon.replace('.kbFont');
            Cufon.now();
            
            $("#promoimage").height($("#pageContainer").height());
        });
    }

    try {
        $("#aspnetForm").validate();
    }
    catch (Error) { }
});
