
var JS_BASE_URL = '../';
//var LOADING_HTML = '<div align="center"><br/>Loading...<br/><img src="' + JS_BASE_URL + 'images/icons/load_busy.gif"/><br/><br/></div>';
var BAG_WIDTH = 216;

var TIMEOUT_LOAD_MINI_CART = 30000;
var TIMEOUT_LOAD_QUICK_SHOP = 15000;
var TIMEOUT_SAVE_TO_BAG = 15000;

var ExtInitialised = false;

function getLoadingHtml() {
    return '<div align="center"><br/>Loading...<br/><img src="' + JS_BASE_URL + 'images/icons/load_busy.gif"/><br/><br/></div>';
}

function popUp(fileName, windowName, urlParameters, windowWidth, windowHeight, scrollHuh) {
    var windowFormat = 'width=' + windowWidth + ',height=' + windowHeight + ',scrollbars=' + scrollHuh + ',resizable=no';
    //    var newWindow = window.open(fileName + '?' + urlParameters + '&this_window=' + window.name, windowName, windowFormat, 'Editor');
    var urlFinal = null;
    if (urlParameters != null) {
        urlFinal = fileName + '?' + urlParameters;
    } else {
        urlFinal = fileName;
    }
    var newWindow = window.open(urlFinal, windowName, windowFormat, 'Editor');
    if (newWindow.opener == null) {
        newWindow.opener = window;
    }
    newWindow.focus();
}

// Extracted from prototype (see map/collect, extractScripts, evalScripts) 
extractScripts= function(responseText) {
  var ScriptFragment = '<script[^>]*>([\\S\\s]*?)<\/script>';
  var matchAll = new RegExp(ScriptFragment, 'img');
  var matchOne = new RegExp(ScriptFragment, 'im');
    var array = responseText.match(matchAll) || [];
    var results = [];
    for (var i = 0; i < array.length; i++) {
        var scriptTag = array[i];
        var temp = (scriptTag.match(matchOne) || ['', ''])[1];
        results.push(temp);
    }
    return results;
};

evalScripts= function(responseText) {
  var scriptTags = extractScripts(responseText);
    for (var i = 0; i < scriptTags.length; i++) {
        var scriptTag = scriptTags[i];
        eval(scriptTag);
    }
};

function generateRandomString() {
  return String((new Date()).getTime()).replace(/\D/gi,'');
}

addToCart = function(event, styleIndex, colourCount, categoryId, categoryPath, isFreegift) {
    //var quantity = document.getElementById('quantity-' + styleIndex).value;
    var singleColourSizeBarcode = document.getElementById('single-colour-size-barcode-' + styleIndex);
    if (singleColourSizeBarcode) {
        var barcode = singleColourSizeBarcode.value;
        var quantity = 1;
        showGiftCardForm(styleIndex, barcode, quantity, categoryId, categoryPath, false);
        //        showCart(barcode, quantity, categoryId, categoryPath);
    } else {
        var quantity = 1;
        if (!isFreegift) {
            var quantityOption = document.getElementById('quantity-' + styleIndex).options[document.getElementById('quantity-' + styleIndex).selectedIndex];
            quantity = quantityOption.value;            
        }
        var barcode = '';
        var barcodeOption = null;
        for (var i = 0; i < colourCount; i++) {
            var barcodeDivName = 'select-size-' + styleIndex + '-' + i;
            if (document.getElementById(barcodeDivName).style.display == '') {
                barcodeOption = document.getElementById(barcodeDivName).options[document.getElementById(barcodeDivName).selectedIndex];
                barcode = barcodeOption.value;
                break;
            }
        }
        //    alert("quantity[" + quantity + "] barcode[" + barcode + "]");

        // Out of stock check
        //    alert("["+barcodeOption.text+"]");
        if (barcodeOption.text.indexOf('(out of stock)') > -1) {
            alert("Cannot add item into shopping bag, the item is currently out of stock.");
        } else {
            showCart(barcode, quantity, categoryId, categoryPath, null, isFreegift);
        }
    }
};

addVoucherToCart = function(event, styleIndex) {
    //var quantity = document.getElementById('quantity-' + styleIndex).value;
    var singleBarcodeGiftVoucher = document.getElementById('single-barcode-giftvoucher-' + styleIndex);
    var barcode = singleBarcodeGiftVoucher.value;
    var quantityOption = document.getElementById('quantity-' + styleIndex).options[document.getElementById('quantity-' + styleIndex).selectedIndex];
    var quantity = quantityOption.value;
    showVoucherCart(barcode, quantity);
};

