var addthis_options = 'email, twitter, facebook, digg, google, delicious, stumbleupon, more', addthis_brand = "Shoe-Envy", addthis_config = {
    username: "ShoeEnvy"
};


var errorHandler = function(dbug) {
    // trap errors and send via ajax to a script that logs them
    new Request({
        url: "/errorTrap.php",
        data: dbug,
        onComplete: function() {
             // $("errorOutput").set("html", this.response.text);
        } // comment this function out out and the comma on the line above
    }).send();
    return true;
}; // end errorHandler

var freeDelivery = 34.99, slidingOptions = {
    topOffset: 84,
    timer: 3,
    id: "slider",
    opacity: 1.0
};

var checkStock = function() {
    // is it in or not...
    var AK = $("productOption").get("value"), NC = $E("div.size[rel="+AK+"]").get("data-nc");
    if (stock[AK] > 0) return true;
    if (NC > 0) return true;
    return false;
}

var announceStock = function() {
    if ($("productOption").get("value") == 0) {
        if ($("closeBubble"))
                $("closeBubble").fireEvent("click");

        return false;
    }
    //console.log(stock[$("productOption").get("value")]);
    if (stock[$("productOption").get("value")] <= 0) {
        var culprit = $E(".sizeSelected");
        if (culprit.get("data-nc") <= 0) {
            // $("SS").slidingTip("Sorry, this size is <br>currently out of stock.", slidingOptions).set("text", "Select size:").fade(0,1);

            $("bi").set("opacity", 1);
        }
        else {
            // can pre-order
            $("bi").set("opacity", 1);

            $("SS").slidingTipaway();

            var days = culprit.get("data-days"), exp = culprit.get("data-exp");

            if (!$("scare"))
            new Element("div", {
                id: "scare",
                styles: {
					width: 250,
                    background: "#ffeca8",
                    color: "#363636",
                    border: "1px solid #000",
                    padding: 3,
                    opacity: 0,
                    "line-height": "16px",
                    fontSize: "14px",
                    marginBottom: 10,
                    textAlign: "center"
                },
                html: "Available for <strong>pre-order</strong> today<br />Due with us " + ((days > 0) ? "on <strong>" + exp : "soon") + "</strong>."
            }).injectBefore($("ProdOptions")).fade(0,1);
        }

    }
    else {
        $("bi").set("opacity", 1);
        if ($("slider"))
            $("ss").slidingTipAway();

    }
};

var largeWaterMarks = function() {
    $$(".largecosmo").each(function(el) {
	    $W(el, {
	        esource: new Asset.image("/img/lrg_cosmo.png", {
                title: "As featured in Cosmopolitan magazine"
            }),
	        xoffset: 474,
	        yoffset: 7
	    });
	});

	$$(".largecoming").each(function(el) {
	    $W(el, {
	        esource: new Asset.image("/img/lrg_coming.png", {
                title: "Coming Soon Pre-Order Now"
            }),
	        xoffset: 474,
	        yoffset: 7
	    });
	});

	$$(".largelowstock").each(function(el) {
	    $W(el, {
	        esource: new Asset.image("/img/lrg_low.png", {
                title: "Stock is Low"
            }),
	        xoffset: 474,
	        yoffset: 7
	    });
	});

	$$(".largesoldout").each(function(el) {
	    $W(el, {
	        esource: new Asset.image("/img/lrg_out.png", {
                title: "Sold Out"
            }),
	        xoffset: 474,
	        yoffset: 7
	    });
	});
};


