var togBasket = {
    // namespace wrapper for the shopping basket
    contents: Cookie.get("basket"),
    add: function(product, version, qtty) {
        // add a product to basket
        if (this.contents !== false) {
            // basket has items?
            var basketItems = this.contents.split(","), newBasket = '';

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

            // already in there?
            if (!basketItems.toString().contains(product + "-" + version + "-"))
                this.contents = product + "-" + version + "-" + qtty + "," + this.contents;
        }
        else {
            // make a new one
            this.contents = product + "-" + version + "-" + qtty + ",";
        }

        // save this
        this.freshen();
        return this;
    },
    freshen: function() {
        // commit to cookie
        Cookie.remove("basket");
        Cookie.set("basket", this.contents, {path: "/", duration: 365});
        return this;
    },
    remove: function(product, version, qtty) {
        // remove an exact product from basket
        this.contents = this.contents.replace(product + "-" + version + "-" + qtty + ",", "");
        this.freshen();
        return this;
    }
};


var Form = {
    // wrapper class for form element values
    getValue: function(name) {
        if ($type(name) == "object")
            return name.getProperty("value");

        var elems = $$('input[name='+name+'], select[name='+name+'], textarea[name='+name+']');
        var value = false;
        elems.each(function(el) {
            if ($(el).getValue()) {
                value = $(el).getValue();
            }
        });
        return value;
    },
    setValue: function(name, value) {
        if ($type(name) == "object")
            name.setProperty("value", value);

        var elems = $$('input[name='+name+'], select[name='+name+'], textarea[name='+name+']');
        elems.each(function(el) {
            if (value != false)
                $(el).setProperty("value", value);
        });
    }
};



$F = Form.getValue;
$f = Form.setValue;

var Empty = {
    // wrapper class for element innerHTML emptying workaround for IE
    doEmpty: function(obj) {
        if ($type(obj) == false)
            return false;

        if (!window.ie) {
            obj.empty();
        }
        else {
            obj.setStyles({"display": "inline", "float": "left", "margin": "0px"}).empty();
        }
    }
}

$empty = Empty.doEmpty;

var Watermark = {
    initialize: function(etarget, esource, options, styles) {
        var coords = etarget.getCoordinates();
        var wm = esource.clone();
            wm.cloneEvents(esource).setStyles({
                "position": "absolute",
                "float": "left",
                "z-index": 10000,
                "left": parseInt(coords['left']) + parseInt(coords['width']) - options.xoffset+ "px",
                "top": parseInt(coords['top']) + options.yoffset + "px"}).setStyles(options.styles)
            .addClass("wm")
            .setProperties({alt: Json.toString({xoffset: options.xoffset, yoffset: options.yoffset}),rel: etarget.id})

            .injectInside(etarget.getParent());
            window.addEvent("resize", Watermark.move);
    },
    move: function() {
        // need to reposition on window.resize
        $$("img.wm").each(function(el) {
            // var coords = etarget.getCoordinates();
            var options = Json.evaluate(el.getProperty("alt"));
            var coords = $(el.getProperty("rel")).getCoordinates();
            el.setStyles({
                "left": parseInt(coords['left']) + parseInt(coords['width']) - options.xoffset+ "px",
                "top": parseInt(coords['top']) + options.yoffset + "px"
            });
        });
    },
    hide: function() {
        $$("img.wm").each(function(el) {
            el.setStyle("display", "none");
        });
    },
    unhide: function() {
        $$("img.wm").each(function(el) {
            el.setStyle("display", "block");
        });
    }
};
$W = Watermark.initialize;


var AjaxLoader = new Class({
    options: {
        zIndex: 1000000,
        loaderImage: "/img/ajax-loader.gif",
        background: "#fff",
        opacity: .7,
        loaderLeft: "center",
        loaderTop: "center",
        loaderAutoTop: true,
        loaderAutoTopMargin: "140px"
    },
    initialize: function(options) {
        this.setOptions(options);
        new Asset.image(this.options.loaderImage); // cache it.
    },
    make: function(el) {
        this.element = $(el);
        this.coords = this.element.getCoordinates();
        if (this.options.loaderAutoTop === true)
            this.options.loaderTop = (this.coords.height > 434) ? this.options.loaderAutoTopMargin : "center";

        this.loader = new Element("div").setStyles($merge({
            position: "absolute",
            zIndex: this.options.zIndex,
            opacity: this.options.opacity,
            background: this.options.background + " url(" + this.options.loaderImage + ") no-repeat " + this.options.loaderLeft + " " + this.options.loaderTop
        }, this.coords)).inject($(document.body));

        el.loader = this.loader;
    },
    remove: function() {
        if (this.loader)
            this.loader.dispose();
    },
    removeFromElement: function(el) {
        if (el.loader)
            el.loader.dispose();
    }
});

AjaxLoader.implement(new Options, new Events);