onColourSelected = function(selectEl, styleIndex, colourCount, imageDivPrefix, fileNameSuffix) {
    var oldSelectedIndex = 0;
    for (i = 0; i < colourCount; i++) {
        var barcodeDivName = 'select-size-' + styleIndex + '-' + i;
        if (document.getElementById(barcodeDivName).style.display == '') {

            document.getElementById(barcodeDivName).style.display = 'none';
            oldSelectedIndex = document.getElementById(barcodeDivName).selectedIndex;
        }
    }
    var barcodeDivNameNew = 'select-size-' + styleIndex + '-' + selectEl.selectedIndex;
    document.getElementById(barcodeDivNameNew).selectedIndex = oldSelectedIndex;
    document.getElementById(barcodeDivNameNew).style.display = '';
    cols_index[styleIndex] = selectEl.selectedIndex;
    document.getElementById(imageDivPrefix + styleIndex).src = cols_url[styleIndex].url[cols_index[styleIndex]] + fileNameSuffix;
    var rrp = cols_url[styleIndex].rrp[cols_index[styleIndex]];
    var csp = cols_url[styleIndex].csp[cols_index[styleIndex]];
//    alert(rrp  + "::" + csp);
    if (rrp != csp) {
        if (document.getElementById(imageDivPrefix + styleIndex + "-price-disc") != null) {
            document.getElementById(imageDivPrefix + styleIndex + "-price-disc").style.display = "";
        }
        if (document.getElementById(imageDivPrefix + styleIndex + "-price-no-disc") != null) {
            document.getElementById(imageDivPrefix + styleIndex + "-price-no-disc").style.display = "none";
        }
    } else {
        if (document.getElementById(imageDivPrefix + styleIndex + "-price-disc") != null) {
            document.getElementById(imageDivPrefix + styleIndex + "-price-disc").style.display = "none";
        }
        if (document.getElementById(imageDivPrefix + styleIndex + "-price-no-disc") != null) {
            document.getElementById(imageDivPrefix + styleIndex + "-price-no-disc").style.display = "";
        }        
    }
    if (document.getElementById(imageDivPrefix + styleIndex + "-rrp") != null) {
        document.getElementById(imageDivPrefix + styleIndex + "-rrp").innerHTML = rrp;
    }
    if (document.getElementById(imageDivPrefix + styleIndex + "-csp") != null) {
        document.getElementById(imageDivPrefix + styleIndex + "-csp").innerHTML = csp;
    }
    var specialsDesc = cols_url[styleIndex].specialsDesc[cols_index[styleIndex]];
    if (specialsDesc != '') {
        document.getElementById(imageDivPrefix + styleIndex + "-promo-row").style.display = "";
        document.getElementById(imageDivPrefix + styleIndex + "-promo-desc").innerHTML = specialsDesc;
    } else {
        document.getElementById(imageDivPrefix + styleIndex + "-promo-row").style.display = "none";
    }
    var specialsDesc2 = cols_url[styleIndex].specialsDesc2[cols_index[styleIndex]];
    if (specialsDesc2 != '') {
        document.getElementById(imageDivPrefix + styleIndex + "-promo-row-2").style.display = "";
        document.getElementById(imageDivPrefix + styleIndex + "-promo-desc-2").innerHTML = specialsDesc2;
    } else {
        document.getElementById(imageDivPrefix + styleIndex + "-promo-row-2").style.display = "none";
    }
};

popupEmailToFriend = function(styleIndex, url) {
    var colourSelectId = 'select-colour-' + styleIndex;
    var colourOption = document.getElementById(colourSelectId).options[document.getElementById(colourSelectId).selectedIndex];
    popUp(JS_BASE_URL + 'browsesearch/LoadEmailToFriend.aspx', 'emailToFriend', url + '&colour=' + colourOption.value, 620, 450, 'yes');
};

var mapquickshopbutton;

hideQuickShopButton = function (event, divId) {
    var imageDiv = Ext.get(divId);
//    document.getElementById('container').innerHTML = imageDiv.getX() + "::" + imageDiv.getY() + "::" + imageDiv.getWidth() + "::" + imageDiv.getHeight();
//    document.getElementById('point').innerHTML = Ext.lib.Event.getPageX(event) + "::" + Ext.lib.Event.getPageY(event);
//    if(!imageDiv.getRegion().contains(new Ext.lib.Point(Ext.lib.Event.getPageX(event), Ext.lib.Event.getPageY(event)))) {
    if(!(Ext.lib.Event.getPageX(event) > imageDiv.getX() &&
        Ext.lib.Event.getPageX(event) < (imageDiv.getWidth() + imageDiv.getX()) &&
        Ext.lib.Event.getPageY(event) > imageDiv.getY() &&
        Ext.lib.Event.getPageY(event) < (imageDiv.getHeight() + imageDiv.getY()))) {
//        document.getElementById(divId).border=0;
        if (mapquickshopbutton != null) {
            mapquickshopbutton.hide();
        }
    } else {
//        document.getElementById(divId).border=5;
    }
};

var lastQuickShopButton = null;
var quickShopStyleIds = null;
var quickShopShortDescs = null;
var quickShopUniqueIds = null;
var quickShopColours = null;

showQuickShopButtonFake = function(event, divId) {
    showQuickShopButton(event, divId, ['150545'], ['150545'], ['150545'], ['BLACK'], 0, '', 0);
};

showQuickShopButton = function (event, divId, uniqueIds, shortDescs, styleIds, colours, categoryId, categoryPath, extraHeight) {
    showQuickShopButtonByUrlBase(event, JS_BASE_URL + "browsesearch/LoadQuickShop.aspx", divId, uniqueIds, shortDescs, styleIds, colours, categoryId, categoryPath, extraHeight);
};

