/* eibJS version 1 - generated on 20.3.2008 */

/* MiniBasket
------------------------------*/
var MiniBasket = {
	ajax : new Ajax(),
    update : function(e,args) {
        this.ajax.set(e,args,{cache: false});

        this.ajax.complete = function() {
            //update minibasket id
            var  basketnavinfo = document.getElementById("basket-nav-info");
            basketnavinfo.innerHTML = this.response;
        };
        this.ajax.get();                     
         
    },
    append : function(e, args) {
        if( typeof e == "string" )  e = document.getElementById(e);
        var ttl = document.getElementById("h-mb-total");
        if( !e || !args || !args.products || !ttl )
            return false;
        var dts = e.getElementsByTagName("dt") || [];
        
        for( var i = 0; i < args.products.length; i++ ) {
            var v = VariantData.getVariantData(args.products[i].vid);
            var dt = null;
            var dd = null;
            var el = null;
            var url = '/assets/en/catalogue/xxsmall/' + args.products[i].pid + ((args.products[i].colourcode)?args.products[i].colourcode:'') + '.jpg';

            for( k = 0; k < dts.length; k++ ) {
                var code = dts[k].getElementsByTagName("span") || [];
                for( j = 0; j < code.length; j++ ) {
                    if( code[j].className == "product-info" && code[j].innerHTML == v.code ) {
                        dd = dt = dts[k];
                        while( dd = dd.nextSibling ) {  // find the associated <dd>
                            if( dd != null && (dd.tagName || "").toLowerCase() == "dd" )
                                break;
                        }
                        break;
                    }
                }
            }

            if( dt == null ) {
                // ..if we don't already have the items in the basket,
                // we want to add the new entry (to the end of the list)..
                if( v.price.toFixed )   v.price = v.price.toFixed(2);
                e.insertBefore(dt = document.createElement("dt"), ttl);
                dt.style.background = "transparent url(" + url + ") no-repeat top left";
                dt.appendChild( el = document.createElement("a") );
                el.href = args.products[i].returnurl;
                el.innerHTML = "<span>" + (args.products[i].qty == 1?"":(args.products[i].qty + "&nbsp;x&nbsp;")) + "</span>" + args.products[i].pname;
                
                dt.appendChild( el = document.createElement("br") );
                
                dt.appendChild( el = document.createElement("span") );
                el.className = "product-info";
                if( v.price.toFixed )   v.price = v.price.toFixed(2);
                el.innerHTML = Product.getUnsafeId(args.products[i].vid);

                el = args.products[i].qty * v.price;
                e.insertBefore( dd = document.createElement("dd"), ttl );
                dd.innerHTML = '&pound;' + ((el.toFixed)?el.toFixed(2):el.toString());
            } else {
                // ..otherwise, we have an existing entry so we need to
                // reuse that; increase quantity and price..
                var n = 1;
                el = dt.getElementsByTagName("a") || [];
                if( el.length != 0 && (el = el[0]) ) {
                    el = el.getElementsByTagName("span");
                    if( el != null && (el = el[0]) ) {
                        var m = el.innerHTML.match(/^\d+/);
                        n = parseInt(m?m[0]:"1") + args.products[i].qty;
                        el.innerHTML = n + "&nbsp;x&nbsp;";
                    }
                }
                n *= v.price;
                if( dd )    dd.innerHTML = '&pound;' + ((n.toFixed)?n.toFixed(2):n.toString());
            }
        }
        
        // ..update the total for all items in the basket..
        var total = document.getElementById("t-mb-total");
        if( args.total.toFixed )    args.total = args.total.toFixed(2);
        if( total ) total.innerHTML = '&pound;' + args.total;
        return false;
    }
};