var winSizes = {};
var menuEvents = function() {
    if ($("SC")) {
        $("SC").addEvent("click", function(e) {
            new Event(e).stop();
            ShowCategories();
        });
    }

    if ($("PC")) {
        $("PC").addEvent("click", function(e) {
            new Event(e).stop();
            ShowPage();
        });
    }

    var searchField = $("searchfield");
    if (searchField) {
         searchField.addEvents({
            "focus": function() {
                if (this.getValue() == 'Type your search here...') {
                    this.setProperty("value", '').setStyle('fontStyle', 'normal');
                }
            },
            click: function() {
                if (this.getValue() == 'Type your search here...') {
                    this.setProperty("value", '').setStyle('fontStyle', 'normal');
                }
            }
         });

         $("searchButton").addEvents({

            "click": function() {
                if (searchField.getProperty("value").length) {
                     if (searchField.getProperty("value") == 'Type your search here...' || searchField.getProperty("value").trim() == '') {
                         simpleBubble(searchField, "Please type<br />keywords here");
                         searchField.setProperty("value", "").fireEvent("focus");

                         return false;
                     }

                     $("searchForm").submit();
                } else {
                     return false;
                }
            }
        }).addClass("curImage");

        var completer = new Autocompleter.Ajax.Json(searchField, "/searchAjax.php", {
            customTarget: $("searchSuggest"),
            ajaxOptions: {
                "method": "get"
            },
            "minLength": 3,
            'postVar': 'q',
            'onRequest': function(el) {
                searchField.addClass("search_ing");
            },
            'onComplete': function(el) {
                searchField.removeClass("search_ing");
            },
            "onSelect": function(el, choice) {
                var choiceURL = choice.getProperty("rel");

                if (choiceURL)
                if (choiceURL.length) {
                    toggleModal("#fff");
                    window.location.href = choiceURL;
                    return false;
                }

                $("searchButton").fireEvent("click");

            }
        });

        if (window.ie6 && $("main")) {
            var sorter = $("main").getElement("div.sorter");

            if (sorter)
            sorter.setStyles({
                "float": "left",
                "margin-left": 10
            });
        }

    }

    if ($("knobRail")) {
        var range = Json.evaluate($("knobRail").getProperty("data-pos"));

        range = $merge({
            min: range.min,
            max: range.max,
            minPos: $("knobKnob").getProperty("data-pos").toFloat(),
            maxPos: $("knobKnobMax").getProperty("data-pos").toFloat()
        }, range);

        var allowSubmit = false;

        var mySlide = new Knobs($('knobRail'), $('knobKnob'), $('knobMid'), {
            start: range.min,
		    end: range.max,
		    offset:0,
		    snap: false,
		    max: 142,
		    numsteps: (range.max - range.min) / 5,
        	onChange: function(pos) {
        	    allowSubmit = true;
        	    $('minMoney').setHTML("&pound;" + pos.minpos);
        	    $('maxMoney').setHTML("&pound;" + pos.maxpos);
        	},
        	onComplete: function(pos) {
        	    if (this.hasSetup < 2)
        	        return;
                this.showMid();

                $data = {
                    a: "applyPriceFilter",
                    t: $("priceHeading").getProperty("data-type"),
                    min: pos.minpos,
                    max: pos.maxpos,
                    filters: $("knobRail").getProperty("data-filters"),
                    price: (pos.minpos == range.min && pos.maxpos == range.max) ? false : true
                };

        	    ajl.make($("main"));

        	    new Ajax("/accountAjax.php", {
        	        method: "get",
        	        data: $data,
        	        onComplete: function() {
        	             window.location.href = this.response.text;
        	        }
        	    }).request();
        	}

        }, $('knobKnobMax')).setMin(range.minPos).setMax(range.maxPos);
    }

    if ($("priceHeading")) {
        $("priceHeading").addEvents({
            click: function(e) {
                new Event(e).stop();

                if (this.hasClass("catChoiceOn"))
                    return false;

                this.addClass("catChoiceOn");

                ajl.make($("main"));
                window.location.href = this.getProperty("data-any");
            }
        });

    }
};

var cdn = 'https:' == document.location.protocol ? "https://cdn.webtogs.com/" : "http://cdn.webtogs.com/";

// sex icons
var icons = [cdn + "img/icons/male.gif", cdn + "img/icons/female.gif"];


var doSeal = function(targetObject) {
    // show thawte seal code w/o the reference to their exe in a dom compliant way
    var sealLoc = "https://seal.thawte.com/thawtesplash?form_file=fdf/thawtesplash.fdf&dn=WWW.WEBTOGS.CO.UK&lang=en";
    new Asset.image("https://seal.thawte.com/getthawteseal?at=0&sealid=0&dn=WWW.WEBTOGS.CO.UK&lang=en&gmtoff=0", {id: 'sealimage'})
        .injectInside(targetObject)
        .addClass("curImage")
        .setProperty("title", "click to verify")
        .addEvent("click", function() {
            window.open(sealLoc,'ga3ef4eb41dcac740b918440eb9cd19c8','height=500,width=516,scrollbars=yes,status=1');
        })
} // end doSeal


var basketEvents = function() {
    if ($("SBL"))
        $("SBL")
        .addEvent("mouseenter", showBasket)
        .addEvent("mouseleave", function() {
            (function() {
                if ($("flyBasketC").getProperty("rel") != "inline") hideBasket();
            }).delay(2000);
        })
} // end basketEvents;