showQuickShopButtonByUrlBase = function (event, urlBase, divId, uniqueIds, shortDescs, styleIds, colours, categoryId, categoryPath, extraHeight) {

    if (!ExtInitialised) {
        return;
    }

    var imageDiv = Ext.get(divId);
    //    document.getElementById(divId).border=3;

    if (divId != lastQuickShopButton) {
        lastQuickShopButton = divId;
        if (mapquickshopbutton != null) {
            mapquickshopbutton.hide();
        }
    }

    if (mapquickshopbutton == null) {
        quickShopShortDescs = shortDescs;
        quickShopStyleIds = styleIds;
        quickShopUniqueIds = uniqueIds;
        quickShopColours = colours;
        mapquickshopbutton = new Ext.Tip({
        html: '<span class="quickShopLink"><a href="#" onclick="showProductDetailTooltip(event,\'' + urlBase + '\',\'' + divId + '\',\'' + categoryId + '\',\'' + categoryPath + '\',' + extraHeight + '); return false;">quick shop</a></span>',
            closable: false,
            listeners: {
                hide: function(w) {
                    mapquickshopbutton = null;
                }
            }
        });
        mapquickshopbutton.showAt([(imageDiv.getLeft()) - 5, imageDiv.getTop() - 5]);
        //        mapquickshopbutton.showBy(imageDiv, 'b-t');
        var pEvent = function(e) {
            if (!(e.getPageX() > imageDiv.getX() &&
                e.getPageX() < (imageDiv.getWidth() + imageDiv.getX()) &&
                e.getPageY() > imageDiv.getY() &&
                e.getPageY() < (imageDiv.getHeight() + imageDiv.getY()))) {
                //            if(!imageDiv.getRegion().contains(e.getPoint())){
                if (mapquickshopbutton != null) {
                    mapquickshopbutton.hide();
                }
            }
        };
        mapquickshopbutton.body.addListener("mouseout", pEvent, mapquickshopbutton);
    }
    var xy = mapquickshopbutton.getPosition();
    if ((xy[0] != imageDiv.getLeft() - 5) && (xy[1] != imageDiv.getTop() - 5)) {
        mapquickshopbutton.showAt([(imageDiv.getLeft()) - 5, imageDiv.getTop() - 5]);
    }
    //    mapquickshopbutton.showBy(imageDiv, 'b-t');
};

showQuickShopButtonByUrlBaseAutoClick = function (event, divId, uniqueIds, shortDescs, styleIds, colours, categoryId, categoryPath, extraHeight) {

    if (!ExtInitialised) {
        return;
    }
    quickShopShortDescs = shortDescs;
    quickShopStyleIds = styleIds;
    quickShopUniqueIds = uniqueIds;
    quickShopColours = colours;
    showProductDetailTooltipFreegift(event, JS_BASE_URL + 'browsesearch/LoadQuickShopFg.aspx', divId, categoryId, categoryPath, extraHeight);
};

var productDetailShowing = false;
var lastId;
var mapwin;
var tabQuickShop;

showProductDetailTooltipFake = function(event, divId) {

    showProductDetailTooltip(event, JS_BASE_URL + "browsesearch/LoadQuickShop.aspx", divId, 0);

};

renderQuickShopTab = function(categoryId, categoryPath, urlBase) {
        //w.body.dom.innerHTML = 'Loading...';
    var w = tabQuickShop.getActiveTab();
    w.body.dom.innerHTML = getLoadingHtml();

        var finalUrl = urlBase;
    if (finalUrl.indexOf("?") > -1) {
        finalUrl += "&";
    } else {
        finalUrl += "?";
    }
    finalUrl += "categoryId=" + categoryId + "&categoryPath=" + categoryPath + "&uniqueId=" + tabQuickShop.getActiveTab().initialConfig.configUniqueId +
                "&styleId=" + tabQuickShop.getActiveTab().initialConfig.configStyleId +
                "&colour=" + escape(tabQuickShop.getActiveTab().initialConfig.configColour);
    Ext.Ajax.request({
    url: finalUrl,
        timeout: TIMEOUT_LOAD_QUICK_SHOP,
            success: function(r) {
                w.body.dom.innerHTML = r.responseText;
                evalScripts(r.responseText);
    //                            r.responseText.evalScripts();
            },
            failure: function(r) {
                w.body.dom.innerHTML = '<div align="center"><br/>Failed to load window<br/> <a href="#" onclick="renderQuickShopTab(\'' + categoryId + '\',\'' + categoryPath + '\',\'' + urlBase + '\');return false;">Refresh</a><br/><br/></div>';
    //                            alert("Failed to load window. Please try again later.");
            }
        });
};

    showProductDetailTooltipFreegift = function (event, urlBase, divId, categoryId, categoryPath, extraHeight) {
    showProductDetailTooltipGeneric(event, urlBase, divId, categoryId, categoryPath, 'freegift details', extraHeight);
}
showProductDetailTooltip = function (event, urlBase, divId, categoryId, categoryPath, extraHeight) {
    showProductDetailTooltipGeneric(event, urlBase, divId, categoryId, categoryPath, 'quick shop by styles', extraHeight);
}
showProductDetailTooltipGeneric = function(event, urlBase, divId, categoryId, categoryPath, title, extraHeight) {

    var WIN_QUICK_SHOP_WIDTH = 200;
    var WIN_QUICK_SHOP_HEIGHT = 345;

    productDetailShowing = true;

    var button = Ext.get(divId);

    if (mapwinzoom != null) {
        mapwinzoom.hide();
    }

    if (mapwinenlargeSingle != null) {
        mapwinenlargeSingle.close();
    }

    //    alert(divId);
    if (divId != lastId) {
        if (lastId != null) {
            mapwin.close();
        }
        lastId = divId;
    }

    //    var quickShopUrl = "LoadQuickShop.aspx?styleId=" + styleId + "&colour=" + colour + "&modelFileNamePrefix=" + modelFileNamePrefix;
    var finalHeight = WIN_QUICK_SHOP_HEIGHT;
    finalHeight = finalHeight + extraHeight;
    
    //    if ((divId == "img-style-12347") || (divId == "img-style-12348") || (divId == "img-style-12349") || (divId == "img-style-12350") || (divId == "img-style-12351")) {
    //        quickShopUrl = "quickshop_main_model.htm";
    //        finalHeight = WIN_QUICK_SHOP_HEIGHT + 220;
    //    }


    var tabItems = new Array();
    for (var i = 0; i < quickShopStyleIds.length; i++) {
        var shortDesc = quickShopShortDescs[i];
        var uniqueId = quickShopUniqueIds[i];
        var styleId = quickShopStyleIds[i];
        var colour = quickShopColours[i];
        tabItems[i] = {
        title: shortDesc,
        configUniqueId: uniqueId,
        configStyleId: styleId,
        configColour: colour,
        listeners: {
                render: function(w) {
                    renderQuickShopTab(categoryId, categoryPath, urlBase);
                }
            }
        };
    }


    // create the window on the first click and reuse on subsequent clicks
    if (mapwin == null) {
        tabQuickShop = new Ext.TabPanel({
            //        renderTo: document.body,
            activeTab: 0,
            frame: true,
            defaults: { autoScroll: true },
            deferredRender: true,
            enableTabScroll: true,
            //        tabPosition: 'bottom',
            items: tabItems
        });
        mapwin = new Ext.Window({
            layout: 'fit',
            title: title,
            closeAction: 'close',
            width: WIN_QUICK_SHOP_WIDTH,
            height: finalHeight,
            resizable: false,
            items: tabQuickShop,
            listeners: {
                render: function(w) {
                    //                    w.body.dom.innerHTML = '<div class="bubble_content"><br/>QuickShop for ['+divId+'] details go here. <br/><br/></div>';
                },
                close: function(w) {
                    mapwin = null;
                    lastId = null;
                    if (mapquickshopbutton != null) {
                        mapquickshopbutton.hide();
                    }
                }
            }
        });
    }
    //    alert(Ext.getBody().getScroll().left);
    //    alert(Ext.getBody().getHeight());
    //    alert(Ext.lib.Dom.getViewportHeight());
    //    alert(Ext.lib.Dom.getViewportWidth());
    var left = button.getLeft() + 20;
    if (Ext.lib.Dom.getViewportWidth() > WIN_QUICK_SHOP_WIDTH * 2) {
        if (button.getLeft() + 20 + WIN_QUICK_SHOP_WIDTH > Ext.lib.Dom.getViewportWidth() + Ext.getBody().getScroll().left) {
            left = button.getLeft() + 20 - WIN_QUICK_SHOP_WIDTH;
        }
    }
    var top = button.getTop() + 20;
    if (Ext.lib.Dom.getViewportHeight() > finalHeight * 2) {
        if (button.getTop() + 20 + finalHeight > Ext.lib.Dom.getViewportHeight() + Ext.getBody().getScroll().top) {
            top = button.getTop() + 20 - finalHeight;
        }
    }
    mapwin.setPosition(left, top);
    mapwin.show(button);
};

