//3.3.1 - RLW only - bypass attribute spec/adjustments
function qtyAddToCart(id, qty, unitPrice) {
    setCartCookie(id, qty, unitPrice);
    setTotalCartItems();
    toggleQuickButtons(id);
    toggleQtyDisabled(id);
}
function rlwAddToCart(id, qty, unitPrice) {    
    setCartCookie(id, qty, unitPrice);
    setTotalCartItems();
    submitMiniCart();
}
//3.3.1 Quick add from list - single quantites only
function quickAddToCart(id, unitPrice) {
    setCartCookie(id, 1, unitPrice);
    setTotalCartItems();
    toggleQuickButtons(id);
}
function quickRemoveFromCart(id) {
    setCartCookie(id, 0, 0);
    setTotalCartItems();
    toggleQuickButtons(id);
    toggleQtyDisabled(id);
    showRefreshBtn(true);
}
function showRefreshBtn(bShow) {
    var btn = document.getElementById("refreshBtn");
    if (typeof (btn) != "undefined")        
        btn.className = bShow ? "enabled" : "disabled";    
}
function toggleQuickButtons(id) {
    var add = document.getElementById("quickAdd_" + id);
    var rem = document.getElementById("quickRemove_" + id);
    if (add) {
        if (add.style.display == "inline") {
            add.style.display = "none";
            if (rem)
                rem.style.display = "inline";
        }
        else {
            add.style.display = "inline";
            if (rem)
                rem.style.display = "none";
        }
    }
}
function toggleQtyDisabled(id) {
    var pQty = document.forms[0]["qty" + id];
    if (pQty) {
        pQty.disabled = !pQty.disabled;

        if (!pQty.disabled)
            pQty.value = "1";
    }
}
function setUpdateTotalVisible() {
    var update = document.getElementById("updateTotal");
    if (update && typeof (update) != "undefined") {
        update.style.display = "inline";
    }
}
//3.3.1 end