var fadeGender = function(gender) {
    $$("."+gender).each(function(el) {
        var fakeDiv = new Element('div', {"class": "polka"});
        var pos     = el.getCoordinates();

        // dots animation is slow on ie, just fade out.
        if (window.ie)
            fakeDiv.setOpacity(0.3).setStyle("background", "#fff");
        else
            fakeDiv.setStyle("background-image", "url(/img/polka.gif)");

        fakeDiv.setStyles({
            "z-index": 1000,
            "position": "absolute",
            "top": pos["top"],
            "left": pos["left"],
            "width": el.getStyle("width"),
            "height": el.getStyle("height")
        }).injectAfter(el);
    });
}; // end fadeGender

var genderEvents = function(sURL) {
    // setup gender change

    $$("a.genderPick").each(function(el) {
        if (el.getNext().getText() == "(0)") {

            var safer = new Element("span").setText(el.getText()).setStyles({
                color: "#777"
            }).injectBefore(el)
            el.dispose();
            return;
        }

        el.addEvents({
            click: function(e) {
                new Event(e).stop();
                ajl.make($("main"));

                var newGender = this.getText(), cookieVal = (newGender == "Women's") ? "female" : "male";

                var goToURL = window.location.href;
                goToURL = goToURL.replace(/Womens_/i, "");
                goToURL = goToURL.replace(/Mens_/i, "");
                goToURL = (cookieVal == "male") ? goToURL.replace(".co.uk/", ".co.uk/Mens_") : goToURL.replace(".co.uk/", ".co.uk/Womens_")


                window.location.href = goToURL;
            }
        });
    });

    if ($("uniselect"))
        $("uniselect").addEvents({
            click: function(e) {
                new Event(e).stop();
                if (this.hasClass("catChoiceOn"))
                    return;

                this.addClass("catChoiceOn");
                ajl.make($("main"));

                var cookieVal = "unisex";
                Cookie.remove("gender");
                Cookie.set("gender", cookieVal, {duration: 365, path: "/"});

                var goToURL = window.location.href;
                goToURL = goToURL.replace(/Womens_/i, "");
                goToURL = goToURL.replace(/Mens_/i, "");
                window.location.href = goToURL;
            }

        });

} // end genderEvents

var ShowCategories = function() {
    // display the categories and hide search...
    $("page_navigation").setStyle("display", "block");
    $("result_interpretation").setStyle("display", "none");
    $("SM").setStyle("display", 'none');
    $("SB").setStyle("display", 'none');
    $("PM").setStyle("display", 'block');
    if ($("top10sellers"))
        $("top10sellers").setStyle("display", "none");
    (function() {Watermark.move()}).delay(200);
} // end ShowCategories

var ShowPage = function() {
    // show the page results and hide the category
    $("page_navigation").setStyle("display", "none");
    $("result_interpretation").setStyle("display", "block");
    $("SM").setStyle("display", 'block');
    $("SB").setStyle("display", 'none');
    $("PM").setStyle("display", 'none');
    if ($("top10sellers"))
        $("top10sellers").setStyle("display", "block");
    Watermark.move();
} // end ShowPage


var toggleModal = function(backgroundColour, options) {
    // modal view for the whole screen
    // ver 2.02 for 1.11, 20/08/2009 10:55:11
    // returns the $("modal") div as element.
    if ($("modal")) {
        $("modal").dispose();
        return false;
    }

    var options = $merge({
        zIndex: 10000000,
        opacity: .8,
        events: $empty()
    }, options);

    if (!$type(backgroundColour) && !$("modal"))
        return false;

    return new Element("div", {
        id: "modal"
    }).setStyles({
        position: "absolute",
        top: 0,
        left: 0,
        width: window.getScrollWidth(),
        height: window.getScrollHeight(),
        background: backgroundColour,
        "z-index": options.zIndex
    }).setOpacity(options.opacity).addEvents(options.events).inject(document.body);
}; // end toggleModal

var getABasket = function() {
    // get ajax basket
    var mj = new Ajax("/BasketAjax.php?a=reload", {method: "get", update: $("flyBasketC")}).request();
} // end getABasket

var basketSummary = function() {
    // prints the basket summary
    var mj = new Ajax("/BasketAjax.php?a=summary", {
        update: $("FB"),
        method: "get",
        onComplete: function() {
            basketEvents();
        }
    }).request();
} // end basketSummary

var continueShopping = function() {
    // gets a page via ajax and redirects to it.
    var mj = new Ajax("/index.php?a=continue", {
        method: "get",
        onComplete: function() {
            window.location.href = unescape(mj.response.text);
        }
    }).request();
} // end continueShopping


var myWhat = function(what, message, options) {
    var options = $merge({
        offsetY: 16,
        offsetX: 0,
        width: 260
    }, options);

    // open up a popup for text
    var coords  = what.getCoordinates();
    new Element("div", {"class": "what", id: "myWhat"}).setStyles({
        top: coords.top+options.offsetY,
        left: coords.left+options.offsetX,
        width: 260
    }).setHTML(message).inject(document.body);

    what.addEvent("mouseleave", function() {
        //what.removeEvents();
        myDestroy("myWhat");
    });
} // end myWhat