var mapwinFreegift;
var tabQuickShopFreegift;

renderFreegiftTab = function(urlBase) {
        //w.body.dom.innerHTML = 'Loading...';
    var w = tabQuickShopFreegift.getActiveTab();
    w.body.dom.innerHTML = getLoadingHtml();

        var finalUrl = urlBase;
    if (finalUrl.indexOf("?") > -1) {
        finalUrl += "&";
    } else {
        finalUrl += "?";
    }
    var categoryId = tabQuickShopFreegift.getActiveTab().initialConfig.configCategoryId;
    var cartItemsCount = tabQuickShopFreegift.getActiveTab().initialConfig.configCartItemsCount;
    finalUrl += "categoryId=" + categoryId + "&cartItemsCount=" + cartItemsCount;

//        var iframe = Ext.DomHelper.append(document.body, { tag: 'iframe', frameBorder: 0, src: finalUrl, width: '100%', height: '100%' });
//        w.contentEl = iframe;
    Ext.Ajax.request({
    url: finalUrl,
        timeout: TIMEOUT_LOAD_QUICK_SHOP,
            success: function(r) {
                w.body.dom.innerHTML = r.responseText;
//                evalScripts(r.responseText);
    //                            r.responseText.evalScripts();
            },
            failure: function(r) {
                w.body.dom.innerHTML = '<div align="center"><br/>Failed to load window<br/> <a href="#" onclick="renderFreegiftTab(\'' + urlBase + '\');return false;">Refresh</a><br/><br/></div>';
    //                            alert("Failed to load window. Please try again later.");
            }
        });
};

showFreegiftSelection = function(categoryIds, shortDescs, cartItemsCount) {

    var WIN_FREE_GIFT_WIDTH = 850;
    var WIN_FREE_GIFT_HEIGHT = 640;

//    var button = Ext.get(divId);

    var urlBase = JS_BASE_URL + "browsesearch/LoadFreegiftList.aspx";

    var tabItems = new Array();
    for (var i = 0; i < shortDescs.length; i++) {
        var shortDesc = shortDescs[i];
        var categoryId = categoryIds[i];
        tabItems[i] = {
        title: shortDesc,
        configCategoryId: categoryId,
        configCartItemsCount: cartItemsCount,
        listeners: {
                render: function(w) {
                    renderFreegiftTab(urlBase);
                }
            }
        };
    }
//    tabItems[0] = {
//    title: "girl-accessories",
//    configCategoryId: "1900",
//    listeners: {
//            render: function(w) {
//                renderFreegiftTab(urlBase);
//            }
//        }
//    };
//    tabItems[1] = {
//    title: "boy-accessories",
//    configCategoryId: "1902",
//    listeners: {
//            render: function(w) {
//                renderFreegiftTab(urlBase);
//            }
//        }
//    };

    // create the window on the first click and reuse on subsequent clicks
    if (mapwinFreegift == null) {
        tabQuickShopFreegift = new Ext.TabPanel({
            //        renderTo: document.body,
            activeTab: 0,
            frame: true,
            defaults: { autoScroll: true },
            deferredRender: true,
            enableTabScroll: true,
            //        tabPosition: 'bottom',
            items: tabItems
        });
        mapwinFreegift = new Ext.Window({
            layout: 'fit',
            title: 'freegift selection',
            closeAction: 'close',
            width: WIN_FREE_GIFT_WIDTH,
            height: WIN_FREE_GIFT_HEIGHT,
            resizable: false,
            modal: true,
            items: tabQuickShopFreegift,
            listeners: {
                render: function(w) {
                    //                    w.body.dom.innerHTML = '<div class="bubble_content"><br/>QuickShop for ['+divId+'] details go here. <br/><br/></div>';
                },
                close: function(w) {
                    mapwinFreegift = null;
                }
            }
        });
    }
//    mapwinFreegift.show(button);
    mapwinFreegift.show();
};

