var staging = "", cacheAngles = [];

new Asset.css("http://reviews.webtogs.co.uk/"+staging+"static/4952-en_gb/bazaarvoice.css");
new Asset.javascript("http://reviews.webtogs.co.uk/"+staging+"static/4952-en_gb/bazaarvoice.js");


var C = {
    // console wrapper
    debug: true, // global debug on|off
    quietDismiss: false, // may want to just drop, or alert instead
    log: function() {
        if (!C.debug) return false;

        if (typeof console == 'object' && typeof console.log != "undefined")
            console.log.apply(this, arguments);
        else
            if (!C.quietDismiss) {
                var result = "";
                for (var i = 0, l = arguments.length; i < l; i++)
                    result += arguments[i] + " ("+typeof arguments[i]+") ";

                alert(result);
            }
    }
} // end console wrapper.


Element.extend({
    get: function(property){
		var index = Element.Properties[property];
		if (index) return this[index];
		var flag = Element.PropertiesIFlag[property] || 0;
		if (!window.ie || flag) return this.getAttribute(property, flag);
		var node = this.attributes[property];
		return (node) ? node.nodeValue : null;
	}
});

var Product = new Class({
    options: {
        liveStockCheck: true,
        liveStockEvery: 45, // seconds
        id: $empty(),
        selectedSize: "",
        selectedColour: $empty(),
        selectedVersion: $empty(),
        lead: "",
        estimate: "",
        sizes: [],
        colours: [],
        versions: [],
        leadsTable: [],
        leadsEstimates: [],
        captions: false,
        cacheAngles: [],
        cacheBoxAngles: []
    },
    initialize: function(options) {
        this.setOptions(options);
        this.startMonitor();
        this.outOfStock(); // 27/05/2009 15:27:02
    },
    set: function() {
        // internal setter for options that can take a json or a simple pair
        switch ($type(arguments[0])) {
            case "object":
                this.setOptions(arguments[0]);
            break;
            default:
                if (arguments.length == 2) {
                    var newo = {}
                        newo[arguments[0]] = arguments[1];

                    this.setOptions(newo);
                } else {
                    C.log("incorrect number of arguments");
                }
            break;
            case "false":
                return false;
            break;
        }
    },
    get: function(key) {
        // this.options getter, 1.2 stylee...
        return this.options[key];
    },
    getVersion: function(id) {
        // returns full container object
        return Json.evaluate(this.options.versions[id]);
    },
    showSelectedColour: function() {
        // update colour name to screen, reset colour swatches.
        var c = this.get("selectedColour"), s = (this.get("selectedSize").length) ? ", " : "";
        $("newColour").setText(c.trim() + s);
        $$("div.colours").each(function(el) {
            if (el.get("data-colour") != c && el.hasClass("colourIconOn"))
                el.removeClass("colourIconOn");
            else if (el.get("data-colour") == c && !el.hasClass("colourIconOn"))
                el.addClass("colourIconOn");
        });

        this.showSelectedSize();
        // fix for longer names
        var paneHeight = $("newColour").getParent().getCoordinates()['height'];

        if (paneHeight > 30) {
            c = c.substr(0, 25) + "...";
            $("newColour").setText(c.trim() + s);
        }
    },
    showSelectedSize: function() {
        // update text and also change size boxes.
        var s = this.get("selectedSize"), c = this.get("selectedColour"), newSize = (s.length) ? "Size: <strong>" + s + "</strong>" : "";


        $("newSizeMsg").setText("Currently selected:");
        $("newSize").setHTML(newSize); // ok to buy now

        $$("div.sizeIconOn").each(function(el) {
            var foo = el.getParent().getParent().getParent().getParent().getParent().getParent().getPrevious().getProperty("data-colour");
            if (el.getText() != s || foo != c)
                el.removeClass("sizeIconOn").addClass("sizeIconOff");

        });

    },
    colourClick: function(el) {
        // clicked on a colour swatch
        var oldColour = this.get("selectedColour");
        this.set("selectedColour", el.get("data-colour"));

        // fix background
        $$("div.colour_grid").removeClass("colour_gridOn");
        el.getNext().addClass("colour_gridOn");

        $("orderNow").setStyle("background", "transparent");
        // workaround selecting size with colour swap
        if (this.get("selectedSize") != "" && this.get("selectedSize") != "One Size") {
            if (this.checkStock(this.get("selectedSize")).allow == false) {
                this.set({
                    selectedSize: "",
                    selectedVersion: $empty()
                });

                this.saveStockStatus("", "");
                this.restoreStockStatus();
                this.showSelectedSize();
                $("add2basket").setProperty("src", "/img/new-add-to-basket-off.gif");
            }
        }

        if (this.get("selectedSize") == "One Size") {
            // do we have the stock?
            var requestedVersion = el.get("data-id"), version = this.getVersion(requestedVersion), _this = this;
            if ((version.stock <= 0 && version.nc >= 0 ) || version.disabled == 'true') {
                el.fade(1,.5, {remove: false, reclaim: false});
                // myEventBubble(el, "Sorry, colour<br /> is out of stock.");
                this.set({
                    selectedVersion: version.cid
                });

                $("add2basket").setProperty("src", "/img/new-add-to-basket-off.gif");


                this.showSelectedSize();
                this.showSelectedColour();

            } else {
                this.set({
                    "selectedVersion": version.cid
                });
            }



        }

        if (this.get("selectedSize") != "")
            this.showStockStatus(this.get("selectedVersion").toInt());

        this.showSelectedColour();
        $("productImage").setProperty("src", "/pimages/" + this.options.id + "/" + el.getProperty("data-id") + "/product_full.jpg");

        // update medium view targets
        var newTarget = '/pimages/' + this.get("id") + "/" + el.get("data-id") + "/product_main.jpg";
        $("PL").setProperty("href", newTarget);
        $("PL2").setProperty("href", newTarget);

        // get angled shots.
        this.getAngles();
        this.buildSizes();
    },
    colourSetEvents: function() {
        var _this = this;
        // define click and mouseover on colour swatches
        $$(".colours").addEvents({
            dblclick: function(e) {
                new Event(e).stop();
                return false;
            },
            click: function() {
                if (this.allowClick === false)
                    return false;

                this.allowClick = false;

                _this.colourClick(this);
                $("productImage").setProperty("data-zoomer", this.getProperty("data-zoomer")).zoomer();

                // mz.loadImage($("productImage"));

                (function() {
                    this.allowClick = true;
                }).delay(500, this);
            },
            mouseenter: function() {
                this.addClass("colourIconOn");
            },
            mouseleave: function() {
                if (_this.get("selectedColour") != this.getProperty("data-colour"))
                    this.removeClass("colourIconOn");
            }
        });

        $$("div.colour_grid").addEvents({
            mouseenter: function() {
                if (!this.hasClass("colour_gridOn"))
                    this.addClass("colour_gridOn");
            },
            mouseleave: function() {
                if (_this.get("selectedColour") != this.getPrevious().getProperty("data-colour"))
                    this.removeClass("colour_gridOn");
            }

        });
    },
    checkStock: function(size, colour) {
        // returns a yes/no on allowing to buy a size from current colour.
        var containers = new Hash(this.get('versions'));
        var allow = false, _this = this, l = this.get("startLead"), mid = false, neg = false;

        colour = (!$type(colour)) ? _this.get("selectedColour") : colour;
        containers.each(function(va, k) {
            if (allow)
                return false;
            var v = Json.evaluate(va);
            if (v.colour == colour && v.size == size) {
                if (v.stock > 0 && v.disabled != 'true')
                    allow = true;
                l = v.lead;
                neg = v.nc;
                mid = v.cid;
            }
        });

        return {
            allow: allow,
            lead: l,
            cid: mid,
            nc: neg
        }
    },
    showStockStatus: function(cid) {

        if ($type(cid) == "number") {
            var thisContainer = this.getVersion(cid), thisEstimate = this.get("leadsEstimates")[thisContainer.lead];
            var leadMessage = "<span style='color: #3CCC49;background:url(/img/in-stock-ok.gif) no-repeat center right; padding-right: 25px;'>In Stock</span>";
            var dispatchMessage = "(Will be dispatched <span class='bold'>"+((thisEstimate == "Today" || thisEstimate == "Tomorrow") ? thisEstimate : "on "+thisEstimate)+"</span>)";
            if (thisContainer.disabled != "true") {
                // nc fix
                if (thisContainer.nc < 0 && thisContainer.lead != 1) {
                    leadMessage = "<span style='color: #e8ba40;background:url(/img/in-stock-way.gif) no-repeat center right; padding-right: 25px;'>On The Way</span>";
                    dispatchMessage = "(Will be dispatched <span class='bold'>within "+this.get("leadsTable")[thisContainer.lead]+"</span>)";
                } // end fix.

                // no stock
                if (thisContainer.nc <= 0 && thisContainer.stock <= 0) {
                    leadMessage = "<span style='color: #f33b3b;background:url(/img/in-stock-not.gif) no-repeat center right; padding-right: 25px;'>Out Of Stock</span>";
                    dispatchMessage = (this.get("traffic") != "red") ? "(... but we may have more on the way)" : "(... and we won't be getting any more)";
                }
            }
            else {
                leadMessage = "<span style='color: #f33b3b;background:url(/img/in-stock-not.gif) no-repeat center right; padding-right: 25px;'>Out Of Stock</span>";
                dispatchMessage = (this.get("traffic") != "red") ? "(... but we may have more on the way)" : "(... and we won't be getting any more)";
            }
        }
        else {
            var leadMessage = "", dispatchMessage = "";
        }

        $("lead").setHTML(leadMessage);
        $("when").setHTML(dispatchMessage);
    },
    saveStockStatus: function(lead, estimate) {
        this.set("lead", lead);
        this.set("estimate", estimate);
    },
    restoreStockStatus: function() {
        $("lead").setHTML(this.get("lead"));
        $("when").setHTML(this.get("estimate"));
    },
    buildSize: function(status, size, lead, cid, nc) {
        // create a size icon and return it as an object
        cid = cid.toInt();
        var _this = this;
        if (size == "One Size") {
            if (_this.checkStock(_this.get("selectedSize")).allow != false)
                $("add2basket").setProperty("src", "/img/new-add-to-basket.gif");
            return false;
        }

        return new Element("div", {"class": "SB curImage left " + status}).setText(size).setProperty("rel", cid).addEvents({
            click: function() {
                if (status == "sizeIconNo")
                    return false;
                _this.set("selectedSize", size);
                _this.set("selectedVersion", cid);
                _this.showSelectedSize();
                _this.saveStockStatus($("lead").innerHTML, $("when").innerHTML);

                var prv = this.getParent().getParent().getParent().getParent().getParent().getParent().getPrevious();
                if (_this.get("selectedColour") != prv.getProperty("data-colour"))
                    prv.fireEvent("click");

                if ($("add2basket").getProperty("src").contains("off"))
                    $("add2basket").setProperty("src", "/img/new-add-to-basket.gif");
            },
            mouseenter: function() {
                _this.saveStockStatus($("lead").innerHTML, $("when").innerHTML);
                if (this.hasClass("sizeIconNo")) {
                    _this.showStockStatus(cid);
                    // myEventBubble(this, "Sorry, this size<br /> is out of stock.");
                    return false;
                }

                this.addClass("sizeIconOn");

                _this.showStockStatus(cid);

            },
            mouseleave: function() {
                var prv = this.getParent().getParent().getParent().getParent().getParent().getParent().getPrevious().getProperty("data-colour");
                if (this.getText() != _this.get("selectedSize") || _this.get("selectedColour") != prv)
                    this.removeClass("sizeIconOn");
                _this.restoreStockStatus();

            }
        });
    },
    buildSizes: function() {
        // build the sizes available for current colour dynamically.
        var sizes = new Hash(this.get('sizes'));
        var versions = new Hash(this.get('versions'));
        var colours = new Hash(this.get('colours'));
        var _this = this;

        colours.each(function(vv, kk) {
            var target = $$("div.sizeBoxes").filter(function(sb) {
                if (sb.getProperty("rel") == kk)
                    return sb;
            })[0];

            if (!target)
                return false;

            target.empty();
            sizes.each(function(v, k) {
                var sc = _this.checkStock(k, kk);
                var statusClass = (sc.allow) ? "sizeIconOff" : "sizeIconNo";
                if (_this.get("selectedVersion") != false && _this.get("selectedSize") == k && _this.get("selectedColour") == kk)
                    statusClass = "sizeIconOn";
                if (!sc.allow && !sc.cid)
                    return false;
                var sizeBox = _this.buildSize(statusClass, k, sc.lead, sc.cid, sc.nc);
                if (sizeBox)
                    sizeBox.inject(target);
                else {
                    target.getPrevious().setStyles({
                        "font-size": "14px",
                        "font-weight": "bold"
                    });

                    target.getParent().addClass("cur").removeEvents().addEvent("click", function() {
                        var prv = this.getParent().getParent().getParent().getParent().getPrevious();
                        if (_this.get("selectedColour") != prv.getProperty("data-colour"))
                            prv.fireEvent("click");
                    });

                }
            });

        });

        // $("sizes").empty();

        if (sizes.length < 2) // one size!
            return false;


    },
    toBasket: function() {
        // add the currently selected item to basket

        if ($("lead").getText().contains("Out Of Stock")) {
            myEventBubble($("add2basket"), "Sorry, item <br />not in stock!");
            return false;
        }

        if (!this.get("selectedVersion")) {
            $("add2basket").tooltip("Please select your size first.", {
                className: "what3",
                topOffset: 44,
                topStartOffset: 150,
                opacity: .95,
                delay: 3000,
                innerStyle: "padding: 5px; padding-top: 14px;line-height: 1.3; font-weight: bold"
            });
            return false;
        }
        var myBasket = Cookie.get("basket");

        if (myBasket != false) {
            basketItems = myBasket.split(",");

            var newBasket = '';
            for (ii = 0; ii < basketItems.length-1; ii++)
                newBasket += basketItems[ii] + ',';

            myBasket = newBasket;
            var Older = false;
            if (basketItems.toString().contains(this.get("id")+ "-" + this.get("selectedVersion")))
                Older = true;
            else
                myBasket = this.get("id") + "-" + this.get("selectedVersion") + "-1,"+ myBasket;
        }
        else {
            myBasket = this.get("id") + "-" + this.get("selectedVersion") + "-1,";
        }

        Cookie.remove("basket");
        Cookie.set("basket", myBasket, {path: "/", duration: 365});
        if (!Older) {
            toggleModal("#fff");
            Cookie.set("basketAB", Cookie.get("lastAB"), {path: "/"});
            window.location.href='/basket.php';
        }
        else {
            myEventBubble($("add2basket"), "Already in<br />basket!");
        }

    }, // end add2basket
    togBox: function(el) {
        var _this = this, imageEvent;
        el.modalBox({
            id: "lightPane",
            width: (window.ie6) ? 692 : 685,
            height: 645,
            title: _this.get("productName")+ " in "+ _this.get("selectedColour")
        });


        imageEvent = (function() {
            var lightPane = $("modalBody");
            if (!lightPane)
                return false;



            new Asset.image(el.getProperty("href"), {
                "class": "xpi",
                onload: function() {

                    this.removeEvents().setOpacity(0).injectTop(lightPane).fade(0,1, {remove: 0});

                    if ($("closelight"))
                        $("closelight").smartDispose();
                    var closelight = new Element("div", {id: "closelight"}).setStyles({
                        width: 60,
                        float: "right",
                        background: "#fff",
                        "font-size": "14px",
                        "font-weight": "bold",
                        "z-index": 1000001000,
                        "text-align": "center"
                    }).injectTop(lightPane);

                    var angleEvents = function(preloadText) {
                        closelight.empty().setHTML(preloadText);
                        $$(".miniangle").each(function(el) {
                            var fullSize = (el.getProperty("src").contains("THUMB"))
                                         ? el.getProperty("src").replace(/THUMB/, "FULL")
                                         : el.getProperty("src").replace(/icon/, "main");

                            if (!$type(preload[el.id]))
                                preload[el.id] = new Asset.image(fullSize, {"class": "xpi"});

                            el.removeEvents().addEvents({
                                "click": function() {
                                    $E(".xpi").replaceWith(preload[el.id].clone().fade(0,1, {remove: false, reclaim: false}));
                                }, // click end
                                "mouseenter": function() {
                                    this.addClass("Selectedimage");
                                },
                                "mouseleave": function() {
                                    this.removeClass("Selectedimage");
                                }
                            }).addClass("curImage").addClass("Plainimage");
                        }); // each
                    };

                    var preload = _this.get("cacheBoxAngles");

                    if (!$type(preload[_this.get("selectedColour")]))
                    new Ajax("/angles.php?a=mini&id="+_this.get("id")+"&version="+_this.get("selectedColour"), {
                        method: "get",
                        onComplete: function() {
                            preload[_this.get("selectedColour")] = this.response.text;
                            _this.set("cacheBoxAngles", preload);
                            angleEvents(this.response.text);
                        }
                    }).request(); // angles.
                    else
                        angleEvents(preload[_this.get("selectedColour")]);



                } // onload
            }); // fullimage
        }).delay(1000); // animation wait.
    },
    togBoxAttach: function() {
        var _this = this;
        $$("a[rel=lightbox]").each(function(el) {
            el.addEvent("click", function(e) {
                // intercept click
                var e = new Event(e).stop();

                if ($("zoomLarger"))
                    $("productImage").fireEvent("mouseleave");
                _this.togBox(el);
            });
        });
    },
    getAngles: function() {
        // gets the angled shots
        $("angles").setOpacity(0);

        var _this = this;

        if (cacheAngles.length > 0) {
            var cached = cacheAngles.filter(function(el) {
                if (el.colour == _this.get("selectedColour"))
                    return el;
            });

            if (cached.length) {
                $("angles").setHTML(cached[0].text).fade(0,1, {reclaim: false, remove: false});
                angles();
                return false;
            }
        }

        new Ajax("/angles.php?id="+this.get("id")+"&version="+this.get("selectedColour"), {
            update: $("angles"),
            method: "get",
            postData: "",
            onComplete: function() {
                $("angles").fade(0,1, {reclaim: false, remove: false});
                angles();
                cacheAngles.push({colour: _this.get("selectedColour"), text: this.response.text});
                // C.log(cacheAngles, _this.get("selectedColour"));
            }
        }).request();

    }, // end getAngles
    liveUpdate: function() {
        // attached to addtobasket mouseover event
        if (this.get("liveStockCheck") != true)
            return false;

        var _this = this;
        new Ajax("/accountAjax.php", {
            method: "get",
            onComplete: function() {
                eval(this.response.text);
                var containers = _this.get('versions');
                var newcontainers = newStock.versions;

                // find out what has changed and if it affects the purchase
                if (!_this.get("selectedVersion")) {
                    // C.log("nothing, resetting");
                    // nothing selected anyway, does not matter, we can update all.
                    _this.set("versions", newcontainers);
                    _this.buildSizes();
                }
                else {
                    // they have something selected. see if it is affected
                    if (newcontainers[_this.get("selectedVersion")] != containers[_this.get("selectedVersion")]) {
                        // yes.
                        var sizeSelected = $E(".SB[rel="+_this.get("selectedVersion")+"]");
                        if ($type(sizeSelected)) {
                            myEventBubble(sizeSelected, "Stock changed<br />please review.");
                            (function() {
                                if ($("myBubble"))
                                    $("myBubble").fade(1,0);
                            }).delay(3000);
                        }

                        _this.set({
                            "selectedVersion": $empty(),
                            "selectedSize": "",
                            "versions": newcontainers,
                            "lead": ""
                        });
                        _this.buildSizes();
                        _this.showSelectedSize();
                        _this.showStockStatus(_this.get("selectedVersion").toInt());
                    } else {
                        _this.set("versions", newcontainers);
                        _this.buildSizes();
                    }
                }

            }
        }).request("a=livestock&id="+this.get("id"));
    },
    stockReview: function() {
        // appraisal of current stock situation, greying out etc.
        var sizes = new Hash(this.get('sizes'));
        var _this = this;
        if (sizes.length == 1) {
            this.set("selectedSize", "One Size");
            // $("cas").setText("This item comes in: ");
            $$(".colours").each(function(el) {
                if (_this.getVersion(el.get("data-id")).stock <= 0)
                    el.fade(1,0.5, {reclaim: false, remove: false})
            });
        }
    },
    startMonitor: function() {
        // live updates of stock every nn seconds.
        if (this.get("liveStockCheck")) {
            (function() {
                this.liveUpdate();
            }).periodical(this.get("liveStockEvery")*1000, this);
        }
    },
    outOfStock: function() {
        var _this = this;



        $("outofstock").getElement("a").addEvents({
            click: function(e) {
                var e = new Event(e).stop();

                var OOSvers = [], versions = new Hash(_this.get("versions"));
                versions.each(function(ver) {
                   var ver = Json.evaluate(ver);
                   if ((ver.stock <= 0 && ver.nc >= 0 )|| ver.disabled == "true")
                        OOSvers.push(ver);
                });

                var bodyText = "", boxheight = 222;

                if (OOSvers.length ) {
                    bodyText = "Please select the colour and size you'd like to be notified about:<br /><br /><select id='OOSversion' style='width:100%'>";
                    OOSvers.each(function(ver) {
                        bodyText += "<option value='"+ver.cid+"'>Colour: <strong>" + ver.colour + "</strong>, Size: <strong>" + ver.size + "</strong><br />";
                    });

                    bodyText += '</select><div style="padding-left: 23px;">';
                    bodyText += '<label for="MBemail" style="color:#000;float:left;font-family:Verdana, Arial, Helvetica, sans-serif;font-size:16px;font-weight:700;height:20px;margin-left:0;margin-right:0;margin-top:20px;padding-top:2px;width:inherit"  >';
                    bodyText += 'Enter your email address:</label>';
                    bodyText += "<br /><input title='Enter your email address' id='OOSemail' value='' name='email' type='text' class='account_input account_input' tabindex='1'  /><br clear='all' />";
                    bodyText += '<div style="padding: 12px; padding-left: 140px"><img src="/img/modal_subscribe.gif" id="OOSsubscribe" class="cur" /></div>';
                }
                else {
                    bodyText = "We're sorry, there are no 'out of stock' sizes of this product at the moment!<br /><br />You can just close this box and add to your basket.";
                    boxheight = 104;
                }

                this.modalBox({
                    height: boxheight,
                    title: "Out of stock? No problem...",
                    text: bodyText,
                    movable: true
                });

                (function() {
                    if ($("OOSsubscribe"))
                    $("OOSsubscribe").addEvents({
                        click: function() {
                            var em = $("OOSemail").getProperty("value").clean();
                            if (isValid(em)) {
                                new Ajax("/accountAjax.php", {
                                    method: "get",
                                    onComplete: function() {
                                        $("modalBody").setStyles({
                                            fontSize: "14px",
                                            textAlign: "center"
                                        }).setHTML("<br /><br /><strong>Thank you for your interest, we appreciate it.</strong><br /><br /><br />You will receieve a notification email<br /> as soon as we stock this in.</center>");
                                        (function() {
                                            if ($("modal"))
                                                $("modal").fireEvent("click");
                                        }).delay(5000);
                                    }
                                }).request("a=s2oos&email=" + em + "&skew="+$("OOSversion").getProperty("value"));

                            }
                            else {
                                $("modalBox").setStyle("background", "#fff url(/img/login-review-box-error.gif) no-repeat");

                                $("OOSemail").tooltip("Invalid email,<br />check and try again.", {
                                    className: "what3",
                                    topOffset: 44,
                                    topStartOffset: 200,
                                    opacity: 1,
                                    eventEnd: "focus",
                                    innerStyle: "padding: 5px;line-height: 1.3; font-weight: bold"
                                }).addEvents({
                                    focus: function() {
                                        $("modalBox").setStyle("background", "#fff url(/img/top_grad_2.gif) repeat-x");
                                    }
                                });

                            }


                        }
                    });
                }).delay(1500); // animation delay

            }
        });
    }
}); // end Product