// cookies
function Cookie(document, name, hours, path, domain, secure) {
    this.$document = document;
    this.$name = name;
    if (hours) this.$expiration = new Date((new Date()).getTime() + hours * 3600000);
    else this.$expiration = null;
    if (path) this.$path = path; else this.$path = null;
    if (domain) this.$domain = domain; else this.$domain = null;
    if (secure) this.$secure = true; else this.$secure = false;
}
Cookie.prototype.store = function() {
    var cookieval = "";
    for (var prop in this) {
        if (prop.charAt(0) == '$' || ((typeof this[prop]) == 'function'))
            continue;
        if (cookieval != "")
            cookieval += '&';
        //		cookieval += prop + ':' + escape(this[prop]);
        cookieval += prop + ':' + encodeURI(this[prop]);
    }

    var cookie = this.$name + '=' + cookieval;

    if (this.$expiration) cookie += '; expires=' + this.$expiration.toGMTString();
    if (this.$path) cookie += '; path=' + this.$path;
    if (this.$domain) cookie += '; domain=' + this.$domain;
    if (this.$secure) cookie += '; secure';

    this.$document.cookie = cookie;
}
Cookie.prototype.load = function() {
    var allcookies = this.$document.cookie;
    if (allcookies == "")
        return false;

    var start = allcookies.indexOf(this.$name + '=');
    if (start == -1)
        return false;

    start += this.$name.length + 1;

    var end = allcookies.indexOf(';', start);
    if (end == -1)
        end = allcookies.length;

    var cookieval = allcookies.substring(start, end);

    var a = cookieval.split('&');
    for (var i = 0; i < a.length; i++)
        a[i] = a[i].split(':');

    for (var i = 0; i < a.length; i++)
        this[a[i][0]] = decodeURI(a[i][1]);
    //		this[a[i][0]] = unescape(a[i][1]);

    return true;
}
Cookie.prototype.remove = function() {
    var cookie;
    cookie = this.$name + '=';

    if (this.$path)
        cookie += this.$path;
    if (this.$domain)
        cookie += '; domain=' + this.$domain;

    cookie += '; expires=Fri, 02-Jan-1970 00:00:00 GMT';

    this.$document.cookie = cookie;
}
Cookie.prototype.toString = function() {
    return this.$document.cookie;
}
function isCookiesEnabled() {
    var cookie = new Cookie(document, "test");
    cookie.test = "test";
    cookie.store();
    if (cookie.load()) {
        cookie.remove();
        return true;
    }
    return false;
}
//Cookies end
function updateTotal() {    //3.3.0
}
function setAttributes() {
    //Set selected vals from cart and/or from query string
    var attVal = getArgs()["AttDetID"];
    if (attVal) {
        for (var i = 0; i < groups.length(); i++) {
            var selID = groups.groups[i].selID;
            var ddl = document.forms[0][selID];
            if (ddl) {
                for (var j = 0; j < ddl.options.length; j++) {
                    if (ddl.options[j].value == attVal) {
                        ddl.selectedIndex = j;
                        onSelChange();
                        return;
                    }
                }
            }
        }
    }
}
function roundPrice(p) {
    var pound = String.fromCharCode(163);
    var price = pound + (new Number(p)).toFixed(2);
    return price;
}
function CookieItem(id, qty, price) {
    this.getValue = function() {
        return this.cartID + "_" + this.qty + "_" + this.price;
    }

    var p = price;
    var i = 0;
    while (isNaN(parseInt(p)) && p.length)
        p = p.substr(++i);

    if (isNaN(p)) {
        alert("An unexpected error occurred");
        return;
    }

    this.cartID = id;
    this.qty = qty;
    this.price = p;
}
function Cart(cookieName, duration) {
    this.toString = function() {
        var str = "";
        var count = 0;
        for (var i = 0; i < this.cookieItems.length; i++) {
            if (this.cookieItems[i].qty > 0) {
                if (count++ > 0)
                    str += "*";

                str += this.cookieItems[i].getValue();
            }
        }
        return str;
    }
    this.getItemIndex = function(cartID) {
        if (this.cookieItems.length)
            for (var i = 0; i < this.cookieItems.length; i++)
            if (this.cookieItems[i].cartID == cartID)
            return i;

        return -1;
    }
    this.addItem = function(cookieItem) {
        var nIndex = this.getItemIndex(cookieItem.cartID);
        if (nIndex == -1)
            this.cookieItems.push(cookieItem);

        else
            this.cookieItems[nIndex] = cookieItem;
    }
    this.removeItem = function(cartID) {
        var nIndex = this.getItemIndex(cartID);
        if (nIndex != -1)
            this.cookieItems[nIndex].qty = 0;
    }
    //3.0.10
    this.removeAll = function() {
        for (var i = 0; i < this.cookieItems.length; i++)
            this.cookieItems[i].qty = 0;

        this.remove();
    }
    //end 3.0.10
    this.count = function() {
        var nCount = 0;
        for (var i = 0; i < this.cookieItems.length; i++)
            if (this.cookieItems[i].qty > 0)
            ++nCount;

        return nCount;
    }
    this.load = function() {
        //this.cookie = new Cookie(document, "cart");
        this.cookie = new Cookie(document, this.cookieName, this.duration);
        //this.cookie = new Cookie(document, "cart", null, "/");      //3.3.1
        if (this.cookie.load()) {
            this.init();    //3.3.1 Sep 09

            //            var items = this.cookie[this.cookieName].split("*");
            //            for (var i = 0; i < items.length; i++) {
            //                var vals = items[i].split("_");
            //                this.addItem(new CookieItem(vals[0], vals[1], vals[2]));
            //            }
        }
    }
    this.save = function() {
        var val = this.toString();
        if (val.length)         //3.3.0
            this.reset(val);    //3.3.0         
    }
    this.remove = function() {
        this.cookie.remove();
    }
    //3.3.0
    this.reset = function(val) {
        //      this.cookie["cart"] = val;
        this.cookie[this.cookieName] = val;
        this.init();
        this.cookie.store();
    }
    //Aug 07
    this.isEmpty = function() {
        return this.count() == 0;
    }
    //3.3.1 Sep 09
    this.init = function() {
        var items = this.cookie[this.cookieName].split("*");
        for (var i = 0; i < items.length; i++) {
            var vals = items[i].split("_");
            this.addItem(new CookieItem(vals[0], vals[1], vals[2]));
        }
    }
    this.cookieName = cookieName ? cookieName : "cart";
    this.duration = duration ? duration : 0;
    this.cookieItems = new Array();
    this.cookie = null;
    this.load();
}
function Group(selID, name) {
    this.selID = selID;
    this.name = name;
    this.getValue = function() {
        return document.forms[0][this.selID].value;
    }
}
function Groups() {
    this.add = function(selID, name) {
        this.groups.push(new Group(selID, name));
    }
    this.getGrpID = function(index) {
        var selID = this.groups[index].selID;
        while (isNaN(parseInt(selID)) && selID.length)
            selID = selID.substr(1);

        return parseInt(selID);
    }
    this.getGrpName = function(index) {
        return this.groups[index].name;
    }
    this.getSelID = function(index) {
        return this.groups[index].getValue();
    }
    this.getSelText = function(index) {
        var sel = this.groups[index].selID;
        sel = document.forms[0][sel];
        var selIndex = sel.selectedIndex;
        return sel.options[selIndex].text;
    }
    this.verify = function() {
        for (var i = 0; i < this.groups.length; i++) {
            if (this.groups[i].getValue() == -1) {
                alert("Please select a value for all atributes [" + this.groups[i].name + "]");
                return false;
            }
        }
        return true;
    }
    this.getPriceModifier = function(details) {
        var pMod = 0;
        for (var i = 0; i < this.groups.length; i++) {
            var detID = this.groups[i].getValue();
            if (detID != -1) {
                if (isPPModel)      //3.3.1
                    pMod = Math.max(pMod, details.getPriceModifier(detID));
                else
                    pMod += details.getPriceModifier(detID);
            }
        }
        return pMod;
    }
    this.getValue = function() {
        var sel = "";
        for (var i = 0; i < this.groups.length; i++)
            sel += "-" + this.getSelID(i);

        return sel;
    }
    this.toString = function() {
        var sel = "";
        for (var i = 0; i < this.groups.length; i++) {
            var grpName = this.getGrpName(i);
            var selText = this.getSelText(i);

            if (sel.length)
                sel += "\n";

            sel += grpName + " : " + selText;
        }
        return sel;
    }
    this.length = function() {
        return this.groups.length;
    }
    this.groups = new Array();
}
function Detail(grpID, detID, dText, pMod) {
    this.grpID = grpID;
    this.detID = detID;
    this.detText = dText;
    this.pMod = pMod;
}
function Details() {
    this.add = function(grpID, detID, dText, pMod) {
        this.details.push(new Detail(grpID, detID, dText, pMod));
    }
    this.getPriceModifier = function(detID) {
        for (var i = 0; i < this.details.length; i++)
            if (this.details[i].detID == detID)
            return this.details[i].pMod;

        return 0;
    }
    this.details = new Array();
}
function CartItem() {
    this.getUnitPrice = function() {
        var p = this.price;
        var i = 0;
        while (isNaN(parseInt(p)) && p.length)
            p = p.substr(++i);

        return p / this.qty;
    }
    this.toString = function() {
        var tStr = this.serialNo + " : " + this.prodName;
        tStr += "\n------------------------------------------------------------------------------------\n";

        if (this.qty > 1)
            tStr += "These items have been added to your shopping cart";

        else
            tStr += "This item has been added to your shopping cart";

        /*
        if (this.attribStr.length)
        tStr += "\n";
        tStr += "\n" + this.attribStr;
        if (this.attribStr.length)
        tStr += "\n";
        */
        tStr += "\nQuantity : " + this.qty;
        tStr += "\nTotal charge : " + this.price;
        tStr += "\n------------------------------------------------------------------------------------";
        tStr += "\nClick on 'Shopping cart' in to review the details.";
        return tStr;
    }

    this.toFavString = function() {
        var tStr = this.serialNo + " : " + this.prodName + " " + this.price;
        tStr += "\n------------------------------------------------------------";

        if (this.qty > 1)
            tStr += "\nThese items have been added to your favourites";

        else
            tStr += "\nThis item has been added to your favourites";
        /*			
        if(this.attribStr.length)
        tStr += "\n";
        tStr += "\n" + this.attribStr;
        if(this.attribStr.length)
        tStr += "\n";
        */
        //		tStr += "\nQuantity : " + this.qty;
        //		tStr += "\nTotal charge : " + this.price;
        tStr += "\n------------------------------------------------------------";
        tStr += "\nClick on \"my watches\"  to review your saved items";
        return tStr;
    }

    this.qty = document.forms[0]["qty"].value;
    this.prodID = document.forms[0]["ProdID"].value; ;
    this.prodName = document.forms[0]["ProdName"].value;
    this.serialNo = document.forms[0]["ProdSerialNo"].value;
    this.price = document.forms[0]["Price"].value;
    if (document.forms[0]["DiscountedPrice"] && document.forms[0]["DiscountedPrice"].value)
        this.price = document.forms[0]["DiscountedPrice"].value;

    this.attribStr = groups.toString();
    this.attribVal = groups.getValue();
    this.itemID = this.prodID + this.attribVal;
    this.unitPrice = this.getUnitPrice();
}
function addToCart() {
    if (!verifyCookies() || !(checkQty() && groups.verify()))
        return;

    var item = new CartItem();
//    alert(item.toString());           //Removed for Condor only Dec 09

    setCartCookie(item.itemID, item.qty, item.unitPrice);
    setTotalCartItems();

    submitMiniCart();   //3.3.0
}
function setCartCookie(itemID, itemQty, itemPrice) {
    if (itemQty == 0)
        cart.removeItem(itemID);

    else {
        var cookieItem = new CookieItem(itemID, itemQty, itemPrice);
        cart.addItem(cookieItem);
    }

    if (cart.count() > 0)
        cart.save();

    else
        cart.remove();
}
function onSelChange() {
    setTotalPrice();
}
function getQty() {
    var qty = document.forms[0]["qty"].value;
    return isNaN(qty) ? 0 : qty;
}
//3.3.13
function checkMMQty(qty) {
    var multiQty = getMultiQty();
    var minimQty = getMinimQty();
    if (qty.value < minimQty) {
        alert("The minimum quantity for this item is " + minimQty);
        qty.value = getLastQty();
        qty.focus();
        qty.select();
        return false;
    }
    if (qty.value % multiQty > 0) {
        alert("This item is supllied in mutliples of " + multiQty + " only");
        qty.value = getLastQty();
        qty.focus();
        qty.select();
        return false;
    }
    return true;
}
function getMultiQty() {
    return typeof (multipleQuantity) == "undefined" ? 1 : multipleQuantity;
}
function getMinimQty() {
    return typeof (minimumQuantity) == "undefined" ? getMultiQty() : minimumQuantity;
}
function getLastQty() {
    var minimQty = getMinimQty();
    if (lastQty && lastQty >= minimQty)
       return lastQty;    
    return minimQty;
}
//3.3.1
function checkPQty(pQty) {
    var qty = document.forms[0][pQty];
    if (isNaN(qty.value) || parseInt(qty.value) != qty.value) //3.0
    {
        alert("Incorrect quantity entered");        
        qty.focus();
        qty.select();
        return false;
    }
    //3.3.14
    //return checkMMQty(qty);
    return true;
}
//3.3.1 end
function checkQty() {
    var qty = document.forms[0]["qty"];
    if (isNaN(qty.value) || parseInt(qty.value) != qty.value) //3.0
    {
        alert("Incorrect quantity entered");
        qty.focus();
        qty.select();
        return false;
    }
    //3.3.14
    //return checkMMQty(qty);
    return true;
}
function onQtyChange() {
    checkQty();
    setTotalPrice();
}
function setDiscountedPrice(listPrice) {
    if (document.forms[0]["DiscountPCent"]) {
        var disc = document.forms[0]["DiscountPCent"].value;
        if (disc && disc > 0) {
            document.forms[0]["Price"].className = "listPrice";
            document.forms[0]["DiscountedPrice"].style.display = "inline";
            var discountedPrice = listPrice * (1 - disc / 100);
            document.forms[0]["DiscountedPrice"].value = roundPrice(discountedPrice);
        }
    }
}
function setTotalCartItems() {
    var count = cart.count();
    if (document.forms[0]["cartSummary"]) {
        var text = "...";
        if (count == 1)
            text = count + " item";
        if (count > 1)
            text = count + " items";

        document.forms[0]["cartSummary"].value = text;
    }
    showRefreshBtn(count > 0);    
}
function getBulkQtyPrice(price) {
    var qty = getQty();
    if (volQuant && volQuant.length) {
        var nIndex = -1;
        for (var i = 0; i < volQuant.length; i++)
            if (qty >= volQuant[i])
            nIndex = i;

        if (nIndex != -1)
            price += volPrice[nIndex];
    }

    return price * qty;
}
function setTotalPrice() {
    //3.3.1
    var price;
    if (isPPModel)
        price = Math.max(basePrice, groups.getPriceModifier(details));
    else
        price = (basePrice + groups.getPriceModifier(details)); 	//2.4.5
    //3.3.1 end
    price = getBulkQtyPrice(price); 								//2.4.5
    document.forms[0]["Price"].value = roundPrice(price);
    setDiscountedPrice(price);
    setVAT(price);                                                  //3.0.6
}
var isPPModel = null;   //3.1.1
//3.0.6
var VAT_NOT_APPLICABLE = 0;
var VAT_INCLUDED = 1;
var VAT_EXCLUDED = 2;
function roundUp(n, numPlaces) {
    var num = Math.pow(10, numPlaces);
    return parseInt(n * num + 0.999999) / num;
}
function setVAT(price) {
    if (vatMethod == VAT_NOT_APPLICABLE)
        return;

    var vat = vatRate * price / 100;
    if (vatMethod == VAT_INCLUDED)
        vat = price * vatRate / (100 + vatRate);

    if (!setDiscountedVAT(vat)) {
        vat = roundUp(vat, 2);
        document.forms[0]["VATAmount"].value = roundPrice(vat);
    }
}
function setDiscountedVAT(vat) {
    if (document.forms[0]["DiscountPCent"]) {
        var disc = document.forms[0]["DiscountPCent"].value;
        if (disc && disc > 0) {
            var discountedVAT = vat * (1 - disc / 100);
            discountedVAT = roundUp(discountedVAT, 2);
            document.forms[0]["VATAmount"].value = roundPrice(discountedVAT);
            return true;
        }
    }
    return false;
}
//3.0.6 end
function registerDetail(grpID, detID, text, pMod) {
    details.add(grpID, detID, text, pMod);
}
function registerGroup(selID, name) {
    groups.add(selID, name);
}
//3.3.0
function refresh() {
    var path = location.pathname.toLowerCase();
    if (path.indexOf("cart.aspx") == -1) {
        if (typeof (submitMiniCart) != null) {
            submitMiniCart();
            return;
        }
    }

    location.href = "Cart.aspx";
}
function onCartQuantityChanged(field, cartID, itemPrice) {

    //itemPrice is the unit price discounted as appropriate
    var qty = field.value;

    if (isNaN(qty) || qty.indexOf(".") != -1) {
        alert("Error in the specified quantity [must be numeric]");
        //3.1.13
        //field.value = lastQty;
        field.value = getLastQty();
        //3.1.13 end
        return;
    }
    //3.1.14
    //if (!checkMMQty(field)) {
    //    field.value = getLastQty();        
    //    return;
    //}

    setCartCookie(cartID, qty, itemPrice);
    setTotalCartItems();    //3.3.1

    //location.href = "Cart.aspx";  //3.3.0
    //refresh();  //3.3.1 - removed
}
//2.4.8
function removeCartItem(cartID) {
    setCartCookie(cartID, 0, 0);
    //    location.href = "Cart.aspx";  //3.3.0   
    refresh();  //3.3.0
}
function onCartQuantityFocus(field) {
    lastQty = field.value;
    showRefreshBtn(true);
}
//3.1.13
function onQtyFocus(field) {
    lastQty = field.value;
}
function recalculate() {
}
function verifyCookies() {
    var tmpcookie = new Date();
    var chkcookie = (tmpcookie.getTime() + '');
    document.cookie = "chkcookie=" + chkcookie + "; path=/";
    if (document.cookie.indexOf(chkcookie, 0) == -1) {
        var msg = "Cookies are not enabled....\n\n";
        msg += "This web site uses cookies to track your shopping cart and manage your shopping experience.\n";
        msg += "Please ensure that they are enabled and/or that your security settings are set to 'Medium'.\n\n";
        if (navigator.userAgent.indexOf("MSIE") != -1)
            msg += "(Internet Explorer > Tools > Internet Options > Security > Custom Level > Medium)";

        alert(msg);
        return false;
    }

    return true;
}
//Aug 07
function goCart(url) {
    if (cart.isEmpty())
        alert("Your shopping cart is empty")

    else
        location.href = url;
}