var mapwinenlargeSingle;
var mapwinenlargeSingleCanClose = true;
showEnlargeImageSingle = function (event, divId, imageUrl) {

    if (mapwinzoom != null) {
        mapwinzoom.hide();
    }

    if (mapwin != null) {
        mapwin.close();
    }
    if (mapwinenlargeSingle != null) {
        if (!mapwinenlargeSingleCanClose) {
            return;
        }
        mapwinenlargeSingle.close();
    }

    var button = Ext.get(divId);

    // create the window on the first click and reuse on subsequent clicks
    if (mapwinenlargeSingle == null) {
        mapwinenlargeSingleCanClose = false;
        mapwinenlargeSingleImageUrl = imageUrl;
        mapwinenlargeSingle = new Ext.Window({
            layout: 'fit',
            title: 'Enlarge Image',
            closeAction: 'close',
            width:460,
            height:540,
			cls: 'white',
            resizable: true,
            listeners: {
                render: function(w) {
                    w.body.dom.innerHTML = '<table border="0" cellspacing="0" cellpading="0" width="100%" height="100%"><tr><td valign="middle"><div align="center"><img src="' + mapwinenlargeSingleImageUrl + '"/></div></td></tr></table>';
                },
                close: function(w) {
                    mapwinenlargeSingle = null;
                },
                show: function(w) {
                    mapwinenlargeSingleCanClose = true;
                }
            }
        });
    }
    mapwinenlargeSingle.show(button);
};
function IsNumeric(sText)

{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;


   for (i = 0; i < sText.length && IsNumber == true; i++)
      {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
         {
         IsNumber = false;
         }
      }
   return IsNumber;

   }

validateGiftCard = function () {
    var priceString = document.getElementById("form-gift-card")["single-colour-size-f1"].value;
    var priceFloat = -1;
//    alert("priceString ["+priceString+"]");
    if (!IsNumeric(priceString)) {
    } else {
        priceFloat = parseFloat(priceString);
    }
//    alert("priceFloat ["+priceFloat+"]");
    if (isNaN(priceFloat) || (priceFloat < giftCardMinPrice) || (priceFloat > giftCardMaxPrice)) {
        var msg = 'Please enter a valid amount for the gift card.  \nYou may enter a value between ' + currencyPrefix + giftCardMinPrice + ' and '+currencyPrefix+ giftCardMaxPrice + '';
        alert(msg);
        document.getElementById("form-gift-card")["single-colour-size-f1"].focus();
        return false;
    }
    document.getElementById("form-gift-card")["single-colour-size-f1"].value = priceFloat.toFixed(2);
    return true;
};

var mapwinGirftCard;
showGiftCardForm = function (styleIndex, barcode, quantity, categoryId, categoryPath, editMode) {
    if (mapwinGirftCard == null) {
        mapwinGirftCard = new Ext.Window({
            layout: 'fit',
            title: 'Gift Card Details',
            closeAction: 'close',
            width:350,
            height:235,
//			cls: 'white',
            resizable: true,
            modal: true,
            focus: function(w) {
                document.getElementById("form-gift-card")["single-colour-size-f1"].focus();
            }, listeners: {
                render: function(w) {
            var innerHtml = [
                '<br/><form id="form-gift-card">',
                '<table cellspacing="6" border="0" cellpadding="0">',
                '<tr><td style="padding:3px;">',
                '<span style="width:100px">Price:</span>' ,
                '</td><td style="padding:3px;">',
                currencyPrefix + '<input type="text" size="5" maxlength="6" name="single-colour-size-f1"/> (max '+currencyPrefix+giftCardMaxPrice+' for each card)<br />' ,
                '</td></tr>',
                '<tr><td style="padding:3px;">',
                '<span style="width:100px">To:</span>',
                '</td><td style="padding:3px;">',
                '<input type="text" size="40" maxlength="25" name="single-colour-size-f2"/><br />',
                '</td></tr>',
                '<tr><td style="padding:3px;">',
                '<span style="width:100px">Love From:</span>' ,
                '</td><td style="padding:3px;">',
                '<input type="text" size="40" maxlength="25" name="single-colour-size-f3"/><br />' ,
                '</td></tr>',
                '<tr><td style="padding:3px;">',
                '<span style="width:100px">You are such a star because:</span>' ,
                '</td><td style="padding:3px;">',
                '<textarea style="color: #77716d;font: 400 10px/13px Arial, Verdana, sans-serif;" cols="30" rows="3" name="single-colour-size-f4"></textarea><br />',
                '</td></tr>',
                '</table>'
            ];
                    if (editMode) {
                        innerHtml.push('<div align="center"><a href="#" onclick="if (validateGiftCard()) { updateCart(\'' + styleIndex + '\');mapwinGirftCard.close(); } return false;"><img src="' + JS_BASE_URL + 'images/btn-continue-v2.gif" border="0"/></a><a href="#" onclick="mapwinGirftCard.close();return false;"><img src="' + JS_BASE_URL + 'images/btn-close-v2.gif" border="0"/></a></div>');
                    } else {
                        innerHtml.push('<div align="center"><a href="#" onclick="if (validateGiftCard()) { showCart(\'' + barcode + '\', \'' + quantity + '\', \'' + categoryId + '\', \'' + categoryPath + '\', \'form-gift-card\', false); } return false;"><img src="' + JS_BASE_URL + 'images/btn-continue-v2.gif" border="0"/></a><a href="#" onclick="mapwinGirftCard.close();return false;"><img src="' + JS_BASE_URL + 'images/btn-close-v2.gif" border="0"/></a></div>');
                    }
                    innerHtml.push('</form>');
                    w.body.dom.innerHTML = innerHtml.join('');
                    if (editMode) {
                        document.getElementById("form-gift-card")["single-colour-size-f1"].value = document.getElementById("single-colour-size-f1-" + styleIndex).value;
                        document.getElementById("form-gift-card")["single-colour-size-f2"].value = document.getElementById("single-colour-size-f2-" + styleIndex).value;
                        document.getElementById("form-gift-card")["single-colour-size-f3"].value = document.getElementById("single-colour-size-f3-" + styleIndex).value;
                        document.getElementById("form-gift-card")["single-colour-size-f4"].value = document.getElementById("single-colour-size-f4-" + styleIndex).value;
                    }
                },
                close: function(w) {
                    mapwinGirftCard = null;
                },
                show: function(w) {
                }
            }
        });
    }
    if (mapquickshopbutton != null) {
        mapquickshopbutton.hide();
    }
    if (mapwin != null) {
        mapwin.hide();
    }
    mapwinGirftCard.show();
};