Product.implement(new Events, new Options);



var angles = function() {
    $$(".angles").each(function(el) {
        var colour = el.getProperty("data-colour");
        el.addEvents({
            mouseenter: function() {
                if (this.hasClass("Selectedimage")) {
                    this.setProperty("Selected", "true");
                    return false;
                }
                this.addClass("Selectedimage").setProperty("Selected", "false");
            },
            mouseleave: function() {
                if (this.getProperty("Selected") == "true")
                    return false;
                this.removeClass("Selectedimage");
            },
            click: function() {
                if (this.getProperty("Selected") == "true")
                    return false;

                this.setProperty("Selected", "true");
                $$(".angles").removeClass("Selectedimage");
                this.addClass("Selectedimage");

                var fn = this.getFirst().getProperty("src");

                if (colour == "_") { // main
                    var mediumView = fn.replace("icon", "full");
                    var fullView = fn.replace("icon", "main");
                }
                else {
                    var mediumView = fn.replace("THUMB_", "");
                    var fullView = fn.replace("THUMB_", "FULL_");
                }

                $("productImage").replaceWith($("productImage").clone().setProperty("src", mediumView).fade(0,1, {reclaim: false, remove: false}));

                $("PL").setProperty("href", fullView);
                $("PL2").setProperty("href", fullView);


            }
        });
    });
}