var myImage = function(what) {
    // open up a popup for a larger image
    myDestroy("myImage");

    var coords  = what.getCoordinates();
    var popup   = new Element("div");
        popup.setStyles({
            "position": "absolute",
            "top": parseInt(coords["top"]+20)+"px",
            "left": parseInt(coords["left"]+184)+"px",
            "border": "1px solid #000",
            "background": "#ffffff",
            "display": "none",
            "z-index": 100000
        })
        .setProperty("id", "myImage")
        .inject(document.body);

    var image = new Element("img");
        image.setProperty("src", what.getProperty("rel")).setStyle("border", 0).injectInside(popup);

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

    // var mw = what.getProperty("id");
    what.addEvent("mouseleave", function() {
        myDestroy("myImage");
    });
} // end myImage

var myDestroy = function(what) {
    // remove any image layers left out
    if ($(what)) {
        $(what).remove();
    }
}

var myEventBubble = function(what, message) {
    // open up a pink bubble popup for text
    myDestroy("myBubble");


    var coords  = what.getCoordinates();
    var popup   = new Element("div");
    popup.setStyles({
        "position": "absolute",
        "top": parseInt(coords["top"]-56)+"px",
        "left": parseInt(coords["left"]-118)+"px",
        "display": "inline"
    })
    .addClass("bubble")
    .setProperty("id", "myBubble")
    .setHTML(message)
    .inject(document.body);

    what.addEvent("mouseleave", function() {
        myDestroy("myBubble");
    });
} // end myEventBubble

var simpleBubble = function(what, message, dobg) {
    // open up a pink bubble popup for text
    myDestroy("myBubble");
    var coords  = what.getCoordinates();
    var popup   = new Element("div");
    popup.setStyles({
        "position": "absolute",
        "top": parseInt(coords["top"]-56)+"px",
        "left": parseInt(coords["left"]-118)+"px",
        "display": "inline"
    })
    .addClass("bubble")
    .setProperty("id", "myBubble")
    .setHTML(message)
    .inject(document.body);


    (function() {
        myDestroy("myBubble");
        if (dobg != false)
            what.setStyle('background', '#fff');
    }).delay(3000);

} // end simpleBubble


var brandScroller = function(options) {
    // brand scroller for mootools 1.1
    window.addEvent("domready", function() {
        var gallery = $('gallery'), progress = $('progressReport');
        var moveDirection   = "Right";
        var moveTimer;
        var moveDelay = options.moveDelay;
        var moveSteps = options.moveSteps;
        var moveRight = function() {
            moveDirection = "Right";
            var el = gallery.getSize();
                gallery.scrollTo(parseInt(el.scroll.x+moveSteps),0);
            var el = gallery.getSize();

            if ((el.scroll.x + el.size.x)>= el.scrollSize.x) {
                $clear(moveTimer);
                moveTimer = moveLeft.periodical(moveDelay);
            }
        } // end moveRight
        var moveLeft = function() {
            moveDirection = "Left";
            var el = gallery.getSize();
                gallery.scrollTo(el.scroll.x-moveSteps,0);
            var el = gallery.getSize();

            if (el.scroll.x <= 0) {
                $clear(moveTimer);
                moveTimer = moveRight.periodical(moveDelay);
            }
        } // end moveLeft
        var moveStop = function() {
            $clear(moveTimer);
        }
        var moveResume = function() {
            $clear(moveTimer);
            progress.setHTML('Click on a logo to see the gear ');
            moveTimer = eval("move"+moveDirection+".periodical(moveDelay)");
        } // end moveResume
        // get it moving!
        progress.setHTML("Loading " + options.brandArray.length + " logos, please wait...");
        options.brandArray.each(function(el, i) {
            var myBrand = new Asset.image("http://cdn.webtogs.com/brands75/" + el.image, {title: "View gear from " + el.brand});
                myBrand
                   .addClass("curImage")
                   .addEvent("click", function() { window.location.href = el.url; })
                   .addEvent("mouseenter", function() {
                        progress.setHTML(this.getProperty("title"));
                        this.setOpacity(1);
                   })
                   .addEvent("mouseleave", function() { this.setOpacity(.9); })
                   .injectInside(gallery);
            if (i < options.brandArray.length) {
                progress.setHTML("<img src='/img/tiny_red.gif' border='0' /> " + i + ' brands loaded...');
            }
            else {
                progress.setHTML('Click on a logo to see the gear');
            }
        }); // each
        $('galleryc').setStyles({"visibility": "visible", "opacity": 0.1});
        var fx = new Fx.Styles('galleryc', {duration: 1000});
            fx.start({opacity: 1}).chain(function() { moveResume(); progress.setHTML('Click on a logo to see the gear'); });
        gallery.addEvent("mouseleave", moveResume).addEvent("mouseenter", moveStop);
    }); // addEvent domready
} // end brandScroller