var slickConfirm = new Class({
    Implements: [Options, Events],
    options: {
        question: "Are you sure?",
        title: "Please confirm this",
        confirmButton: "",
        dismissButton: "",
        modal: false
    },
    initialize: function(src, options) {
        if (!$type(src) == "element")
            return;

        this.element = src;
        this.setOptions(options);
    },
    draw: function() {
        var _this = this;
        this.modalBox = new mOOdalBox(this.element, {
            title: this.options.title,
            movable: true,
            width: 379,
            modal: this.options.modal,
            height: 180,
            onComplete: function() {
                // scope is mOOdalBox class
                this.setHTML(_this.options.question);

                new Element("div", {
                    styles: {
                        margin: 16,
                        textAlign: "center"
                    }

                }).inject(this.modalBody).adopt(new Element("button", {
                      id: "confirmNo",
                    "class": "cur",
                    html: _this.options.dismissButton,
                    events: {
                        click: function() {
                            _this.fireEvent("dismiss");
                            this.close();
                        }.bind(this)
                    }
                })).adopt(new Element("button", {
                  id: "confirmYes",
                    "class": "cur",
                    html: _this.options.confirmButton,
                    events: {
                        click: function() {
                            _this.fireEvent("confirm");
                            this.close();
                        }.bind(this)
                    }
                }));
            }
        });
    },
    confirm: function() {
        this.fireEvent("confirm");
    },
    dismiss: function() {
        this.fireEvent("dismiss");
    }
});