var mapwinzoom;
var domzoom;
var lastZoomUrl;
var mapwinzoom_can_hide;
var mapwinzoom_can_show = true;
showZoomImage = function(event, divId, imageUrlZoom) {

//    if ((mapwinenlarge != null) || (mapwinenlargeSingle != null) || (mapwin != null)) {
//    if ((mapwinenlarge != null) || (mapwinenlargeSingle != null)) {
    if ((mapwinenlargeSingle != null)) {
        return;
    }

    var button = Ext.get(divId);

    // create the window on the first click and reuse on subsequent clicks
    if (mapwinzoom == null) {
        lastZoomUrl = imageUrlZoom;
        mapwinzoom = new Ext.Window({
            layout: 'fit',
            title: 'Zoom Image',
            closeAction: 'close',
            width: 238,
            height: 274,
            cls: 'white',
            x: button.getRight(),
            y: button.getTop(),
            resizable: false,
            closable: true,
            listeners: {
                render: function(w) {
                    w.body.dom.innerHTML = '<img src="' + lastZoomUrl + '">';
                    domzoom = w.body.dom;
                },
                close: function(w) {
                    mapwinzoom = null;
                },
                beforeHide: function(w) {
                    mapwinzoom_can_hide = false;
                },
                hide: function(w) {
                    mapwinzoom_can_show = true;
                },
                beforeShow: function(w) {
                    mapwinzoom_can_show = false;
                },
                show: function(w) {
                    mapwinzoom_can_hide = true;
                }
            }
        });
    } else {
        updateDomZoom(event, button, imageUrlZoom);
    }
    if (mapwinzoom_can_show) {
        //       button.setOpacity(0.5);
        mapwinzoom.setPosition(button.getRight(), button.getTop());
        mapwinzoom.show(button);
    }
};

updateDomZoom = function(event, button, imageUrlZoom) {
    // Update URL
    if (domzoom != null) {
        if (lastZoomUrl != imageUrlZoom) {
            lastZoomUrl = imageUrlZoom;
            domzoom.innerHTML = '<img src="' + lastZoomUrl + '">';

            mapwinzoom.setPosition(button.getRight(), button.getTop());
        }
    }
};
onZoomImageMouseClick = function(event, divId, imageUrlZoom) {
    showZoomImage(event, divId, imageUrlZoom);
};
onZoomImageMouseMove = function(event, divId, imageUrlZoom) {
    var button = Ext.get(divId);
    updateDomZoom(event, button, imageUrlZoom);
    if (domzoom != null) {
        if (mapwinzoom_can_hide) {
            domzoom.scrollLeft = Ext.lib.Event.getPageX(event) - button.getLeft();
            domzoom.scrollTop = Ext.lib.Event.getPageY(event) - button.getTop();
        }
    }
};

onZoomImageMouseOut = function (event, divId) {
    var button = Ext.get(divId);

    if (mapwinzoom != null) {
//        alert("close");
        if (mapwinzoom_can_hide) {
//            button.setOpacity(1.0);
            mapwinzoom.hide(button);
//            mapwinzoom.close();
        }
    }
};

renderMiniCartTab = function() {
    var button = Ext.get("shopping-bag");
    var finalWidth = button.getLeft() - (BAG_WIDTH - 100);

    var w = mapwinbag;
    w.body.dom.innerHTML = getLoadingHtml();
    Ext.Ajax.request({
        url: JS_BASE_URL+'cart/LoadMiniCart.aspx',
        timeout: TIMEOUT_LOAD_MINI_CART,
        success: function(r) {
            w.body.dom.innerHTML = r.responseText;
            // IE6 bug, combo box on page appears on top of window. Reset position fixes this
            if (mapwinbag != null) {
                mapwinbag.setPosition(finalWidth, button.getBottom());
//                                        if ((document.documentElement || document.body).scrollTop == 0) {
//                                            mapwinbag.setPosition(finalWidth, button.getBottom());
//                                        } else {
//                                            mapwinbag.setPosition(finalWidth, (document.documentElement || document.body).scrollTop + 5);
//                                        }
            }
        },
        failure: function(r) {
            w.body.dom.innerHTML = '<div align="center"><br/>Failed to load window<br/> <a href="#" onclick="renderMiniCartTab();return false;">Refresh</a><br/><br/></div>';
//            alert("Failed to load window. Please try again later.");
//                                    mapwinbag.close();
        }
    });
};