/* Basket
------------------------------*/
var Basket = {
    ajax: new Ajax(),
    add: function(e, args) {
        //this.ajax = new Ajax();
        this.clear();
        var qty = 1;
        //calling base url
        var url = e;

        if (args.qty != null) {
            if (!Validation.isNumeric(args.qty)) {
                qty = document.getElementById(args.qty).value;
            }
            else {
                qty = args.qty;
            }
        }

        args.qty = qty;

        //get the selected linked item
        var selectedLinkItem = Product.variantData.selectedLinkedStyle;
        //Add the shipped product id and shipped variant id to the query string only if the linked style exists
        if (selectedLinkItem) {
            args.Spid = selectedLinkItem.parent;
            args.Svid = selectedLinkItem.code;
        }

        if (args.vid == null) {
            var vid = document.getElementById('add-basket-sizes');
            if (vid && vid.value == "null") {
                if (vid = document.getElementById('selection-warning')) vid.style.display = 'block';
                if (vid = document.getElementById('add-basket-size')) vid.style.border = 'dashed 1px #b13750';
                return false;
            } else if (vid && vid.value != "null")
                args.vid = vid.value;
            if (vid = document.getElementById('add-basket-size')) vid.style.border = 'none';
            if (vid = document.getElementById('selection-warning')) vid.style.display = 'none';
        }

        this.ajax.set(e, args);
        // ..problems with caching - explicitly disable it; otherwise
        // it looks like the product has been added but hasn't..
        this.ajax.cache = this.ajax.cached = false;

        this.ajax.complete = function() {
            if (Config.debug) {
                var t = document.createTextNode(this.req.responseText);
                this.output.appendChild(t);
            }

            // About to redirect so freeze page
            var submit = document.getElementById("add-to-basket");
            if (submit != null) {
                submit.src = submit.src.replace("-o.gif", ".gif");
                submit.disabled = false;
            }

            // Go to basket
            var json = this.getJson();

            if (json.products && json.products[0].addToBasket) {
                if (typeof (Omniture) != "undefined") {
                    Omniture.basketAdd(json.products);
                }
                //Core.Url.redirect(MiniBasket.basketURL);
                var p = document.getElementById("add-basket-success");

                if (!p) {
                    p = document.createElement("p");
                }

                if (ProductData != null) {
                    if (json.products[0].vid != null) {
                        var variantData = VariantData.getVariantData(json.products[0].vid);

                        if (variantData) {
                            p.innerHTML = variantData.addedmessage;
                        }
                    }
                    else {
                        p.innerHTML = ProductData.p.addedmessage;
                    }
                }
                else {
                    p.innerHTML = Config.Access.addToBasketDefault;
                }

                if (submit != null && p.id == "") {
                    p.id = "add-basket-success";
                    p.className = "add-basket-success";
                    //submit.parentNode.insertBefore(p, submit);
                    submit.parentNode.appendChild(p);
                    setTimeout("Basket.clear();", 5000);
                }

                // Update mini basket
                if ((p = document.getElementById("basket-nav-info")) && json.message)
                    p.innerHTML = json.message;

                MiniBasket.append('mini-basket-content', json);
            }
            else if (!json.addToBasket) {
                var p = document.getElementById("add-basket-error") || document.createElement("p");
                p.innerHTML = (json.products && json.products.length != 0) ? json.products[0].reason : "Insufficient Stock!";
                if (submit != null && p.id == "") {
                    //submit.disabled = true;
                    p.id = "add-basket-error";
                    p.className = "add-basket-error";
                    //submit.parentNode.insertBefore(p, submit);
                    submit.parentNode.appendChild(p);
                    setTimeout("Basket.clear();", 5000);
                }
            }
        }
        this.ajax.busy = function() {

            var submit = document.getElementById("add-to-basket");
            if (submit != null) {
                submit.src = submit.src.replace(".gif", "-o.gif");
                submit.disabled = true;
            }
        }
        this.ajax.get();
        return false;
    },
    keep: function(e, args) {
        //this.ajax = new Ajax();
        this.clear();

        var qty = 1;
        if (args.qty != null) {
            if (!Validation.isNumeric(args.qty)) {
                qty = document.getElementById(args.qty).value;
            }
            else {
                qty = args.qty;
            }
        }

        args.qty = qty;
        //calling base url 
        var url = e;

        if (args.vid == null) {
            var vid = document.getElementById('add-basket-sizes');
            if (vid && vid.value == "null") {
                if (vid = document.getElementById('selection-warning')) vid.style.display = 'block';
                if (vid = document.getElementById('add-basket-size')) vid.style.border = 'dashed 1px #b13750';
                return false;
            } else if (vid && vid.value != "null")
                args.vid = vid.value;
            if (vid = document.getElementById('add-basket-size')) vid.style.border = 'none';
            if (vid = document.getElementById('selection-warning')) vid.style.display = 'none';
        }
        this.ajax.set(e, args);

        this.ajax.complete = function() {
            if (Config.debug) {
                var t = document.createTextNode(this.req.responseText);
                this.output.appendChild(t);
            }

            // About to redirect so freeze page

            var submit = document.getElementById("add-to-basket");
            if (submit != null) {
                submit.src = submit.src.replace("-o.gif", ".gif");
                submit.disabled = false;
            }

            // Go to basket
            var json = this.getJson();

            if (json.products && json.products[0].addToBasket) {
                //Core.Url.redirect(MiniBasket.basketURL);
                var p = document.getElementById("add-basket-success");

                if (!p) {
                    p = document.createElement("p");
                }

                p.innerHTML = Config.Access.addToWishlist;

                if (submit != null && p.id == "") {
                    p.id = "add-basket-success";
                    p.className = "add-basket-success";
                    submit.parentNode.insertBefore(p, submit);
                    setTimeout("Basket.clear();", 5000);
                }
            }
            else if (!json.addToBasket) {
                var p = document.getElementById("add-basket-error");
                if (!p) p = document.createElement("p");

                p.id = "add-basket-error";
                p.className = "add-basket-error";
                p.innerHTML = json.products[0].reason;
                if (submit != null && p.id != "") {
                    //submit.disabled = true;
                    submit.parentNode.insertBefore(p, submit);
                    setTimeout("Basket.clear();", 5000);
                }
            }
        }
        this.ajax.busy = function() {

        }
        this.ajax.get();
        return false;
    },
    clear: function() {
        var error = document.getElementById("add-basket-error");
        if (error && error.parentNode) error.parentNode.removeChild(error);

        error = document.getElementById("add-basket-success");
        if (error && error.parentNode) error.parentNode.removeChild(error);
    },
    removeItem: function(item) {

    },
    updateItemQuantity: function(item, qty) {

    },
    update: function(e) {

        var basketQty = FormUtils.collect("basket");

        this.ajax.method = "POST";
        this.ajax.set(e, basketQty, "content");
        this.ajax.addParam("ajax", "true");
        this.ajax.addParam("cmd", "update");

        this.ajax.complete = function() {
            alert(this.req.responseText);
        }

        this.ajax.get();
    },

    onshippingupdate: function(data, context) {
        data = eval(data);
        var e = (data && data.shipment) ? document.getElementById('ShippingMethods-' + data.shipment) : null;
        if (e) {
            Core.Dom.emptyElement(e);
            for (var i = 0; i < data.methods.length; i++) e.options[i] = new Option(data.methods[i].name, data.methods[i].value, i === 0);
            Core.Dom.Event.raise(e, 'change');
        }
    },

    // ..on error, try reloading the actual page
    // instead; just in case we need some missing
    // contextual info..
    onshippingerror: function(err, context) {
        window.location.reload();
    }
};

var VariantData = {
    getVariantData : function(value) {
        return eval("ProductData.p" + value.replace("-", ""));
    }
};

var LinkedProductData = {
    getLinkedProductData: function(value) {
        return eval("selectedLinkedStyle.p" + value.replace("-", ""));
    }
};


/**
* @namespace Stats.Omniture
* 
* Do all the Omniture stats updates
*
* @requires	Stats.Omniture
*/

var Omniture = {
    basketAdd: function(products) {
        if (typeof s_account == "undefined") {
            return;
        }

        s = s_gi(s_account);
        if (typeof s == "undefined") {
            return;
        }

        var events = "";
        if (typeof products[0].scOpen !== "undefined" && products[0].scOpen.toLowerCase() !== "false") {
            s.linkTrackVars = "products,events,eVar1,eVar6";
            s.linkTrackEvents = "scAdd,scOpen";
            s.events = "scAdd,scOpen";
            events = "scAdd,scOpen";
        }
        else {
            s.linkTrackVars = "products,events,eVar1,eVar6";
            s.linkTrackEvents = "scAdd";
            s.events = "scAdd";
            events = "scAdd";
        }
        
        var i = 0;
        var productString = "";

        for (i = 0; i < products.length; i++) {
            productString += products[i].cid.replace(/'/g, "") + ";" + products[i].pid.replace(/'/g, "") + ";;;;evar1=" + products[i].cid.replace(/'/g, "") + "|evar6=" + products[i].vid.replace(/'/g, "") + "|events=" + events;
        }

        s.products = productString;
        s.tl(this, 'o', 'Add to Bag');
    },
    wishList: function() {
    s.events="event13";
    }   
    
};