Element.extend({
    getHTML: function() {
        return this.innerHTML;
    },
    modalBox: function(options) {
        var options = $merge({
            width: 400,
            height: 300,
            title: "",
            titleClass: "modalTitle",
            close: true,
            modal: true,
            shadow: true,
            scroll: false,
            modalColour: "#fff",
            text: "",
            textFunction: false,
            id: "modalBox",
            innerPadding: 10,
            movable: false,
            callback: function() {

            },
            onClose: function() {

            }
        }, options);



        // make the box.
        var coords = this.getCoordinates(), modalBox = new Element("div", {
            id: options.id
        }).setStyles({
            width: coords.width,
            height: coords.height, // + "px !important",
            left: coords.left,
            top: coords.top,
            position: "absolute",
            border: "1px solid #000",
            background: "#fff url(/img/top_grad_2.gif) repeat-x",
            "z-index": 1000000000
        }).injectInside(document.body), myfx = new Fx.Styles(modalBox, {
                transition: Fx.Transitions.Sine.easeOut,
                duration: 300
        }), modalPos = centerBox(options.width,options.height);


        var closeModalBox = function() {
            myfx.stop();
            if (options.modal && $("modal")) {
                // $("modal").fade(.8, 0);
                $("modal").smartDispose();
            }

            if ($(options.id))
                 $(options.id).smartDispose();


            $$(".what3").smartDispose();

            options.onClose.attempt();
        };

        if (options.modal)
            toggleModal(options.modalColour).addEvents({
                click: function() {
                    closeModalBox();
                }
            });

        var modalTitle = new Element("div", {
            id: "modalTitle",
            "class": "left " + options.titleClass
        }).injectTop(modalBox);

        var modalBody = new Element("div", {
            id: "modalBody"
        }).setStyles({
            height: options.height - 48
        }).injectInside(modalBox);



        myfx.start({
            height: options.height,
            width: options.width,
            left: modalPos.left,
            top: modalPos.top
        }).chain(function() {
            if (options.scroll) {
                modalBody.setStyles({
                    "overflow-y": "scroll",
                    "overflow-x": "none"
                });
            }

            if (options.shadow) {
                if (window.ie)
                    modalBox.dropShadow();
                else
                    modalBox.addClass("shadowy");
            }

            if (options.close)
                new Asset.image("/img/modal_close2.gif", {
                    onload: function() {
                        this.injectTop(modalBox).addClass("curImage").addClass("right").setOpacity(1).setStyles({
                            paddingTop: 3, paddingRight: 3, border: 0
                        }).setProperties({
                            "title": "click to close",
                            "id": "modalClose"
                        }).addEvents({
                            click: function() {
                                this.removeEvents();

                                //(function() {
                                    closeModalBox();
                                //}).delay(500);
                            } /*,
                            mouseenter: function() {
                                this.fade(.6, 1, {reclaim: false, remove: false});
                            },
                            mouseleave: function() {
                                this.fade(1, .6, {reclaim: false, remove: false});
                            }
                            */
                        });
                    }
                });

            var adjustedWidth = (options.close) ? 58 : 0;
            modalTitle.setHTML(options.title).setStyles({
                width: options.width - adjustedWidth,
                cursor: (options.movable) ? "move" : "default"
            });

            // new Element("br").setStyles({"clear": "both"}).injectAfter(modalTitle);

            modalBody.setStyles({padding: options.innerPadding, clear: "both"}).setHTML(options.text);
            options.callback();

            // movable.
            if (options.movable) {
                new Drag.Move(modalBox, {
                    handle: modalTitle,
                    onStart: function() {
                        if (options.shadow && window.ie) {
                            var rel = modalBox.getProperty("data-related");
                            if ($(rel))
                                $(rel).remove();
                        }
                    },
                    onComplete: function() {
                        if (options.shadow && window.ie) {
                            modalBox.dropShadow();
                        }
                    }
                });
            }
        });

    }, // end modalBox...
    smartDispose: function() {
        // dispose of an element and its dropShadow (if there is one)
        var rel = this.getProperty("data-related");
        if ($(rel)) {
            $(rel).dispose();
        }

        if (this.parentNode)
            this.dispose();
    }, // end smartDispose
    dropShadow: function(options) {
        // creates a shadow effect to a rectangular element

        // define defaults
        var options = $merge({
            id: "dropShadow" + $random(100,1000),
            x: 3, // offset from parent
            y: 3,
            border: "1px solid #000",
            background: "#555",
            opacity: .5,
            zIndex: this.getStyle("z-index").toInt() - 1 // behind parent
        }, options);

        // only apply shadow on absolutely positioned elements
        if (this.getStyle("position") != "absolute")
            return this;

        var c = this.getCoordinates();

        new Element("div", {
            id: options.id
        }).setStyles({
            position: "absolute",
            left: c.left + options.x,
            top: c.top + options.y,
            width: c.width,
            height: c.height,
            background: options.background,
            zIndex: options.zIndex
        }).setOpacity(0).injectBefore(this).fade(0, options.opacity, {reclaim: false, remove: false});

        // store the shadow id into the element
        this.setProperty("data-related", options.id);

        return this;
    }, // end dropShadow
    simpleBox: function(message, options) {
        var options = $merge({
            offsetY: 16,
            offsetX: 0,
            width: 260,
            closeEvent: "mouseleave",
            background: "#fff"
        }, options);

        // open up a popup for text
        var coords  = this.getCoordinates();
        new Element("div", {"class": "what", id: "myWhat"}).setStyles({
            top: coords.top+options.offsetY,
            left: coords.left+options.offsetX,
            width: options.width,
            background: options.background,
            position: "absolute"
        }).setHTML(message).inject(document.body);

        if (options.closeEvent != false)
            this.addEvent(options.closeEvent, function() {
                if ($("myWhat"))
                    $("myWhat").dispose();
            });
    },
    tooltip: function(what, options) {
        // apple style tooltip
        var _this = this, coords = _this.getCoordinates(), options = $merge({
            eventEnd: "mouseleave",
            eventEndTrigger: _this,     // parent element or self
            topOffset: 90,             // offset when in full view
            topStartOffset: 100,        // offset for animation start
            opacity: .8,                // target opacity in full view
            className: "tooltip",       // linked to css
            morphOptions: {
                duration: 300,
                transition: Fx.Transitions.Sine.easeOut
            },
            style: $empty(),
            delay: 0,                    // can dispose on a timer, in seconds
            id: "tt_" + $random(100, 1000),
            innerStyle: "padding:20px; line-height: 18px"
        }, options);

        if ($type(_this.tip) != "element") {
            this.tip = new Element("div", {
                "class": options.className,
                id: options.id
            });
        }

        options.style = $merge({
            left: coords.left + coords.width / 2
        }, options.style);
        this.tip.setStyles(options.style).setOpacity(0).setHTML("<div style='"+ options.innerStyle + "'>"+what+"</div>").inject(document.body);

        this.morph = new Fx.Styles(this.tip, options.morphOptions).start({
            opacity: options.opacity,
            top: [coords.top - _this.tip.getSize().size.y - options.topStartOffset, coords.top - options.topOffset]
        });

        var closeAnimation = {
            opacity: 0,
            top: coords.top - _this.tip.getSize().size.y - options.topStartOffset
        }

        this.tip.setProperty("data-close", Json.toString(closeAnimation));
        if (options.delay === 0) {
            options.eventEndTrigger.addEvent(options.eventEnd, function(e) {
                this.morph.stop();
                _this.tipaway(closeAnimation);
            });
        }
        else {
            (function() {
                if (this.tipaway)
                this.tipaway(closeAnimation);
            }).delay(options.delay, this);
        }
        return this;
    },
    tipaway: function(options) {
        if (this.tip) {
            this.morph.start(Json.evaluate(this.tip.getProperty("data-close")));
        }

        return this;
    },
    dispose: function() {
        if ($type(this) != false)
            this.remove();
    },
    slowFocus: function(options) {
        // don't focus straight away so user can read error bubble
        el = this;
        options = $merge({delay: 3000}, options);
        (function() {
            el.focus();

        }).delay(options.delay);
        return el;
    },
    fade: function(from, to, options) {
        var options = $merge({
            reclaim: true,
            remove: true,
            duration: 500
        }, options);

        var fadeobj = this;
        if (fadeobj.getStyle("display") == "none")
            fadeobj.setStyle("display", "inline");

        var fx = new Fx.Style(this, "opacity", {duration: options.duration, onComplete: function() {

            if (to == 0 && options.reclaim) {
                fadeobj.setStyle("display", "none");
            }
            if (options.remove == true) {
                return fadeobj.smartDispose();
            }
        }});
        fx.start(from, to);
        return this;
    },
    newFade: function(options) {
        var options = $merge({
            from: 1,
            to: 0,
            reclaim: true,
            remove: true
        }, options);

        var fadeobj = this;
        fadeobj.setProperty("removed", true);
        if (fadeobj.getStyle("display") == "none")
            fadeobj.setStyle("display", "inline");

        var fx = new Fx.Style(this, "opacity", {duration: 500, onComplete: function() {

            if (options.to == 0 && options.reclaim) {
                fadeobj.setStyle("display", "none");
            }
            if (options.remove == true) {
                return fadeobj.remove();
            }
        }});
        fx.start(options.from, options.to);
        return this;
    },
    fieldError: function(error_title, body, options) {
        if ($("error"+this.getProperty("id")))
            $("error"+this.getProperty("id")).dispose();

        var options = $merge({
            left: 0,
            top: -5,
            position: "relative",
            marginLeft: 0,
            errorClass: "account_input_error",
            doEvents: true
        }, options);

        var el = this;
        var error_message = new Element("div", {
            "id": "error"+this.getProperty("id"),
            "class": "error_state_wrap"
        }).setHTML('<div class="error_state"><div class="large">' + error_title + '</div><div class="small">' + body + '</div></div>')
        .setStyles({
            position: options.position,
            left: options.left,
            top: options.top,
            "margin-left": options.marginLeft
        })
        .injectAfter(this);

        if (options.doEvents == false)
            return this;

        this.addClass(options.errorClass).addEvent("focus", function() {
            if (error_message.getProperty("removed"))
                return false; // already removing...
            el.removeEvent("focus").removeClass(options.errorClass);
            error_message.newFade();
        });
        return this;
    }
}); // element