var charts = {
    sizeChart: function(el, dbid) {
        // get the sizechart data on screen...
        if ($("mychart"))
            return false;

        var chartTitle = "";
        new Ajax("/accountAjax.php?a=getchart&id="+dbid, {
            method: "get",
            onComplete: function() {
                var MT = new Element("div", {id: "modalTitle"}).setStyles({display:"none"}).inject(document.body),
                temp = new Element("div").setHTML(this.response.text).setStyles({
                    position: "absolute",
                    top: -400,
                    left: -400,
                    width: 540
                }).inject(document.body), tempHeight = temp.getCoordinates()['height'] + 28;

                temp.dispose();

                el.modalBox({
                    title: MT.innerHTML,
                    text: this.response.text,
                    shadow: !false,
                    width: 560,
                    height: tempHeight,
                    id: "mychart",
                    innerPadding: 0,
                    movable: true
                });

                MT.dispose();

            }
        }).request();
    }
}

// bazaar voice variables and function definitions, prod pages
var attachEvents = function(els) {
    // attaches an event to all reviews that asks users to auth if not logged in.

    els.addEvents({
        "click": function(e) {
            var el = this;
            new Event(e).stop();

            if (!AU) {
                new Ajax("/accountAjax.php?a=loginBox&f=" + el.getProperty("href"), {
                    method: "get",
                    onComplete: function() {
                        el.modalBox({
                            id: "loginBox",
                            title: "To leave a review on Webtogs, you need to log in",
                            width: 500,
                            height: 300,
                            text: this.response.text
                        });

                        (function() {
                            $("MBli").addEvents({
                                click: function() {
                                    var email = $("MBemail").getProperty("value").clean(), password = $("MBpass").getProperty("value"), back = $("MBback").getProperty("value");

                                    if (email.length && password.length) {
                                        new Ajax("/accountAjax.php", {
                                            method: "get",
                                            onComplete: function() {
                                                var result = this.response.text;
                                                if (result != "false") {
                                                    window.location.href = el.getProperty("href");
                                                }
                                                else {
                                                    $("loginBox").setStyle("background", "#fff url(/img/login-review-box-error.gif) no-repeat");

                                                    $("MBemail").tooltip("Invalid email or password,<br />Check and try again.", {
                                                        className: "what3",
                                                        topOffset: 44,
                                                        topStartOffset: 200,
                                                        opacity: 1,
                                                        eventEnd: "focus",
                                                        innerStyle: "padding: 5px;line-height: 1.3; font-weight: bold"
                                                    }).addEvents({
                                                        focus: function() {
                                                            $("loginBox").setStyle("background", "#fff url(/img/top_grad_2.gif) repeat-x");
                                                        }
                                                    });
                                                    return false;
                                                }
                                            }
                                        }).request("a=loginBoxAuth&MBemail="+email+"&MBpass="+password);
                                    }
                                    else {
                                        $("loginBox").setStyle("background", "#fff url(/img/login-review-box-error.gif) no-repeat");

                                        $("MBemail").tooltip("Please enter your email <br />and password to login.", {
                                            className: "what3",
                                            topOffset: 44,
                                            topStartOffset: 200,
                                            opacity: 1,
                                            eventEnd: "focus",
                                            innerStyle: "padding: 5px;line-height: 1.3; font-weight: bold"
                                        }).addEvents({
                                            focus: function() {
                                                $("loginBox").setStyle("background", "#fff url(/img/top_grad_2.gif) repeat-x");
                                            }
                                        });
                                    }
                                }
                            });
                        }).delay(1000); // delay for animation
                    }
                }).request();




            }
            else {
                window.location.href = this.getProperty("href");
            }
        }
    }); // end addEvents
}, attachReviewEvents = function() {
    [
        "BV_TrackingTag_Rating_Summary_1_WriteReview_",
        "BV_TrackingTag_Rating_Summary_2_WriteReview_",
        "BV_TrackingTag_Review_Display_WriteReview",
        "BV_TrackingTag_Review_Display_AddPositiveFeedback_",
        "BV_TrackingTag_Review_Display_AddNegativeFeedback_",
        "BV_TrackingTag_Review_Display_Inappropriate_"
    ].each(function(ln) {
        var L = document.getElements("a[name^="+ln+"]");
        if (L) {
            attachEvents(L);
        }
    });
}; // end attachReviewEvents