renderFailedToAddToBag = function() {
    var w = mapwinbag;
    w.body.dom.innerHTML = '<div align="center"><br/>Failed to add item to shopping bag<br/> <a href="#" onclick="renderMiniCartTab();return false;">Refresh</a><br/><br/></div>';
};

displayMapWinBag = function(callback, modal) {
    var button = Ext.get("shopping-bag");
    var finalWidth = button.getLeft() - (BAG_WIDTH - 100);

    if (mapwinbag == null) {
        mapwinbagcanclose = false;
        mapwinbag = new Ext.Window({
            layout: 'fit',
            title: 'shopping bag',
            closeAction: 'close',
            modal: modal,
            width: BAG_WIDTH,
            //                    height:100,
//                    x: finalWidth,
//                    y: button.getBottom(),
            focus: Ext.emptyFn,
            resizable: false,
            closable: true,
            listeners: {
                render: function(w) {
                    callback();
                },
                close: function(w) {
                    mapwinbag = null;
                },
                show: function(w) {
                    mapwinbagcanclose = true;
                }
            }
        });
    }
    // In FF3.5, setPosition() scrolls the browser to the top
    mapwinbag.setPosition(finalWidth, button.getBottom());
//            if ((document.documentElement || document.body).scrollTop == 0) {
//                mapwinbag.setPosition(finalWidth, button.getBottom());
//            } else {
//                mapwinbag.setPosition(finalWidth, (document.documentElement || document.body).scrollTop + 5);
//            }
    // moveTo() doesn't work
//            mapwinbag.moveTo(finalWidth, button.getBottom());
    // Cannot afford not to ignore close bug, otherwise will loose add to cart call
    //           mapwinbag.show(button);
    mapwinbag.show();
};

var mapwinbag;
var mapwinbagcanclose = true;
showCart = function (barcode, quantity, categoryId, categoryPath, extraForm, isFreegift) {

    //    var scrollEl = Ext.get(document.documentElement || document.body);
    //    scrollEl.scrollTo('top', 0);

    //    alert(Ext.getBody().getScroll().top);
    //    if (Ext.getBody().getScroll().top > 100) {
    Ext.pp.msg('add to bag', 'Please wait while the item is added to your shopping bag.');
    //        Ext.pp.show('add to bag', 'Please wait while the item is added to your shopping bag.');
    //    }

    if (mapwinbag != null) {
        if (!mapwinbagcanclose) {
            return;
        }
        mapwinbag.close();
    }

    var isFreegiftFinal = 0;
    if (isFreegift) {
        isFreegiftFinal = 1;
    }

    var url = JS_BASE_URL + 'cart/SaveAddToCart.aspx?freegift=' + isFreegiftFinal + '&barcode=' + barcode + '&quantity=' + quantity + '&categoryId=' + categoryId + '&categoryPath=' + categoryPath;
    var formDom = null;
    var formMethod = "GET";
    //    var formParams = "";
    if (extraForm != null) {
        //        formDom = Ext.get(extraForm).dom;
        //        formParams = Ext.lib.Ajax.serializeForm(Ext.get(extraForm).dom);
        //        alert("formParams ["+formParams+"]");
        //        url = url + '&' + formParams;
        formDom = Ext.get(extraForm).dom;
        formMethod = "POST";
    }


    Ext.Ajax.request({
        url: url,
        form: formDom,
        method: formMethod,
        timeout: TIMEOUT_SAVE_TO_BAG,
        success: function (r) {
            // Get number of items to determine height of shopping bag window (not need, Ext does this for us)
            // create the window on the first click and reuse on subsequent clicks
            //            alert(r.responseText);
            //            Ext.pp.ghost();
            Ext.cart.msg(r.responseText);
            //            Ext.pp.msg('SSSSS', r.responseText);
            if (!isFreegift) {
                displayMapWinBag(function () { renderMiniCartTab(); }, false);
                if (mapwinGirftCard != null) {
                    mapwinGirftCard.close();
                }
            } else {
                displayMapWinBag(function () { renderMiniCartTab(); }, true);
                if (mapwin != null) {
                    mapwin.close();
                }
                if (mapwinFreegift != null) {
                    mapwinFreegift.close();
                }
                hideFreegift();
            }
        },
        failure: function (r) {
            //            alert("Failed to add item to shopping bag. Please try again later.");
            displayMapWinBag(function () { renderFailedToAddToBag(); });
        }
    });
};

showVoucherCart = function(barcode, quantity) {

    Ext.pp.msg('add to bag', 'Please wait while the item is added to your shopping bag.');

    if (mapwinbag != null) {
        if (!mapwinbagcanclose) {
            return;
        }
        mapwinbag.close();
    }

    var url = JS_BASE_URL + 'cart/SaveAddVoucherToCart.aspx?barcode=' + barcode + '&quantity=' + quantity;
    var formDom = null;
    var formMethod = "GET";

    Ext.Ajax.request({
        url: url,
        form: formDom,
        method: formMethod,
        timeout: TIMEOUT_SAVE_TO_BAG,
        success: function(r) {
            // Get number of items to determine height of shopping bag window (not need, Ext does this for us)
            // create the window on the first click and reuse on subsequent clicks
            //            alert(r.responseText);
            //            Ext.pp.ghost();
            Ext.cart.msg(r.responseText);
            //            Ext.pp.msg('SSSSS', r.responseText);
            displayMapWinBag(function() { renderMiniCartTab(); }, false);
        },
        failure: function(r) {
            //            alert("Failed to add item to shopping bag. Please try again later.");
            displayMapWinBag(function() { renderFailedToAddToBag(); }, false);
        }
    });
};