/**
Function to handle the AJAX on the address control. 
*/
var Address = {
	_ajax: null, // Holds the private Ajax instance
	output: "address-console",
	init: function() {
		Ajax.History.trigger(Site.Address.history);
		this.Interface.init.call(this);
	},
	/**
	* Get a single Ajax instance - this will not handle multiple simultaneous requests, you will need to create multiple Ajax objects for that
	*/
	ajax: function() {
		if (!this._ajax) {
			this._ajax = new Ajax();
		}
		return this._ajax;
	},
	/**
	* Finds the address using an address finder functionality
	*
	* @param {object} e			The button that called this method
	* @param {string} url		URL to the page
	* @param {array} fields		Array of form elements to find e.g. house number, country, postcode
	*/
	findAddress: function(e, url, fields) {
		var ajax = this.ajax();
		ajax.set(url, {"ajax": "true","action": "find"}, {"method": Ajax.Method.Post, "canvas": this.output });
	
		var hno = document.getElementById(fields[0]).value;
		var pcode = document.getElementById(fields[1]).value;
		if(hno != "" )		    ajax.addParam("hno",hno, this.ajax.param);
        if(pcode != "") 	    ajax.addParam("pcode",pcode, this.ajax.param);
	
		ajax.busy = function() {
			var data = {"canvas": this.canvas.id, "response": this.canvas.innerHTML};
			Ajax.History.register(Ajax.History.encodeKey("findAddress"), data);
			Ajax.History.trigger(Address.history);
		};
		
		ajax.complete = function() {
			var data = {"canvas": this.canvas.id, "response": this.response};
			Ajax.History.register(Ajax.History.encodeKey("selectAddress"), data);
			Ajax.History.trigger(Address.history);
			Address.renderSelectAddress(data);
			//Site.ClearText.init("ctl00_cphContent_ucAddress_tbAddressName");
		};
		
		ajax.get();
		return false;
	},
	/**
	* Selects one address froma list of addresses returned by the address finder functionality
	*
	* @param {object} e			The button that called this method
	* @param {string} url		URL to the page
	* @param {string} address	Pipe separted address returned by address finder which is used to populate the text boxes.
	*/
	selectAddress: function(e, url, address) {   
	    var ajax = this.ajax();
		ajax.set(url, {"ajax": "true","action": "select"}, {"method": Ajax.Method.Post, "canvas": this.output});
		ajax.addParam("address",address , this.ajax.param);
		ajax.busy = function() {
			var data = {"canvas": this.canvas.id, "response": this.canvas.innerHTML};
			Ajax.History.register(Ajax.History.encodeKey("findAddress"), data);
			Ajax.History.trigger(Address.history);
		};
		ajax.complete = function() {
			var data = {"canvas": this.canvas.id, "response": this.response};
			Ajax.History.register(Ajax.History.encodeKey("selectAddress"), data);
			Ajax.History.trigger(Address.history);
			Address.renderSelectAddress(data);
			//Site.ClearText.init("ctl00_cphContent_ucAddress_tbAddressName");
		};
		ajax.get();
		return false;	    
	},
	/**
	* Loads the address edit form to enter the address manually
	*
	* @param {object} e			The button that called this method
	* @param {string} url		URL to the page
	*/
	enterAddress: function(e, url) {   
        var ajax = this.ajax();
	    ajax.set(url, {"ajax": "true","action": "enter"}, {"method": Ajax.Method.Post, "canvas": this.output });
	    ajax.busy = function() {
		    var data = {"canvas": this.canvas.id, "response": this.canvas.innerHTML};
		    Ajax.History.register(Ajax.History.encodeKey("findAddress"), data);
		    Ajax.History.trigger(Address.history);
	    };
	    ajax.complete = function() {
		    var data = {"canvas": this.canvas.id, "response": this.response};
		    Ajax.History.register(Ajax.History.encodeKey("selectAddress"), data);
		    Ajax.History.trigger(Address.history);
		    Address.renderSelectAddress(data);
		    //Site.ClearText.init("ctl00_cphContent_ucAddress_tbAddressName");
	    };
	    ajax.get();
	    return false;
	},
	renderFindAddress: function(data) {
		document.getElementById(data.canvas).innerHTML = data.response;	
		//Site.ClearText.init("ctl00_cphContent_ucAddress_tbAddressName");	
	},
	renderSelectAddress: function(data) {
		document.getElementById(data.canvas).innerHTML = data.response;		
		//Site.ClearText.init("ctl00_cphContent_ucAddress_tbAddressName");
	},
	history: function(key, value) {
		// Remove counter - any number
		switch (Ajax.History.decodeKey(key)) {
			case "findAddress":
				Address.renderFindAddress(value);
			break;
			case "selectAddress":
				Address.renderSelectAddress(value);
			break;
		}
	}
};



var Email = {
    add: function(e, t, f, l, m) {
        if( typeof e == "string" )  e = document.getElementById(e);
        if( !e )    return false;
        
        var tr = document.createElement("tr");
        var n = e.getElementsByTagName("tr").length + 1;
        if( n >= Config.MaxWishlistRecipients )
            return false;   // TODO: explanation of why!
        var td, usr;
        e.appendChild(tr);
        
        // 1. add the selection for title
        tr.appendChild( td = document.createElement("td") );
        tr.scope = "col";
        tr.className = tr.headers = "title";
        td.appendChild( usr = document.createElement("select") );
        usr.name = "u-title-" + n;
        e = document.getElementById("u-friends-button");
        e.value = n;
        
        e = document.getElementById("u-title-1");
        for( var i = 0; i < e.options.length; i++ ) {
            var o = new Option( e.options[i].text, e.options[i].value );
            if( t && t == o.value ) o.selected = true;
            usr.options[i] = o;
        }
        
        // 2. add the input for the friend's first name
        tr.appendChild( td = document.createElement("td") );
        tr.scope = "col";
        tr.className = tr.headers = "f-name";
        td.appendChild( usr = document.createElement("input") );
        usr.name = "u-forename-" + n;
        usr.type = "text";
        if( f ) usr.value = f.toString();
        // 3. add the input for the friend's last name
        tr.appendChild( td = document.createElement("td") );
        tr.scope = "col";
        tr.className = tr.headers = "l-name";
        td.appendChild( usr = document.createElement("input") );
        usr.name = "u-surname-" + n;
        usr.type = "text";
        if( l ) usr.value = l.toString();
        
        // 2. add the input for the friend's email address
        tr.appendChild( td = document.createElement("td") );
        tr.scope = "col";
        tr.className = tr.headers = "email-address";
        td.appendChild( usr = document.createElement("input") );
        usr.name = "u-email-" + n;
        usr.type = "text";
        if( m ) usr.value = m.toString();

        return false;
    }
};