var IEactivateFlash = function() {
    $$("embed").each(function(el) {
        el.outerHTML = el.outerHTML;
    });
} // activate all embed controls.

if (window.ie)
window.addEvent("domready", function() {
    // activate flash
    IEactivateFlash();
});

var centerBox = function(width, height) {
    // returns coordinates for positioning
    var winSize = window.getSize(), winScroll = winSize.scroll, winSize = winSize.size, windowHeight = window.getScrollHeight()-1, coords = {
        top: winScroll.y + (winSize.y / 2) - (height / 2),
        left: winSize.x / 2 - width / 2,
        width: width,
        height: height
    }

    if (coords.top + height + 20 > windowHeight)
        coords.top = windowHeight - 20 - height;

    if (coords.top <= 0) {
        coords.top = 20;
    }

    return coords;
};


Number.extend({
    money: function(currency) {
        var amount = this.toFloat();
        amount = (Math.round(amount*100))/100;
        amount = (this == Math.floor(amount))
                    ? amount + '.00'
                    : ((amount*10 == Math.floor(amount*10))
                                ? amount + '0'
                                : amount);
        return ($type(currency) == "string") ? currency + amount : amount;
    }
});// end number extend

var validEmailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, isValid = function(email) {
    return email.test(validEmailRegex);
};

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")
            try {
                console.log.apply(this, arguments); // safari's console.log can't accept scope...
            } catch(e) {
                // so we loop instead.
                for (var i = 0, l = arguments.length; i < l; i++)
                    console.log(arguments[i]);
            }
        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.