//Aug 07 ends
var cart = new Cart("cart", 0);     //Cart
var favs = new Cart("favs", 2160);  //Favourites
var groups = new Groups(); 		    //Attribute groups
var details = new Details(); 	    //Attribute details
var basePrice = null;
var lastQty = null;
var volQuant = null;                //3.0
var volPrice = null;                //3.0

//3.0.10 - empty the cart on complete
if (location.pathname.toLowerCase().indexOf("/completey") != -1)
    cart.removeAll();

//3.0.13    
function doSignOut(url) {
    if (!cart.isEmpty())
        if (!confirm("Please confirm you want to sign out and empty the contents of you shopping cart"))
        return;

    location.href = url;
}
if (location.pathname.toLowerCase().indexOf("/signout.aspx") != -1) {
    if (!cart.isEmpty()) {
        cart.removeAll();
        location.reload();
    }
}
// Favourite funtions
function FavItem() {
    this.toString = function() {
        var tStr = this.serialNo + " : " + this.prodName + " " + this.price;
        tStr += "\n------------------------------------------------------------";

        if (this.qty > 1)
            tStr += "\nThese items have been added to your favourites";

        else
            tStr += "\nThis item has been added to your favourites";
        /*			
        if(this.attribStr.length)
        tStr += "\n";
        tStr += "\n" + this.attribStr;
        if(this.attribStr.length)
        tStr += "\n";
        */
        //		tStr += "\nQuantity : " + this.qty;
        //		tStr += "\nTotal charge : " + this.price;
        tStr += "\n------------------------------------------------------------";
        tStr += "\nClick on \"my watches\"  to review your saved items";
        return tStr;
    }

    this.prodID = document.forms[0]["prodID"].value; ;
    this.serialNo = document.forms[0]["prodSerialNo"].value;
    this.prodName = document.forms[0]["prodName"].value;
    this.price = document.forms[0]["prodPrice"].value;

    this.itemID = this.prodID;
}
function addToFavs() {
    if (!verifyCookies())
        return;

    var item = new FavItem();
    alert(item.toString());

    setFavsCookie(item.itemID, '1', '0');
}
function removeFromFavs(cartID) {
    if (confirm("Please confirm that you want to remove this item")) {
        setFavsCookie(cartID, 0, 0);
        location.href = location.href;
    }
}
function removeAllFavs() {
    if (favs.count() > 0 && confirm("Please confirm that you want to remove all saved items")) {
        favs.remove();
        location.href = location.href;
    }
}
function setFavsCookie(itemID, itemQty, itemPrice) {
    if (itemQty == 0)
        favs.removeItem(itemID);

    else {
        var cookieItem = new CookieItem(itemID, itemQty, itemPrice);
        favs.addItem(cookieItem);
    }

    if (favs.count() > 0)
        favs.save();

    else
        favs.remove();
}