// 14/03/2008 15:55:45 by dimitar christoff <coda@dci.uk.net>
window.addEvent("domready", function() {

    (function() {
        largeWaterMarks();
    }).delay((Browser.Engine.trident) ? 1000 : 0);

    $("bi").setOpacity(.5);

    $E("a.basketbutton").addEvents({
        "click": function(e) {
            var e = new Event(e).stop();
            if ($("productOption").get("value") != 0) {
                announceStock();
                if (checkStock()) {
                    if ($("scare")) {
                        var expDate = $("clickSize").getElement("div.sizeSelected").get("data-exp");
                        new slickConfirm(this, {
                            title: "Reserve your shoes",
                            question: "<div style='text-align:center;line-height:1.3'>Secure your " + $("SS").get("text").replace("Pre-Order UK", "size") +" by placing a <strong>PRE-ORDER</strong> today.<br /><br />This item will be despatched to you on or around <strong>" + expDate + "</strong>. <br /><br />To ensure this item is reserved for you, <strong>ADD TO BAG</strong> now.</div>",
                            onConfirm: function() {
                                submitDoc('addtobasket');
                            }
                        }).draw();
                    }
                    else {
                        submitDoc('addtobasket');
                    }
                }
                else
                    $("SS").slidingTip("Please select a size that's <br>not out of stock.", slidingOptions);
            }
            else {
                $("SS").slidingTip("Please select the<br> required size.", slidingOptions);
            }
        },
        "mouseenter": function() {

        }
    });

    var buildElement = function(targetElement, fieldLabel, fieldName, startValue, className) {
        var cl = new Element("div", {
            styles: {
                margin: 0,
                paddingBottom: 2,
                width: 325,
                "text-align": "right"
            }
        }).inject(targetElement);

        new Element("label", {
            "for": fieldName,
            "text": fieldLabel,
            styles: {
                width: 200,
                clear: "both",
                "margin-left": 5,
                margin: 0
            }
        }).inject(cl);

        new Element("input", {
            "class": className,
            id: fieldName,
            "name": fieldName,
            value: startValue,
            styles: {
                float: "none",
                clear: "both",
                "margin": 0,
                "margin-left": 5
            }
        }).inject(cl);
    }

        if ($("Product_description")) {
        $E("h1").dispose();
        var newHTML = $("Product_description").getFirst().get("html");
        var pd = new Element("div", {
            html: "<div class='avant' style='font-size:16px;padding-bottom:12px;font-weight: bold'>Description:</div>" + newHTML,
            styles: {
                "margin-bottom": 10,
				"margin-top": 10,
                "font-size": "12px",
                "line-height": "16px",
                color: "#000"
            }
        });

        if (Browser.Engine.trident) {
            pd.inject($("pd"));
        }
        else {
            pd.setOpacity(0).inject($("pd")).fade(1);
        }
        $("Product_description").dispose();
    }
    $$(".size").addEvents({
        "mouseenter": function() {
            this.addClass("sizeOn");
            $("SS").store("text", $("SS").get("text")).set("text", this.get("title"));
        },
        "mouseleave": function() {
            this.removeClass("sizeOn");
            $("SS").set("text", $("SS").retrieve("text"));
        },
        "click": function() {
            $("SS").slidingTipaway();

            if (this.hasClass("sizeSelected")) {
                $("productOption").set("value", 0);
                this.removeClass("sizeSelected");
                $("bi").set("opacity", .3);
                $("SS").store("text", "Select size:").set("text", "Select size:").fade(0,1);
                return false;
            }
            $("SS").store("text", $("SS").get("text")).set("text", this.get("title"));
            $$(".size").removeClass("sizeSelected");
            this.addClass("sizeSelected");
            $("productOption").set("value", this.get("rel"));
            if ($("scare"))
                $("scare").smartDispose();

            announceStock();
            if (this.get("opacity") == 1)
                $("SS").set("text", this.get("title")).fade(0,1);
        }
    }).addClass("cur").each(function(el) {
        if (stock[el.get("rel")] <= 0) {
            if (el.get("data-nc") <= 0)
                el.setOpacity(.4).addClass("sizeOutofstock").set("title", "size out of stock");
            else
                el.set("title", "Pre-Order " + el.get("title")).addClass("sizeOffpre");
        }
        else {
            el.set("title", el.get("title") + " in stock");
        }
    });





    if ($type(price) == "number") {
        if (price <= freeDelivery && $("freedelivery"))
        $("freedelivery").dispose();
    }

    $("doreview").addEvent("click", function() {
        var prodId = this.get("rel"), modalBox = new mOOdalBox(this, {
            title: "Create a new Shoe Envy Review",
            movable: true,
            text: "We'd love to know your impressions of <span style='color: #327BB2'>" + this.get("alt") + "</span>. By sharing your views you will help other customers make a more informed decision about their purchase.<br clear='all' />",
            width: 359,
            height: 347,
            onComplete: function() {
                this.setHTML(this.options.text);

                var userData = JSON.decode($("Login").get("alt"));

                buildElement(this.modalBody, "Your name", "senderName", userData.user, "box_input");
                buildElement(this.modalBody, "Your email", "senderEmail", userData.email, "box_input req");
        		buildElement(this.modalBody, "Review Title", "reviewTitle", "", "box_input req");

                new Element("textarea", {
                    id: "message",
                    name: "reviewBody",
                    "class": "box_input req",
                    text: "",
                    styles: {
                        float: "none",
                        clear: "both",
                        height: (Browser.Engine.trident) ? 126 : 130,
                        width: 320,
                        "margin-left": 5
                    }
                }).inject(this.modalBody);

                new Element("img", {
                    "src": "/images/buttons/button-cancel.gif",
                    id: "closemail",
                    "class": "cur",
                    styles: {
                        "margin-left": 2,
                        "margin-right": 7,
                        "margin-top": 8
                    }
                }).inject(this.modalBody).addEvent("click", function() {
                    this.close();
                }.bind(this));

        		// send review
        		new Element("img", {
                    "src": "/images/buttons/button-send-it.gif",
                    id: "sendmail",
                    "class": "cur",
                    styles: {
                        margin: 0,
                        "margin-top": 8
                    }
                }).inject(this.modalBody).addEvent("click", function() {

                    var errors = false;
                    $$(".req").each(function(el) {
                        if (el.get("value").length == 0) {
                            if (!errors) el.slidingTip("This is a required field,<br /> please fill it in", {
                                topOffset: 84,
                                eventEnd: "focus",
                                id: "slider",
                                opacity: 1.0
                            });

                            el.inputError();
                            errors = true;
                        }
                    });
                    if (errors) return false;

                    var regexp = new RegExp("^[\_]*([a-z0-9]+(\.|\_*)?)+@([a-z][a-z0-9\-]+(\.|\-*\.))+[a-z]{2,6}$", 'i');

                    if (!$("senderEmail").get("value").clean().toLowerCase().test(regexp)) {
                        $("senderEmail").slidingTip("This email does not <br>seem to be valid", {
                           topOffset: 84,
                           eventEnd: "focus",
                           id: "slider",
                           opacity: 1.0
                       }).inputError();
                        errors = true;
                    }

        			if (errors) return false;

                    // get data...
                    var string = "";
                    this.modalBody.getElements(".box_input").each(function(el) {
                        string += el.get("id") + "=" + el.get("value") +"&";
                    });

                    new Request({
                        method: "post",
                        url: "/accountAjax/a=review&prod="+prodId,
                        onComplete: function() {
                            this.setHTML("<div style='line-height: 1.3; font-size: 18px; font-weight: bold; letter-spacing: 1px;'><center><br />Thank you, an email has <br />been sent to our editor for approval</center></div>");
                            (function() {
                                this.close();
                            }).delay(3000, this);
                        }.bind(this)
                    }).send(string);
                }.bind(this)); // end click send


            }
        });





    });

    $$(".ReviewEntry").addEvents({
    	mouseenter: function() {
    		this.setStyle("border", "1px solid #4c4c4c");
    	},
    	mouseleave: function() {
    		this.setStyle("border", "1px solid #ccc");
    	}
    });

    var fitTimer;
	$$(".fitting").addEvents({
	    mouseenter: function() {
	    },
	    mouseleave: function() {

	    },
	    click: function(e) {
	        new Event(e).stop();
	        var brandId = this.get("data-id"), prodId = this.get("data-product"), brandName = this.get("data-brand_name"), _this = this;

	        new Request({
	            url: "/accountAjax/a=getFitting&id=" +brandId+"&p="+prodId,
	            method: "get",
	            onComplete: function() {
	                var fittingResponse = this.response.text;
                    if (fittingResponse.length > 0) {
                        var modalBox = new mOOdalBox(_this, {
                            title: " &nbsp;",
                            movable: true,
                            height: 300,
                            width: 750,
                            scroll: "true",
                            text: "Loading...",
                            onComplete: function() {
                                this.setHTML(fittingResponse);
                            }
                        });
                    }
	            }
	        }).send();

	    }
	}).set("title", "");


    $("addthis").setOpacity(.2);

    new Asset.javascript("http://s7.addthis.com/js/250/addthis_widget.js?pub=xa-4a32e50a6d8db98f", {
        onload: function() {
            (function() {
                $("addthis").fade(0,1).addEvents({
                    mouseenter: function() {
                        addthis_open(this, '', '[URL]', '[TITLE]');
                    },
                    mouseleave: addthis_close,
                    click: function(e) {
                        new Event(e).stop();
                        addthis_sendto();
                    }
                });
            }).delay(2000);
        }
    });

    var dodgyStock = [];

    for (key in stock)  {
        if (stock[key] <= 0)
            dodgyStock.push(key);
    };

    if (dodgyStock.length) {
        $("subscribe").set({
            styles: {
                display: "block"
            },
            events: {
                click: function() {
                    var prodId = $("doreview").get("rel");

                    var modalBox = new mOOdalBox(this, {
                        title: "Is your size out of stock?",
                        movable: true,
                        height: (Browser.Engine.trident) ? 286 : 280,
                        width: 359,
                        text: "Just leave us your contact details and we'll get in touch with you as soon as more stock arrives - it's easy! <br>Simply fill in your details below and select the size you're after. Remember to read our sizing information - with some shoes you need to get a size up or down from your normal size.<br /><br />",
                        onComplete: function() {
                            this.setHTML(this.options.text);

                    		var userData = JSON.decode($("Login").get("alt"));

                            buildElement(this.modalBody, "Your name", "senderName", userData.user, "box_input");
                            buildElement(this.modalBody, "Your email", "senderEmail", userData.email, "box_input req");
                            buildElement(this.modalBody, "Contact number", "senderNumber", userData.email, "box_input");

                            var sSelect = new Element("select", {
                                id: "senderSkew",
                                name: "senderSkew",
                                "class": "box_input",
                                styles: {
                                    margin: "auto",
                                    width: "100%",
                                    marginTop: 12
                                }
                            }).inject(this.modalBody), prod = $("doreview").get("alt");

                            $$("div.sizeOutofstock").each(function(el) {
                                new Element("option", {
                                    value: el.get("rel") + ";" + el.get("text"),
                                    html: prod + ", size " + el.get("text") + " &nbsp;"
                                }).inject(sSelect);
                            });

                            // cancel subscribe
                            new Element("img", {
                                "src": "/images/buttons/cancel_notify.gif",
                                id: "closemail",
                                "class": "cur",
                                styles: {
                                    "margin-left": 2,
                                    "margin-right": 8,
                                    "margin-top": 8
                                }
                            }).inject(this.modalBody).addEvent("click", function() {
                                this.close();
                            }.bind(this));

                    		// send review
                    		new Element("img", {
                                "src": "/images/buttons/notify_me_2.gif",
                                id: "sendmail",
                                "class": "cur",
                                styles: {
                                    "margin-top": 8
                                }
                            }).inject(this.modalBody).addEvent("click", function() {

                                var errors = false;
                                $$(".req").each(function(el) {
                                    if (el.get("value").length == 0) {
                                        if (!errors)
                                        el.slidingTip("This is a required field,<br /> please fill it in", {
                                            topOffset: 84,
                                            eventEnd: "focus",
                                            id: "slider",
                                            opacity: 1.0
                                        }).inputError();
                                        errors = true;
                                    }
                                });
                                if (errors) return false;

                                var regexp = new RegExp("^[\_]*([a-z0-9]+(\.|\_*)?)+@([a-z][a-z0-9\-]+(\.|\-*\.))+[a-z]{2,6}$", 'i');

                                if (!$("senderEmail").get("value").clean().toLowerCase().test(regexp)) {
                                    $("senderEmail").slidingTip("This email does not <br>seem to be valid",  {
                                       topOffset: 84,
                                       eventEnd: "focus",
                                       id: "slider",
                                       opacity: 1.0
                                    }).inputError();
                                    errors = true;
                                }

                    			if (errors) return false;

                                // get data...
                                var string = "";
                                this.modalBody.getElements(".box_input").each(function(el) {
                                    string += el.get("id") + "=" + el.get("value") +"&";
                                });

                                new Request({
                                    method: "post",
                                    url: "/accountAjax/a=subscribe&prod="+prodId,
                                    onComplete: function() {
                                        var size = ", Size " + $("senderSkew").get("value").split(";")[1];
                                        this.setHTML("<div style='line-height: 1.3; font-size: 18px; font-weight: bold; letter-spacing: 1px;'><center><br />Thank you!</center></div><br /><br />We will contact you as soon as we stock in some more of '" + prod + size + "'. <br /><br /><br /><br /><br /><center><span style='font-size:10px;color: #555'>This window will now close...</span></center>");
                                        (function() {
                                            if ($("mOOdalBox"))
                                            this.close();
                                        }).delay(6000, this);
                                    }.bind(this)
                                }).send(string);
                            }.bind(this)); // end click send
                        }
                    });




                }
            }
        });
        $("subscribe_message").setStyle("display", "block");

    }

    if ($("revlink"))
		$("revlink").addEvent("click", function() {
			$("doreview").fireEvent("click");
		});

	$$(".largesale").each(function(el) {
	    (function() {
    	    try {
        	    $W(el, {
        	        esource: new Asset.image("/img/lrg_sale.gif", {title: "Item is on sale"}),
        	        xoffset: 474,
        	        yoffset: 7,
        	        zIndex: 100
        	    });
        	} catch(e) {

        	}
        }).delay(1000);
	});

    Cufon(".avant");
}); // end domready
// end coda