// currency change
var currencySwap = {
    changed: false,
    isOpen: false,
    initialize: function() {
        this.changer = $("currencySwapper");
        if (!this.changer)
            return;

        this.source = $("ASDASD");
        if (!this.source)
            return;

        this.content = this.source.innerHTML;
        var _this = this;
        this.changer.getFirst().addEvents({
            click: function(e) {
                new Event(e).stop();

                if (_this.isOpen)
                    return false;

                _this.openSwapper(this);
            }
        }); // events
    },
    openSwapper: function(el) {
        this.isOpen = true;
        var _this = this;

        el.modalBox({
            width: 800,
            height: 170,
            title: "Set your currency and delivery preferences",
            titleClass: "modalTitle",
            close: true,
            modal: !true,
            shadow: true,
            scroll: false,
            modalColour: "#fff",
            text: "",
            textFunction: false,
            id: "modalBox",
            innerPadding: 10,
            movable: !false,
            callback: function() {
                // load content
                $("modalBody").setHTML(_this.content).setStyles({
                    textAlign: "center"
                });

                $("ASDASD").empty();

                $("currencyNotice").addEvents({
                    mouseenter: function() {
                        this.tooltip($("currencyTip").innerHTML, {
                            className: "what2 shadowy",
                            topOffset: -16,
                            topStartOffset: -250,
                            opacity: 1,
                            style: {
                                zIndex: 1000000000,
                                background: "#ffffcf"
                            },
                            innerStyle: "padding: 5px;line-height: 1.3"
                        });
                    },
                    click: function(e) {
                        var e = new Event(e).stop();
                    }
                });

                _this.addEvents();
            },
            onClose: function() {
                _this.isOpen = false;
                if (_this.changed === true) {
                    if ($("main"))
                        ajl.make($("main"));
                    else
                        toggleModal("#fff");
                    window.location.href = window.location.href;
                }
            }
        });
    },
    addEvents: function() {
        // currency change...
        var _this = this;
        $("priceSwap").addEvents({
            change: function() {
                var target = this.getProperty("value");
                Cookie.remove("currency");
                Cookie.set("currency", target, {duration: 7, path: "/"});
                _this.changed = true;
            }
        }); // end priceSwap change

        // target country change
        $("deliveryCountry").addEvents({
            change: function() {
                var newId = this.getProperty("value");
                if (newId == 0) {
                    Cookie.remove("deliveryCountry");
                    return false;
                }

                Cookie.remove("deliveryCountry");
                Cookie.set("deliveryCountry", newId, {duration: 7, path: "/"});
                _this.changed = true;
                console.log("changed");
            }
        });
    }
}; // end currency changer namespace