var AU = false, BVisLoaded = false, ratingsDisplayed = function(totalReviewsCount, avgRating, ratingsOnlyReviewCount, recommendPercentage, productID) {
    if (totalReviewsCount > 0) {
        var bvRevCntr = $("BVReviewsContainer");
        if (bvRevCntr)
            bvRevCntr.setStyle("display", "block");
    }
    attachReviewEvents();
}, BVcheckLoadState = function() {
    if(!BVisLoaded) {
        var page = $('BVFrame').getProperty("src");
        $('BVFrame').setProperty("src", 'http://reviews.webtogs.co.uk/"+staging+"/logging?page=' + escape(page));
        $('BVReviewsContainer').setHTML('<!-- Review retrieval timed out -->');
    }
};
// end bazaar functions


Element.extend({
    zoomer: function() {
        var garbageCollect, zoomed = false;

        this.removeEvent("mousemove");

        if ($("zoomLarger")) {
            $("zoomLarger").dispose();
            // C.log("disposed larger");
        }
        if ($("zoomer")) {
            $("zoomer").dispose();
            //C.log("disposed");
        }

        $("product_buyout_pane").setStyle("border", 0);
        var _this = this, coords = this.getCoordinates(), zoomer, zoomDimensions = {
            width: 127,
            height: 88,
            maxRight: coords.right - 127,
            maxBottom: coords.bottom - 88
        }, buyOut = $("product_buyout_pane").getCoordinates();

        zoomLarger = new Element("div", {
            id: "zoomLarger"
        }).setStyles($merge({
            height: 324,
            border: "1px solid #000",
            position: "absolute",
            display: "none"
        }, buyOut)).setStyle("width", buyOut.width - 2).injectInside(document.body);

        $("product_buyout_pane").setStyle("border", "1px solid #ccc");

        var largerImage = this.getProperty("src").replace("full", "max");
        new Asset.image(largerImage, {
            onload: function() {
                var AR = 3.75;
                // C.log("loaded ", largerImage);
                zoomLarger.setStyle("background",  "#fff url(" +largerImage+ ") no-repeat");

                _this.addEvents({
                    mousemove: function(e) {
                        if (!this.getProperty("data-zoomer"))
                            return false;

                        // where do we put it?
                        var adjY = window.getScrollTop() + e.clientY, adjX = window.getScrollLeft() + e.clientX;

                        newPos = {
                            left: (adjX - zoomDimensions.width / 2 > zoomDimensions.maxRight) ? zoomDimensions.maxRight : adjX - zoomDimensions.width / 2,
                            top: (adjY - zoomDimensions.height / 2 > zoomDimensions.maxBottom) ? zoomDimensions.maxBottom : adjY - zoomDimensions.height / 2
                        };

                        if (newPos.left < coords.left)
                            newPos.left = coords.left;

                        if (newPos.top < coords.top)
                            newPos.top = coords.top;

                        if ($("zoomer"))
                            zoomer = $("zoomer").setStyle("display", "block");
                        else
                            zoomer = new Element("div", {
                                id: "zoomer"
                            }).setStyles({
                                position: "absolute",
                                zIndex: 100000000+1,
                                width:zoomDimensions.width,
                                height:zoomDimensions.height,
                                // "background-image": "url(/img/polka.gif)",
                                background: "#ccc",
                                border: "1px solid #fff"
                            }).setOpacity(.3).injectAfter(this).addEvents({
                                mousemove: function(e) {
                                    $clear(garbageCollect);
                                    var adjY = window.getScrollTop() + e.clientY, adjX = window.getScrollLeft() + e.clientX;

                                    newPos = {
                                        left: (adjX - zoomDimensions.width / 2 > zoomDimensions.maxRight) ? zoomDimensions.maxRight : adjX - zoomDimensions.width / 2,
                                        top: (adjY - zoomDimensions.height / 2 > zoomDimensions.maxBottom) ? zoomDimensions.maxBottom : adjY - zoomDimensions.height / 2
                                    };


                                    if (newPos.left < coords.left)
                                        newPos.left = coords.left;

                                    if (newPos.top < coords.top)
                                        newPos.top = coords.top;

                                    this.setStyles(newPos);
                                    zoomed = true;

                                    // now larger one...
                                    zoomLarger.setStyles({
                                        backgroundPosition: "-" + (newPos.left-coords.left) * AR+"px -" + (newPos.top-coords.top) * AR + "px"
                                    });

                                },
                                mouseleave: function() {
                                    this.setStyle("display", "none");
                                    zoomLarger.setStyle("display", "none");
                                    zoomed = false;
                                }
                            });

                        zoomed = true;
                        zoomer.setStyles(newPos)

                        zoomLarger.setStyle("display", "block");

                    }, // mousemove
                    mouseleave: function() {
                        garbageCollect = (function() {
                            if (!zoomed) {
                                if (zoomer)
                                    zoomer.setStyle("display", "none");
                                zoomLarger.setStyle("display", "none");
                            }
                        }).delay(200); // 1 sec garbage collector.
                    }
                }); // events
            } // onload
        });


    }
});