// Uncomment this to make shopping bag follow user's scroll
//Ext.EventManager.on(window, 'scroll', function(){
//    if (mapwinbag != null) {
//        var button = Ext.get("shopping-bag");
//        var finalWidth = button.getLeft() - (216 - 100);
//        if ((document.documentElement || document.body).scrollTop == 0) {
//            mapwinbag.setPosition(finalWidth, button.getBottom());
//        } else {
//            mapwinbag.setPosition(finalWidth, (document.documentElement || document.body).scrollTop + 5);
//        }
//    }
//}, window, {buffer: 50});

displayCartRefreshMsg = function(action) {
    var innerHtml = [
        '<table width="202" border="0" cellpadding="4" cellspacing="0">',
        '  <tr>',
        '    <td style="padding:4px 4px 4px 4px" width="202" valign="middle" bgcolor="#EEEEEE"><table width="194" border="0" align="center" cellpadding="0" cellspacing="5" bgcolor="#FFFFFF">',
        '        <tr>',
        '          <td colspan="2" class="link-style">',
        '          <br />',
        '<div align="center"><input type="image" src="' + JS_BASE_URL + 'assets/img/shopping-list/update-changes.gif" border="0" onclick="document.getElementById(\'form-cart-action\').value=\'' + action + '\';document.getElementById(\'form-checkout\').submit();"/><br /><br /><span style="font: 400 10px/13px Arial, Verdana, sans-serif">to refresh price & stock values</span></div>',
        '          <br />',
        '          </td>',
        '        </tr>',
        '    </table></td>',
        '  </tr> ',
        '</table>'
    ];
    Ext.refreshCart.msg(innerHtml.join(''));
};
Ext.cart = function(){
    var msgCt;
    return {
        msg : function(htmlContent){
            if (msgCt == null) {
                msgCt = Ext.get("added-to-cart-div");
            }
            if(!msgCt){
//                alert("Error: added-to-cart-div not found. Creating now.");
                msgCt = Ext.DomHelper.insertFirst(document.body, {id:'added-to-cart-div'}, true);
            }
            msgCt.alignTo(document, 't-t');
//            var s = String.format.apply(String, Array.prototype.slice.call(arguments, 0));
            var m = Ext.DomHelper.append(msgCt, {html:htmlContent}, true);
            m.slideIn('t').pause(2).ghost("t", {remove:true});
        },

        init : function(){
            if(!msgCt){
                msgCt = Ext.DomHelper.insertFirst(document.body, {id:'added-to-cart-div'}, true);
            }
            msgCt.alignTo(document, 't-t');
        }
    };
}();

Ext.refreshCart = function(){
    var msgCt;
    return {
        msg : function(htmlContent){
            if (msgCt == null) {
                msgCt = Ext.get("refresh-cart-div");
            }
            if(!msgCt){
//                alert("Error: refresh-cart-div not found. Creating now.");
                msgCt = Ext.DomHelper.insertFirst(document.body, {id:'refresh-cart-div'}, true);
            }
            msgCt.alignTo(document, 't-t');
//            var s = String.format.apply(String, Array.prototype.slice.call(arguments, 0));
            var m = Ext.DomHelper.append(msgCt, {html:htmlContent}, true);
            m.slideIn('t').pause(3).ghost("t", {remove:true});
//            m.slideIn('t');
        },

        init : function(){
            if(!msgCt){
                msgCt = Ext.DomHelper.insertFirst(document.body, {id:'refresh-cart-div'}, true);
            }
            msgCt.alignTo(document, 't-t');
        }
    };
}();

Ext.pp = function() {
    var msgCt = null;
//    var showHide = null;

    function createBox(t, s) {
        return ['<div class="msg">',
                '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
                '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3>', t, '</h3>', s, '</div></div></div>',
                '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
                '</div>'].join('');
    }
    return {
        msg: function(title, format) {
            if (msgCt == null) {
                msgCt = Ext.get("msg-div");
            }
            if (msgCt == null) {
//                alert("Error: msg-div not found. Creating now.");
                msgCt = Ext.DomHelper.insertFirst(document.body, { id: 'msg-div' }, true);
            }
            msgCt.alignTo(document, 't-t');
            var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
            var m = Ext.DomHelper.append(msgCt, { html: createBox(title, s) }, true);
            m.slideIn('t').pause(2).ghost("t", { remove: true });
        },
//        show: function(title, format) {
//            if (!msgCt) {
//                msgCt = Ext.DomHelper.insertFirst(document.body, { id: 'msg-div' }, true);
//            }
//            if (showHide == null) {
//                //                showHide.ghost("t", {remove:true});
//                msgCt.alignTo(document, 't-t');
//                var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
//                showHide = Ext.DomHelper.append(msgCt, { html: createBox(title, s) }, true);
//                showHide.slideIn('t');
//            }
//        },
//        ghost: function() {
//            if (showHide != null) {
//                showHide.ghost('t', { remove: true });
//                //                showHide.hide();
//                showHide = null;
//            }
//        },
        init: function() {
            if (!msgCt) {
                msgCt = Ext.DomHelper.insertFirst(document.body, { id: 'msg-div' }, true);
            }
            msgCt.alignTo(document, 't-t');
        }
    };
} ();

doInit = function() {
//    Ext.pp.init();
//    Ext.cart.init();
//    Ext.refreshCart.init();
}
Ext.onReady(function() {
//    window.setTimeout(doInit, 200);
//    doInit();
    ExtInitialised = true;
});

String.prototype.trim = function()
{return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""));};

String.prototype.endsWith = function(str)
{return (this.match(str+"$")==str);};

String.prototype.startsWith = function(str)
{return (this.match("^"+str)==str);};