// ajax loader class
ajl = new AjaxLoader();


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

    var gender = Cookie.get("gender");
    if (gender != "male" && gender != "female") {
        var myStyleBorder = {border: "1px solid #ddd"};
        var male = new Asset.image(icons[0], {title: "Suitable for men"});
            male.addEvent("click", function(e) { new Event(e).stop(); if ($("gender_m")) $("gender_m").fireEvent("click"); }).addEvent("mouseenter", function() { this.setOpacity(1); }).addEvent("mouseleave", function() { this.setOpacity(.7);}).addClass("curImage").setOpacity(.7);
        $$("img.male").each(function(el) { $W(el, male, {xoffset: 20, yoffset: 3, "styles": myStyleBorder}); }); // end each

        var female = new Asset.image(icons[1], {title: "Suitable for women"});
            female.addEvent("click", function(e) { new Event(e).stop(); if ($("gender_m")) $("gender_f").fireEvent("click"); }).addEvent("mouseenter", function() { this.setOpacity(1); }).addEvent("mouseleave", function() { this.setOpacity(.7);}).addClass("curImage").setOpacity(.7);
        $$("img.female").each(function(el) { $W(el, female, {xoffset: 20, yoffset: 3, "styles": myStyleBorder}); }); // end each
    }

    var SI = $$("img.sale");
    if (SI.length > 0) {
        var SMark = new Asset.image(cdn + "img/icons/sale2.gif", {title: "Item is on sale"});
        SI.each(function(el) { $W(el, SMark, {xoffset: el.width, yoffset: 0}); }); // end each
    }

    var SI = $$("img.sale20");
    if (SI.length > 0) {
        var SMark = new Asset.image(cdn + "/img/icons/sale20.gif", {title: "Item is on sale with 20% off RRP"});
        SI.each(function(el) { $W(el, SMark, {xoffset: el.width, yoffset: 0}); }); // end each
    }

    var SI = $$("img.sale30");
    if (SI.length > 0) {
        var SMark = new Asset.image(cdn + "/img/icons/sale30.gif", {title: "Item is on sale with 30% off RRP"});
        SI.each(function(el) { $W(el, SMark, {xoffset: el.width, yoffset: 0}); }); // end each
    }

    var SI = $$("img.sale40");
    if (SI.length > 0) {
        var SMark = new Asset.image(cdn + "/img/icons/sale40.gif", {title: "Item is on sale with 40% off RRP"});
        SI.each(function(el) { $W(el, SMark, {xoffset: el.width, yoffset: 0}); }); // end each
    }


    if (window.ie6) {
        //  css selector of all images with a property src ending on "png"
        $$('img[src$=png]').each(function(img, i) {
            var oldParent = img.getParent();
            var oldId = img.id;
            img.setProperty("id", "old"+i);
            var imgID = "id='clone" + i + "' ";
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
            img.outerHTML = strNewHTML;
            $("clone"+i).cloneEvents(img).setProperties(img.getProperties('alt','rel','title','id'));
        }); // each
    }

    if ($("subscribe_email")) {
        $("subscribe_email").addEvent("click", function() {
            if (this.value == 'Enter your email address...') {
                this.setProperty("value",  "").setStyle("fontStyle", "normal");
            }
        });

        $("subscribe_email_go").addEvent("click", function() {
            if ($F("subscribe_email") == "Enter your email address..." || !$F("subscribe_email")) {
                simpleBubble($("subscribe_email"), "Please enter a<br />valid email");
                return false;
            }

            var mj = new Ajax("/accountAjax.php?a=bh&id="+$F("subscribe_email"), {
                method: "get",
                onComplete: function() {
                    eval(mj.response.text);
                }
            }).request();
        });
    }



    if (window.ie) {
        (function() {
            menuEvents();
        }).delay(1000);
    }
    else {
        menuEvents();
    }

    if (Cookie.get("EDM") == "show") {
        (function() {
            var topEffect = new Fx.Styles(new Element("div", {
                id: "topnotice"
            }).setHTML("<div style='float: left; text-align: center; font-weight: bold; padding-top: 5px;padding-left: 5px;'>Hi there, you can shop at webtogs as normal and we'll apply your 11% discount during checkout.</div><div id='closeNotice' class='closeNotice' style='float: right'>close</div><br clear='all'/>").injectTop(document.body), {
                duration: 1000,
                transition: Fx.Transitions.Sine.easeOut
            }).start({
                opacity: [0,1],
                top: [-150, 0]
            });
            Watermark.move();

            $("closeNotice").addEvents({
                click: function() {
                    topEffect.start({
                        opacity: [1,0],
                        top: [0, -20]
                    }).chain(function() {
                        Cookie.set("EDM", "hidden", {path: "/"});
                        $("topnotice").dispose();
                    });
                },
                mouseenter: function() {
                    this.addClass("closeNoticeOn");
                },
                mouseleave: function() {
                    this.removeClass("closeNoticeOn");
                }
            }).addClass("curImage");
        }).delay(500);
    }


    // sidemenu expand
    var $mytime;

    $$("div.catExpand").each(function(el) {
        var myId = el.getProperty("rel");
        el.addEvents({
            mouseenter: function() {
                $mytime = (function() {
                    this.addClass("catDown").removeEvents();

                    $$("div.catHide[rel="+myId+"]").each(function(sub) {
                        sub.setStyles({
                            "display": "block"
                        }).setOpacity(0).fade(0,1, {remove: false, reclaim: false});
                    });
                }).delay(500, this);

            },
            mouseleave: function() {
                $clear($mytime);
            }
        });

    });

    if ($("allsubs"))
        $("allsubs").addEvents({
            click: function(e) {
                this.getFirst().addClass("catChoiceOn");
                ajl.make($("main"));
            }
        });

    if ($("allbrands"))
        $("allbrands").addEvents({
            click: function() {
                this.getFirst().addClass("catChoiceOn");
                ajl.make($("main"));
            }
        });

    $$("div.navSize").each(function(el) {
        var link = el.getFirst(), size = link.getText(), url = link.getProperty("href");
        link.dispose();
        el.setText(size);
        el.addEvents({
            click: function() {
                ajl.make($("main"));
                $$("div.navSizeOn").removeClass("navSizeOn");
                this.addClass("navSizeOn").fade(0,1, {remove:0,reclaim:0});
                window.location.href = url;
            },
            mouseenter: function() {
                this.addClass("navSizeOver");
            },
            mouseleave: function() {
                this.removeClass("navSizeOver");
            }
        }).addClass("cur"); //.setHTML(size);
    });

    if ($("sizeHeading"))
        $("sizeHeading").getParent().addEvents({
            click: function(e) {
                ajl.make($("main"));
            }
        });

    currencySwap.initialize();

}); // domready