/* Gift wrapping visibility
------------------------------*/
var GiftWrapping = {
    tablets: [],  // text boxes
    options: [],  // radio buttons
    init: function() {
        var e = document.getElementsByTagName("input") || [];
        
        // ..grab the text boxes and radio buttons representing the
        // gift wrapping options..
        for( var n = e.length - 1; n >= 0; n-- ) {
            if( e[n].type == "text" && /^[\w\d\-\$]*-message$/.test(e[n].name) ) {
                this.tablets.push(e[n]);
            } else if( e[n].type == "radio" && /^[\w\d\-\$]*-gift-wrap$/.test(e[n].name) ) {
                Core.Dom.Event.add(e[n], "click", GiftWrapping.toggle );
                if( e[n].checked == true )  Core.Dom.Event.raise(e[n], "click");
                this.options.push(e[n]);
            }
        }
    },
    toggle: function(e) {
        if( !e || !(e = (e.srcElement)?e.srcElement:e.target) )
            return;
        // ..find the associated text entry and/or the parent
        // elements of the list item and show as selected..
        var alt = e.name.replace(/-gift-wrap$/, "-message" );
        for( var n = 0; n < GiftWrapping.tablets.length; n++ ) {
            var t = GiftWrapping.tablets[n];
            if( t == null || t.name != alt )
                continue;
            
            var p = t.parentNode;
            if( p ) p.style.visibility = (e.value == 'true')?"visible":"hidden";
            while( (p = p.previousSibling) && p.nodeType != 1);
            if( p ) p.style.visibility = (e.value == 'true')?"visible":"hidden";
            break;
        }
        
        return;
    }
};


// init function to set event handler for paging control
var PagingControls = {
    init: function() {
        this.hide("product-filter-header");
        this.hide("product-filter-footer");
    },
    hide: function(e) {
        if( typeof e == "string" )  e = document.getElementById(e);
        if( !e )    return false;
        
        // ..knock out the buttons..
        var items = e.getElementsByTagName("input") || [];
        for( var i = 0; i < items.length; i++ ) {
            if( /(^|\s+)access-submit($|\s+)/.test(items[i].className) ) {
                items[i].style.display = "none";
            }
        }
        // ..now, assign the change events on any select elements
        // to that of the button following it..
        items = e.getElementsByTagName("select") || [];
        for( var i = 0; i < items.length; i++ ) {
            // ..find the button..
            var button = items[i];
            while( button != null && (button = button.nextSibling) ) {
                if( (button.tagName || "").toLowerCase() == "input" && (button.type || "").toLowerCase() == "submit" )
                    break;
            }
            if( button == null )    continue;
            this.assign(items[i], button);
        }
    },
    assign: function(s,b) {
        Core.Dom.Event.add( s, "change", function() { b.click(); } );
    }
};