var load_method = (window.ie ? 'load' : 'domready');
window.addEvent(load_method, function() {

    var PH = $("product_heading_title");
    var reduceTitle = function() {
        var PHh1 = PH.getFirst(), fontSize = 18, currentSize = PH.getStyle("height").toInt();
        if (currentSize <= 23)
            return false;

        while (currentSize > 23) {
            fontSize--;
            PHh1.setStyle("font-size", fontSize + "px");
            currentSize = PH.getStyle("height").toInt();
            // C.log(PH.getStyle("height").toInt());
        }

        PH.setStyle("height", 23);

    }

    if ($("product_heading_title"))
        reduceTitle();

    $$(".recentProducts").addEvents({
        click: function() {
            window.location.href = this.getProperty("data-url");
        },
        mouseenter: function() {
            this.setStyle("border", "1px solid #000");
        },
        mouseleave: function() {
            this.setStyle("border", "1px solid #fff");
        }
    }).addClass("cur");


    $("product_buyout_pane").addEvents({
        mouseenter: function() {
           this.setStyle("border", "1px solid #000");
        },
        mouseleave: function() {
           this.setStyle("border", "1px solid #ccc");
        }
    });

    if ($("productImage").getProperty("data-zoomer") == "1")
        (function() {
            $("productImage").zoomer();
        }).delay(1000);


    // cdc
    var checkSum = $("priceSwap").getProperty("value") + $("deliveryCountry").getProperty("value");
    var cdcDelay = 0, csc = $("changeShippingSource").innerHTML;
    if (!$("cdc"))
        cdcDelay = 2000;

    $("changeShippingSource").dispose();

    (function() {
        $("cdc").addEvents({
            click: function(e) {
                new Event(e).stop();
                currencySwap.openSwapper(this);
            }
        }).addClass("curImage");
    }).delay(cdcDelay);

    // rest
    if ($("sizingchart"))
        $("sizingchart").addEvent("click", function() {
            charts.sizeChart(this, this.getProperty("data-id"));
        });


    $("CS").addEvent("click", function() { continueShopping() }).addClass("curImage");


    // seo shuffle...
    $$("div.seo").each(function(el) {
        el.replaceWith($(el.getProperty("id").replace(/_container/, ""))).setStyle("display", "block");
    });

    $E("h1").remove();

    Cookie.remove("basketAB");



});