/* Product
------------------------------*/
var Product = {
    ajax: new Ajax(),  // alternate image provision
    matrix: null, // Radio button container
    productCode: null, // The product code <p>
    productPrice: null, // The product price <p>
    totalPrice: null, // The total price <p>
    stockStatus: null, // The product stock <p>
    product: null, // The product that has the variants
    variant: null, // The list item that holds the radio button
    variantCodes: new Array(), // The list of variant Ids
    variantData: null, // The information for a specific variant	
    variantText: "##name##, in ##colour##", // Text to replace with variant values
    variantList: null, // The actual variant list
    variantDesc: null, // The element containing the variant description
    sizes: new Array(),
    selected: null, // The pre-selected variant ID data
    productSelection: null, // The selected product data from the details page global var
    email: null, // The email a friend link
    imagery: { // Holds all product imagery
        packShot: null, // The PackShot Url
        hero: null, // The main product image
        heroWidth: 275,
        heroHeight: 380,
        wardrobe: null,
        zoom: null
    },
    addBasket: { // Add to basket button stuff
        el: null,
        alt: null
    },
    stockMessages: {
        outOfStock: "Out of Stock"
    },
    init: function() {
        // Get matrix and the variant item containers
        this.product = document.getElementById("add-basket-colour");
        this.variants = this.product.getElementsByTagName("li");
        this.productCode = document.getElementById("product-code");
        this.productPrice = document.getElementById("product-price");
        this.stockStatus = document.getElementById("stock-message");
        this.variantDesc = document.getElementById("variant-desc");
        this.totalPrice = document.getElementById("total-price");

        // Get the add-to-basket button
        this.addBasket.el = document.getElementById("add-to-basket");
        if (this.addBasket.el) {
            this.addBasket.alt = this.addBasket.el.alt;
        }

        // Grab the global variable on the details page
        if (typeof ProductSelection != "undefined" && !this.selected) {
            this.productSelection = ProductSelection;
            this.selected = ProductData['p' + ProductSelection.oid];
        }

        // Exit if there are no variants
        if (this.variants.length < 1) {
            // Create the container tag
            var p = document.createElement("p");
            p.id = "void-variant";

            var colours = document.getElementById("add-basket-colour");
            Core.Dom.emptyElement(colours);
            colours.appendChild(p);

            this.updateBasketButton(false);
            return;
        }

        // Get the email a friend link..
        var ctrl = document.getElementById("tell-a-friend");
        if (ctrl && ctrl.firstChild.nodeName.toLowerCase() == "a") {
            this.ctrl = ctrl.firstChild;
        } else if (ctrl.nodeName.toLowerCase() == "a") {
            this.ctrl = ctrl;
        }
        // ..handle any changes to the size selection..
        if (ctrl = document.getElementById("add-basket-sizes")) {
            Core.Dom.Event.add(ctrl, 'change', function() {
                Product.setVariantOption(this);
                Product.stockCheck(this);
                var qty = document.getElementById("product-quantity");
                if (qty) Product.setTotalPrice(qty);
            });
        }
        // ..handle any changes to quantity selection..
        if (ctrl = document.getElementById("product-quantity")) {
            Core.Dom.Event.add(ctrl, 'change', function() {
                Product.setTotalPrice(this);
            });
        }

        Debug.p("Product count", this.variants.length);
        // Get product elements
        this.imagery.hero = document.getElementById("main-product-image");
        this.imagery.wardrobe = null; //document.getElementById("pic-wardrobe").firstChild;
        var zoom = this.imagery.zoom = document.getElementById("product-zoom").firstChild;
        var hero = this.imagery.hero;
        // Grab the PackShot Url from the details page global
        if (typeof (PackShot) != "undefined") {
            this.imagery.packShot = PackShot;
        }
        Core.Dom.Event.add(this.imagery.hero, 'load', function() { ProductZoom.active = false; if (ProductZoom.message) ProductZoom.message.style.visibility = 'hidden'; hero.parentNode.href = zoom.src = this.src.replace(/\/medium/, '/large'); });

        // Create the new list
        var list = this.variantList = document.createElement("ul");
        list.id = 'variant-matrix-list';

        // Replace the radio buttons
        for (var i = 0, c = this.variants.length, item; i < c; i++) {
            this.variantCount = i;
            if (this.variants[i].firstChild.nodeName.toLowerCase() == "input") {
                item = this.setItem(this.variants[i], i);
                if (item) {
                    list.appendChild(item);
                }
            }
        }

        // Hide the radio matrix list
        this.matrix = document.getElementById("variant-matrix");

        //matrix.style.display = "none";
        this.matrix.className = "access-node";
        // Replace the radio matrix with the new size list
        this.product.insertBefore(list, this.matrix.nextSibling);

        // Preselect after the replacements have been added to the page and if a variant has been preselected
        this.setSelection((this.selected) ? true : false, true);
    },

    setTotalPrice: function(e) {
        var span = this.totalPrice.getElementsByTagName("span") || [];
        if (span.length != 0 && (span = span[0])) {
            var variant = ProductData["p" + document.getElementById("add-basket-sizes").value];
            var price = (variant) ? variant.price : 0.00;
            price *= parseInt(e.value);
            span.innerHTML = "&pound;" + ((price.toFixed) ? price.toFixed(2) : price);
        }
    },

    setItem: function(variant, i) {
        Debug.w("Setting up new item variant");

        // Get the radio button
        var radio = variant.getElementsByTagName("input");

        // Exit if not there
        if (!radio) { return null; }

        // Set first instance
        radio = radio[0];
        // Collect the variant Ids to use for preselection
        this.variantCodes.push(radio.value);

        // Json array of variant data
        this.getVariantData(radio.value);

        // Set the preselected variant
        if (radio.checked) {
            this.selected = this.variantData;
        }

        // Use only unique colours
        if (this.sizes.contains(this.variantData.colourcode)) {
            // Exit if a colour is already used
            return null;
        } else {
            // Add the new colour
            this.sizes.push(this.variantData.colourcode);
        }

        // Create the item
        var item = document.createElement("li");
        // Create link for the swatch
        var link = document.createElement("a");
        link.id = "swatch-link-" + this.variantData.colourcode;
        link.className = "form-replacement";
        link.href = "#";
        link.title = this.variantText.replace("##name##", this.variantData.name).replace("##size##", this.variantData.size).replace("##colour##", this.variantData.colour);
        this.setVariantFunction(link, this.variantData, null, this.variantData.colourcode);

        // Create image for the swatch
        var img = document.createElement("img");
        img.id = "swatch-" + this.variantData.colourcode;
        img.alt = this.variantText.replace("##name##", this.variantData.name).replace("##colour##", this.variantData.colour);
        img.src = Config.absoluteHttpPath + "/assets/en/catalogue/swatch/" + this.productSelection.pid + this.cleanColourCode(this.variantData.colourcode) + ".jpg";
        img.onerror = function() {
            this.src = Config.absoluteHttpPath + "/assets/en/catalogue/missing/swatch.gif";
        };

        // Add hidden class and add the swatch to the variant item
        link.appendChild(img);

        //create span for colour name link
        var span = document.createElement("span");
        span.id = "variant-spanid";
        //create content inside the span 
        var linktext = document.createTextNode(this.variantData.colour);
        span.appendChild(linktext);
        //make the span child of the <a> link
        link.appendChild(span);
        item.appendChild(link);
        // Return the newly made LI
        return item;
    },

    // Set up the preselected variant
    setSelection: function(preSelect, init) {
        // Set up the default selection based on the first variant
        var colourCode = this.sizes[0];
        var variantCode = this.variantCodes[0];

        // If one is prselected, replace the default values
        if (this.selected) {
            variantCode = this.selected.code;
            colourCode = this.selected.colourcode;
        }

        // Trim the colour code to match the one used by the swatch image ID (NO LONGER REQUIRED?)
        // realColourCode = (colourCode.charAt(0) == "0") ? colourCode.substring(1) : colourCode;
        // Get the link
        var link = document.getElementById("swatch-link-" + colourCode);
        // Select the swatch
        var img = document.getElementById("swatch-" + colourCode);
        if (img) img.className = "selected";
        // Set up the variant if this is called during the init
        if (init) {
            this.setVariant(link, this.selected, variantCode, colourCode, preSelect);
            var el = document.getElementById('add-basket-sizes');
            this.setVariantOption(el);
        }
    },

    // Find the sizes for a particular colour
    evalVariantData: function(colour) {
        var cache = Ajax.Cache.get("variantcolour" + colour);
        if (!cache) {
            // Create a unique array of colours
            var variantInfo, size = new Array(), vid = new Array(), stock = new Array();

            // Add the default selection text
            size.push("Select a size");
            vid.push("null");
            stock.push("null");

            // Loop through the variants and create a size list based on a common colour
            for (var i in ProductData) {
                variantInfo = ProductData[i];
                if (variantInfo.colourcode == colour) {
                    size.push(variantInfo.size);
                    vid.push(variantInfo.code);

                    //Loop through the linked styles to fetch the most available stock
                    var linkedVariantInfo;
                    var selectedLinkedStyle;
                    if (typeof (LinkedProductCount) != "undefined") {
                        for (var j = 1; j <= LinkedProductCount; j++) {
                            for (var k in eval("LinkedProductData" + j)) {
                                linkedVariantInfo = eval("LinkedProductData" + j + "[k]");
                                if (linkedVariantInfo.sizecode == variantInfo.sizecode && linkedVariantInfo.colourcode == variantInfo.colourcode && linkedVariantInfo.stocklevel > variantInfo.stocklevel) {
                                    if (selectedLinkedStyle != null) {
                                        if (selectedLinkedStyle.stocklevel > variantInfo.stocklevel) {
                                            selectedLinkedStyle = linkedVariantInfo;
                                        }
                                    }
                                    else {
                                        if (linkedVariantInfo.stocklevel > variantInfo.stocklevel) {
                                            selectedLinkedStyle = linkedVariantInfo;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (selectedLinkedStyle) {
                        stock.push(selectedLinkedStyle.stock);
                        selectedLinkedStyle = null;
                    }
                    else {
                        stock.push(variantInfo.stock);
                    }
                }
            }

            cache = [size, vid, stock];
            Ajax.Cache.set("variantcolour" + colour, cache);
        }
        // Return an array of sizes and their vid
        return cache;
    },

    // Apply lexical variables correctly
    setVariantFunction: function(e, selected, variantCode, colourCode) {
        e.onclick = function() {
            Product.setVariant(this, selected, variantCode, colourCode, false);
            Product.setSelection(false);
            return false;
        };
    },

    // Set the radio button
    setVariantOption: function(e) {
        // Set it based on a drop-down value or a variant Id
        if (typeof (e) == "object") {
            variantCode = e.value;
        } else {
            variantCode = e;
        }
        Basket.clear();

        this.productCode.innerHTML = (variantCode == null || variantCode == "null") ? 'REF:&nbsp;' + ProductSelection.pid : Product.getUnsafeId(variantCode);
        this.setEmailVariant(e, variantCode == "null" ? null : variantCode);
        var selectedRadio = document.getElementById("product-" + variantCode);
        if (selectedRadio) selectedRadio.checked = true;
    },

    setEmailVariant: function(e, variantCode) {
        // Update the email a friend link
        if (this.email) {
            if (variantCode == null || variantCode == 'null') {
                this.email.href = Core.Url.removeParam('vid', this.email.href);
                return false;
            }
            var vid = Core.Url.qs('vid', this.email.href);
            if (vid && vid.length != 0) this.email.href = Core.Url.replaceParam("vid", variantCode, this.email.href);
            else this.email.href = Core.Url.addParam('vid', variantCode, this.email.href);
        }
        return false;
    },

    setVariant: function(e, selected, variantCode, colourCode, preSelect) {
        // Set the currently selected
        this.selected = selected;
        // Clean the selection
        this.clearProduct();
        // Set the selected swatch border
        e.firstChild.className = "selected";

        // Get the vid and size information from the data array
        var data = this.evalVariantData(colourCode);
        var size = data[0], vid = data[1], stock = data[2];
        var fieldset = document.getElementById("add-basket-size");
        var select = document.getElementById("add-basket-sizes");

        //Update product info
        if (selected) {
            var amount = (selected.price.toFixed) ? selected.price.toFixed(2) : selected.price.toString();
            this.productCode.innerHTML = (variantCode == null) ? ProductSelection.pid : selected.code;
            if (typeof selected.originalprice == "undefined") {
                this.productPrice.innerHTML = '&pound;' + amount.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"");
            }
            else {
                //put was now price on variant selection
                // :( implementation
                this.productPrice.innerHTML = '<span class="del was-price">Was <em>&pound;' + selected.originalprice.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"") + '</em></span><span class="ins now-price">Now <strong>&pound;' + amount.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"") + '</strong></span>';
            }
            this.variantDesc.innerHTML = selected.description;

            // Do a stock check	
            this.stockCheck();

            //Clear the selectedlinkedstyle if the master is changed
            //Take a backup of the selectedlinkedstyle
            if (this.variantData.selectedLinkedStyle != null) {
                this.variantData.tempSelectedLinkedStyle = this.variantData.selectedLinkedStyle;
            }
            this.variantData.selectedLinkedStyle = null;

            if (this.variantData.tempSelectedLinkedStyle != null) {
                if (this.variantData.tempSelectedLinkedStyle.master == selected.code) {
                    //put back the selected linked style if the previously selected master is selected again
                    this.variantData.selectedLinkedStyle = this.variantData.tempSelectedLinkedStyle;
                }
            }
        }

        // Reset the add-to-basket button before checking for single variant
        this.updateBasketButton(true);
        // If the size drop-down exists, replace it with the sizes associated with the colour
        if (select) {
            this.createSize(select, size, vid, stock, (preSelect) ? variantCode : null, colourCode);

            // Check to see if there in only one radio button (3 because of parent elements)
            //if (this.variants.length == 3) {
            // Json array of variant data
            this.getVariantData(this.matrix.getElementsByTagName("input")[0].value);
            // Check to see if the variant has one size, if it does hide the drop down
            if (this.hasSingleSize(this.variantData.size)) {
                // If the first drop down value is null, remove it and default to the first size
                if (select.options[0].value == "null") {
                    select.className = "single-variant";
                    select.removeChild(select.options[0]);
                    select.options[0].selected = true;
                }

                // Create text replace the drop down
                var variantNote = "One Size" + this.cleanStock(this.variantData.stock);
                var variantNoteWrap = document.getElementById("single-variant-status");
                if (variantNoteWrap) {
                    variantNoteWrap.innerHTML = variantNote;
                } else {
                    variantNoteWrap = document.createElement("span");
                    variantNoteWrap.id = "single-variant-status";
                    variantNoteWrap.innerHTML = variantNote;
                    select.parentNode.appendChild(variantNoteWrap);
                }
            }
            //}
            Core.Dom.Event.raise(select, "change");
        }

        // Set up the product imagery
        this.setImages(variantCode, colourCode);
        this.setEmailVariant(e, variantCode);
        // Stop link from working
        return false;
    },

    // Update the add-to-basket button
    updateBasketButton: function(enable) {
        if (this.addBasket.el) {
            if (enable) {
                // Show and enable the button
                this.addBasket.el.disabled = false;
                this.addBasket.el.style.cursor = "pointer";
                this.addBasket.el.alt = this.addBasket.alt;
                this.addBasket.el.style.filter = "alpha(opacity=100)";
                this.addBasket.el.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=100)";
                this.addBasket.el.style.opacity = "1.0";
            } else {
                // Hide and disable the button
                this.addBasket.el.disabled = true;
                this.addBasket.el.style.cursor = "default";
                this.addBasket.el.style.filter = "alpha(opacity=50)";
                this.addBasket.el.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=50)";
                this.addBasket.el.style.opacity = ".50";
                this.addBasket.el.alt = (this.variantData) ? this.variantData.stock : this.stockMessages.outOfStock;
            }
        }
    },

    // Remove illegal Json chars to eval data for product id
    cleanVariantValue: function(value) {
        return "p" + value.replace("-", "");
    },

    // Get the variable from the page and Json it
    getVariantData: function(value) {
        this.variantData = eval("ProductData." + this.cleanVariantValue(value));
    },

    // Create the drop down options for the selected size range
    createSize: function(e, name, value, stock, selected, colourCode) {
        // Don't loop with the default text check - do it once only
        var i = 0;
        var z = null;

        if (e && e.selectedIndex != -1) {
            var v = e.options[e.selectedIndex].text || "";
            var m = v.match(/^[\w]*/i);
            if (m && m.length != 0) z = m[0];
        }

        Core.Dom.emptyElement(e);

        // Check if the variant is alone, if it is apply a class to hide it
        if (value[i] == "null") {
            e.options[i] = new Option(name[i], value[i], selected == null);
            i++;
        }
        for (c = name.length; i < c; i++) {
            e.options[i] = new Option(name[i] + this.cleanStock(stock[i]), value[i]);
            e.options[i].innerHTML = name[i] + this.cleanStock(stock[i]);
            // ..select the item if the preselection matches;
            // OR if the previously selected size matches a new
            // entry being populated..
            var m = name[i].match(/^[\w]*/i);
            var t = '';
            if (m && m.length != 0)
                t = m[0];
            if ((selected && value[i] == selected) || z == t) {
                this.setVariantOption(value[i]);
                e.options[i].selected = true;
            }
        }

        cache = e;
        return cache;
    },

    // Load up the variant data and do a stock check
    stockCheck: function(e) {
        if (e && e.value != "null") {
            // Update variant data if passing in a reference to a variant
            this.getVariantData(e.value);
        }
        if (this.variantData) {
            // ..update the quantity selection dropdown..
            if (e = document.getElementById("product-quantity")) {
                var n = parseInt(e.value);

                Core.Dom.emptyElement(e);

                n = (n > this.variantData.stocklevel) ? 1 : n;

                // Loop through the linked styles and create a size list based on a common colour
                var linkedVariantInfo;
                var selectedLinkedStyle;
                if (typeof (LinkedProductCount) != "undefined") {
                    for (var j = 1; j <= LinkedProductCount; j++) {
                        for (var k in eval("LinkedProductData" + j)) {
                            linkedVariantInfo = eval("LinkedProductData" + j + "[k]");
                            if (linkedVariantInfo.sizecode == this.variantData.sizecode && linkedVariantInfo.colourcode == this.variantData.colourcode && linkedVariantInfo.stocklevel > this.variantData.stocklevel) {
                                if (selectedLinkedStyle != null) {
                                    //If the selected linked style already exist, then compare its stock level with the most recent one
                                    if (selectedLinkedStyle.stocklevel > this.variantData.stocklevel) {
                                        selectedLinkedStyle = linkedVariantInfo;
                                    }
                                }
                                else {
                                    if (linkedVariantInfo.stocklevel > this.variantData.stocklevel) {
                                        selectedLinkedStyle = linkedVariantInfo;
                                    }
                                }
                            }
                        }
                    }
                }

                //If the stock level of the linked style is greater than the master variant's stock level, use the stock level from the linked style variant
                if (selectedLinkedStyle) {
                    for (var i = 1; i <= selectedLinkedStyle.stocklevel; i++) {
                        e.options[e.options.length] = new Option(i.toString(), i.toString(), i == n);
                    }
                    selectedLinkedStyle.master = this.variantData.code;
                    this.variantData.selectedLinkedStyle = selectedLinkedStyle;
                    // If variant is out of stock, disable button
                    if (selectedLinkedStyle.stocklevel <= 0) {
                        this.updateBasketButton(false);
                        this.stockStatus.innerHTML = "Out of Stock";

                    } else {
                        this.updateBasketButton(true);
                        this.stockStatus.innerHTML = "In Stock";
                    }
                }
                else {
                    for (var i = 1; i <= this.variantData.stocklevel; i++) {
                        e.options[e.options.length] = new Option(i.toString(), i.toString(), i == n);
                    }
                    this.variantData.selectedLinkedStyle = null;
                    // If variant is out of stock, disable button
                    if (this.variantData.stocklevel <= 0) {
                        this.updateBasketButton(false);
                        this.stockStatus.innerHTML = "Out of Stock";

                    } else {
                        this.updateBasketButton(true);
                        this.stockStatus.innerHTML = "In Stock";
                    }
                }
                if (e.options.length == 0) e.options[e.options.length] = new Option(0, 0, true);
                // ..force an onchange event for the quantity selection
                // to circumvent the custom form elements restriction..
                Core.Dom.Event.raise(e, "change");
            }
        }
        if (parseFloat(this.variantData.price) == 0) {
            this.updateBasketButton(false);
        }
    },

    // Reset all variant items to select a new one
    clearProduct: function() {
        // Remove checked radio buttons
        var radio = this.product.getElementsByTagName("input");
        for (var i = 0, c = radio.length; i < c; i++) {
            var item = radio[i];
            if (item.name == this.groupName && item.type == "radio") {
                radio[i].checked = false;
            }
        }

        // Remove selected graphics
        var img = this.product.getElementsByTagName("img");
        for (var i = 0, c = img.length; i < c; i++) {
            var item = img[i];
            item.className = "";
            item.src = item.src.replace(/-o.gif/i, ".gif");
        }
    },

    // Universal image mutator
    setImages: function(variantCode, colourCode) {
        colourCode = this.cleanColourCode(colourCode);
        var oid = this.productSelection.pid + colourCode;
        // Set the hero image
        var hero;
        if (hero = this.imagery.hero) hero.src = this.heroImage(oid);
        // Set the add-wardrobe link
        if (this.imagery.wardrobe) this.imagery.wardrobe.href = Core.Url.replaceParam("vid", oid, this.imagery.wardrobe.href);
        // Set the zoom link
        //if(this.imagery.zoom)       this.imagery.hero.parentNode.href = this.imagery.zoom.src = this.imagery.hero.src.replace(/\/medium/, '/large');

        // ..fetch the alternative images and apply them once received..
        this.ajax.set('/handler.aspx', { Command: 'Alternatives', pid: oid });
        this.ajax.busy = this.ajax.error = function() {
            var el = document.getElementById('product-gallery');
            if (el) Core.Dom.emptyElement(el);

            if (el = document.getElementById('product-gallery-caption'))
                el.style.display = 'none';
        };
        this.ajax.complete = function() {
            var json = this.getJson() || [];
            var el = document.getElementById('product-gallery');
            var hrefs = [], pics = [];
            if (!el) return false;

            if (el) Core.Dom.emptyElement(el);


            // ..create each alternate image..
            for (var i = 0; i < json.length; i++) {
                var li = document.createElement('li'), a, img;

                li.appendChild(a = document.createElement('a'));
                a.onclick = function() { hero.src = this.href; return false; };
                li.style.width = '55px';
                li.style.height = '72px';

                a.href = json[i].medium;
                a.appendChild(img = document.createElement('img'));
                img.src = '/assets/en/site/icons/loading.gif';
                hrefs.push(json[i].small);
                pics.push(img);
                el.appendChild(li);
            }

            if (json.length != 0 && (el = document.getElementById('product-gallery-caption')))
                el.style.display = 'block';

            // ..preload the images and set the display when they're finished..
            // (this avoids a flickering effect on the image elements)
            if (hrefs.length != 0) Core.Image.preload(hrefs, function() {
                for (var x = 0; x < pics.length; x++) {
                    if (typeof (this.cache) != "undefined" && typeof (this.cache[x]) != "undefined")
                        pics[x].src = this.cache[x].src;
                    else
                        pics[x].src = hrefs[x];
                }
            });
            return false;
        };
        this.ajax.get();
        return false;
    },

    // Ensure colour code has correct format
    cleanColourCode: function(colourCode) {
        // Make sure the code is always 2 digits
        return (colourCode.length < 2) ? colourCode = "0" + colourCode : colourCode;
    },

    // Replace the hero image with the right variant
    heroImage: function(oid) {
        // Replace the placholder with the option Id
        return '/assets/en/catalogue/alt/medium_default/' + oid + ".jpg";
    },

    // Return proper stock messages
    cleanStock: function(stock) {
        var message = stock, suffix = " - ";
        if (message.length > 0) {
            message = suffix + message;
        } else {
            message = "";
        }
        return message;
    },

    // Tells you if stock has multiple sizes based on the size data
    hasSingleSize: function(size) {
        return (size == "One Size");
    },

    // Clean up the weird size name
    cleanSize: function(size) {
        if (size == "One Size") {
            size = "One Size";
        }
        return size;
    },

    ImageSizeReplace: function() {
        //make the main image size bigger
        tmpHolder[0] = tmpHolder[0].replace("width=50", "width=275");
        tmpHolder[0] = tmpHolder[0].replace("height=50", "height=380");
        for (var i = 1; i <= 3; i++) {
            tmpHolder[i] = tmpHolder[i].replace("width=275", "width=50");
            tmpHolder[i] = tmpHolder[i].replace("height=380", "height=50");
        }
    },

    getUnsafeId: function(id) {
        /* 2009-01-13, KS. Decode the "safe" id such that it is suitable for display.
        */
        return (decodeURIComponent(id) || '').replace('$U0022', '&quot;').replace('$U002E', '.').replace('$U002D', '-');
    }
};

var DataCash = {
	/**
	* Load the DataCash IFRAME
	*/
	init: function() {
		var form = document.forms["datacash-acs-form"];
		if (form) {
			form.submit();
		}
	},
	submit: function() {
		// Jump to the location of the page
		window.location.hash = "payment-form"; 
		return false;
	}
};

var Checkout = {
    init: function(textboxid, dropdownid) {
        var textbox = document.getElementById(textboxid);
        textbox.onkeydown = function(oEvent) { Checkout.FillCardType(textboxid, dropdownid); }
    },
    disable: function() {
        var e = null;
        if( e = document.getElementById("checkout-button-1") ) {
            e.onclick = function(e) { return false; }
            e.style.cursor = "default";

            e.src = "/assets/en/site/buttons/basket-add-o.gif";
        }
        if( e = document.getElementById("checkout-button-2") ) {
            e.onclick = function(e) { return false; }
            e.style.cursor = "default";

            e.src = "/assets/en/site/buttons/basket-add-o.gif";
        }
        return true;
    },
    FillCardType: function(textboxid, dropdownid) {
        var textbox = document.getElementById(textboxid);
        
        //mastercard
        var regexp = new RegExp("^(5[1-5])");
        if (textbox.value.match(regexp))
        {
            Checkout.SelectDropDown(dropdownid, "MAS");
            return;
        }

        //Amex
        var regexp = new RegExp("^(34|37)");
        if (textbox.value.match(regexp))
        {
            Checkout.SelectDropDown(dropdownid, "AMEX");
            return;
        }
        
        //Visa
        var regexp = new RegExp("^(4)");
        if (textbox.value.match(regexp))
        {
            Checkout.SelectDropDown(dropdownid, "VISA");
            return;
        }

        //Maestro
        var regexp = new RegExp("^(50|5[6-8]|6)");
        if (textbox.value.match(regexp))
        {
            Checkout.SelectDropDown(dropdownid, "MAE");
            return;
        }
        
        //Solo
        var regexp = new RegExp("^6767");
        if (textbox.value.match(regexp))
        {
            Checkout.SelectDropDown(dropdownid, "SOLO");
            return;
        }
    },
    SelectDropDown: function(dropdownid, selectedvalue) {
        var dropdown = document.getElementById(dropdownid);

        for (iLoop = 0; iLoop < dropdown.options.length; iLoop++)
        {    
            if (dropdown.options[iLoop].value == selectedvalue)
            {
                // Item is found. Set its selected property, and exit the loop
                dropdown.options[iLoop].selected = true;
                break;
            }
        }        
    }
}
/* Payment Page Show/Hide
------------------------------*/
function showElement(layer){
	var myLayer = document.getElementById(layer);
	if(myLayer.style.display=="none"){
		myLayer.style.display="block";
		myLayer.backgroundPosition="top";
	} else { 
		myLayer.style.display="none";
	}
	
	return false;
}

/* ie6 Menu Show/Hide
------------------------------*/
sfHover = function() {
	var sfEls = document.getElementById("cat-nav");
	if( !sfEls )    return;
	
	sfEls = sfEls.getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);
