﻿$(document).ready(function() {
   $('#tabs div').css("display","block");
 });


//#region -- Prototypes
if (!"".trim) {
    String.prototype.trim = function() {
        return this.replace(/^\s*/, "").replace(/\s*$/, "");
    }
}
//#endregion -- Prototypes

//#region -- Egghead
//#region -- Egghead base 
Egghead = {
    //#region -- properties
    application: {
        path: function() { return window.location.protocol + "//" + window.location.hostname + window.location.port; }
    }
	, debug: { petedit: 0, ajaxloaderror: 0 }
	, isdebug: true
	, templates: {}
	, defaults: {
	    dialogcnt: function() {
	        if ($("#dialogContainer").length == 0) {
	            $("body").append('<div id="dialogContainer"></div>');
	        }
	        return $("#dialogContainer");
	    }
	}
    //#endregion -- properties

    //#region -- fn
	, fn: {
	    mergeOptions: function() { }
		, dialog: function() { }
		, isInt: function(evt) {
		    var charCode = (evt.which) ? evt.which : event.keyCode
		    if (charCode > 31 && (charCode < 48 || charCode > 57)) return false;
		    if (charCode == 13) return false;
		    return true;
		}
		, dictToJson: function(dictParsed) {
		    var json = {};
		    $.each(dictParsed, function(i, item) { json[item.Key] = item.Value; });
		    return json;
		}
		, dictToGroupedOptions: function(dict) {
		    var options = "";
		    $.each(dict, function(gi, group) {
		        options += "<optgroup label='" + group.Key + "'>";
		        $.each(group.Value, function(i, item) {
		            options += "<option value='" + item.Key + "' group='" + group.Key + "'>" + item.Value + "</option>";
		        });
		        options += "</optgroup>";
		    });
		    return options;
		}
		, formToJson: function(form) {
		    var json = {};
		    for (var i = 0; i < form.length; i++) {
		        var el = form[i];
		        var val = $(el).val();
		        if (el.type && el.type === "checkbox") {
		            val = el.checked;
		        }
		        json[el.name] = val;
		    }
		    return json;
		}
		, intColumnEdit: function(pattern, container) { }
		, checkEmailSyntax: function(email) { return /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(email); }
		, setDebug: function(info) { var dg = $("#eggheadDebug span"); if (dg.length == 0) { $("body").append('<div id="eggheadDebug"><span></span></div>'); dg = $("#eggheadDebug span"); $("#eggheadDebug").dialog({ modal: false, title: "debug", width: 200, height: 800, position: ["left"] }); } dg.html(info + "<br />"); }
		, addDebug: function(info) { var dg = $("#eggheadDebug span"); if (dg.length == 0) this.setDebug(info); else dg.html(dg.html() + info + "<br />"); }
	}
    //#endregion -- fn

    //#region -- services
	, services: {
	    ajax: { path: function() { }
			, load: function() { }
			, ucLoad: function() { }
			, ucUpdate: function() { }
	    }
	}
    //#endregion -- services

    //#region -- busy 
	, busy: { obj: $()
		, items: []
		, visible: false
		, hide: function() {
		    Egghead.busy.visible = false;
		    Egghead.busy.obj.hide();
		    Egghead.busy.items = []; //reset
		}
		, show: function() {
		    if (!Egghead.busy.visible && Egghead.busy.items.length) {

		        Egghead.busy.obj.show();
		        Egghead.busy.visible = true;
		    }
		}
		, subscribe: function(id) {
		    if (id) {
		        Egghead.busy.items.push(id);
		        Egghead.busy.show();
		    }
		}
		, unsubscribe: function(id) {
		    var a = [], removed = false;
		    for (var i = 0; i < Egghead.busy.items.length; i++) {
		        if (!removed && Egghead.busy.items[i] === id) removed = true
		        else a.push(Egghead.busy.items[i]);
		    }
		    Egghead.busy.items = a;
		    if (Egghead.busy.visible && !Egghead.busy.items.length) Egghead.busy.hide();
		}
		, move: function(e) {
		    Egghead.busy.obj.css({ "left": e.pageX + 8, "top": e.pageY - 10 });
		}
	}
    //#endregion -- busy

    //#region -- controls
	, controls: {
	    //#region -- datepicker
	    datepicker: function(jqPattern, container) {
	        $(jqPattern, container) //z-index fixed per class, z-index + possition: relative, absolute, fixed
			.datepicker({
			//beforeShow: function(input, inst){ }

});
	    }
	    //#endregion -- datepicker
	}
    //#endregion -- controls
};
//#endregion -- Egghead base 

//#region -- fn 
//#region -- Egghead.fn.mergeOptions(options, extended)
Egghead.fn.mergeOptions = function(options, extended) {
    if (extended) for (var key in extended) {
        if (extended.hasOwnProperty(key)) {
            if (options.hasOwnProperty(key) && (typeof extended[key] === "object") && (typeof options[key] === "object")) {
                Egghead.fn.mergeOptions(options[key], extended[key]);
            }
            else {
                options[key] = extended[key];
            }
        }
    }
    return options;
};
//#endregion -- Egghead.fn.mergeOptions(options, extended)

//#region -- Egghead.fn.dialog(options, html)
Egghead.fn.dialog = function(options, html) {
    var defaults = { autoOpen: true, height: 'auto', width: 570
		, modal: true
		, title: "Dialog"
		, buttons: {}
		, close: function() { $(this).empty(); }
    };

    Egghead.fn.mergeOptions(defaults, options);

    return Egghead.defaults.dialogcnt()
		.empty().html(html)
		.dialog(defaults);
}
//#endregion -- Egghead.fn.dialog(options, html)

//#region -- Egghead.fn.intColumnEdit(pattern, container)
Egghead.fn.intColumnEdit = function(pattern, container) {
    return $(pattern, container)
	.keypress(Egghead.fn.isInt)
	.keydown(function(event) {
	    if (event.keyCode != 38 && event.keyCode != 40) return;
	    var inputs = $(pattern);
	    for (var i = 0; i < inputs.length; i++) {
	        if ($(inputs[i]).attr("id") == $(this).attr("id")) {
	            if (event.keyCode == 38) if (i > 0) $(inputs[i - 1]).focus();
	            if (event.keyCode == 40) if (inputs.length > i) $(inputs[i + 1]).focus();
	        }
	    }
	})
	.focus(function() { if ($(this).val() == 0) $(this).val(''); })
	.blur(function() { if ($(this).val() == '') $(this).val('0'); });
}
//#endregion -- Egghead.fn.intColumnEdit(pattern, container)

//#endregion -- fn 

//#region -- services
Egghead.services.ajax.path = function() { return Egghead.application.path() + "/AjaxServices.asmx"; };

//#region -- load(options: {service_fn, data:stringify'ied}) - success(result.d, srv_result), error(msg.responseText)
Egghead.services.ajax.load = function(options) {
    var defaults = { type: 'POST'
		, url: Egghead.services.ajax.path() + options.service_fn
        //,data: {}
		, contentType: "application/json; charset=utf-8"
		, dataType: "json"
		, success: function(result) { }
		, error: function(msg) { alert(msg.responseText); } // default one

		, busy: "default"
		, beforeSend: function(rq) {
		    Egghead.busy.subscribe(this.busy);
		}
		, complete: function(rq) {
		    Egghead.busy.unsubscribe(this.busy);
		}
    };

    Egghead.fn.mergeOptions(defaults, options);

    if (Egghead.debug.ajaxloaderror) defaults.error = function(msg) { alert(msg.responseText); };

    $.ajax(defaults);

    return this;
};
//#endregion -- load

//#region -- ucLoad(options: { controlPath: 'folder/control', data: {}, success:(result.d), error })
Egghead.services.ajax.ucLoad = function(options) {
    var defaults = { service_fn: "/RenderUserControl", controlPath: "" }
    Egghead.fn.mergeOptions(defaults, options);
    defaults.data = JSON.stringify({ controlPath: defaults.controlPath
		, options: defaults.data
    });
    return Egghead.services.ajax.load(defaults);
};
//#endregion -- ucLoad

//#region -- ucUpdate(options: { controlPath: 'folder/control', data: {}, success:(json, srv_result), error })
Egghead.services.ajax.ucUpdate = function(options) {
    var defaults = { service_fn: "/RenderUserControlUpdate", controlPath: "" }
    Egghead.fn.mergeOptions(defaults, options);
    defaults.data = JSON.stringify({ controlPath: defaults.controlPath
		, options: defaults.data
    });

    defaults.clientSuccess = options.success;
    defaults.success = function(msg, result) {
        var dict = JSON.parse(msg.d);
        //if(json.result === "success")
        return defaults.clientSuccess(Egghead.fn.dictToJson(dict), result); //data, service result
    }
    return Egghead.services.ajax.load(defaults);
};
//#endregion -- ucUpdate

//#region -- getdata(options: { controlName: 'className', data: {}, success:(json, result, srv_result), error })
Egghead.services.ajax.getdata = function(options) {
    var defaults = { service_fn: "/GetDataJson", controlName: "" };
    Egghead.fn.mergeOptions(defaults, options);
    defaults.data = JSON.stringify({ controlName: defaults.controlName
		, options: defaults.data
    });

    defaults.clientSuccess = options.success;
    defaults.success = function(msg, result) {
        var json = JSON.parse(msg.d);
        //if(json.result === "success")
        return defaults.clientSuccess(Egghead.fn.dictToJson(json.data), json.result, result); //data, service result, ajax result
    }
    return Egghead.services.ajax.load(defaults);
}
//#endregion -- getdata

//#endregion -- services

//#endregion -- Egghead

//#region === (jQuery.extend)

//#region -- serializeFormToJson (jQuery.extend)
jQuery.extend({
    serializeFormToJson: function(form) {
        var json = {};
        for (var i = 0; i < form.length; i++) {
            var el = form[i];
            var val = $(el).val();
            if (el.type && el.type === "checkbox") {
                val = el.checked;
            }
            json[el.name] = val;
        }
        var res = JSON.stringify(json);
        return res;
    }
});
//#endregion -- serializeFormToJson

//#region -- dictionaryToJson 
jQuery.extend({
    dictionaryToJson: function(dictUnparsed) {
        var dic = JSON.parse(dictUnparsed);
        var json = {};
        $.each(dic, function(i, item) {
            json[item.Key] = item.Value;
        });
        return json;
    }
		, pDictionaryToJson: function(dictParsed) {
		    var json = {};
		    $.each(dictParsed, function(i, item) {
		        json[item.Key] = item.Value;
		    });
		    return json;
		}
});
//#endregion -- dictionaryToJson

//#region -- dictionaryToOptions
jQuery.extend({
    dictionaryToOptions: function(dictUnparsed) {
        var dic = JSON.parse(dictUnparsed);
        var options = "";
        $.each(dic, function(i, item) {
            options += "<option value='" + item.Key + "'>" + item.Value + "</option>";
        });
        return options;
    }
});
//#endregion -- dictionaryToOptions

//#region -- dictionaryToGroupedOptions
jQuery.extend({
    dictionaryToGroupedOptions: function(dictUnparsed) {
        var dic = JSON.parse(dictUnparsed);
        var options = "";
        $.each(dic, function(gi, group) {
            options += "<optgroup label='" + group.Key + "'>";
            $.each(group.Value, function(i, item) {
                options += "<option value='" + item.Key + "' group='" + group.Key + "'>" + item.Value + "</option>";
            });
            options += "</optgroup>";
        });
        return options;
    }
});
//#endregion -- dictionaryToGroupedOptions

//#region -- groupOptions
jQuery.extend({
    groupOptions: function(id, group) {
        if (!group) group = "group";
        id = "#" + id;
        var a = {};
        $(id + " [" + group + "]").each(function() {
            g = $(this).attr(group);
            if (!a[g]) a[g] = true;
        });
        $.each(a, function(key, val) {
            $(id + " [" + group + "='" + key + "']").wrapAll("<optgroup label='" + key + "'>");
        });
        return true;
    }
});
//#endregion -- groupOptions

//#endregion === (jQuery.extend)

//#region -- subscription/unsubscription
(function($) {
    Egghead.Subscriber = function(options) {
        //#region -- options
        var defaults = {
            subscriber: {}
			, unsubscriber: {
			    success: function(result) {
			        if (result.d === "success") alert("You have been successfully subscribed");
			        else alert("Subscription failed");
			    }
				, error: function(msg) { alert("Unsubscription failed"); }
			}
			, data: {}
			, success: function(result) {
			    if (result.d === "success") alert("You have been successfully subscribed");
			    else alert("Subscription failed");
			}
			, error: function(result) { alert("Subscription failed"); }
        }
        var mergeOptions = function(options, extended) {
            if (extended) for (var key in extended) if (key != "subscriber" && key != "unsubscriber") {
                if (extended.hasOwnProperty(key)) {
                    if (options.hasOwnProperty(key) && (typeof extended[key] === "object") && (typeof options[key] === "object")) {
                        mergeOptions(options[key], extended[key]);
                    }
                    else {
                        options[key] = extended[key];
                    }
                }
            }
        }

        mergeOptions(defaults, options);
        this.options = { subscriber: defaults.subscriber, unsubscriber: defaults.unsubscriber };
        mergeOptions(this.options.subscriber, defaults);
        if (options && options.subscriber) mergeOptions(this.options.subscriber, options.subscriber);
        mergeOptions(this.options.unsubscriber, defaults);
        if (options && options.unsubscriber) mergeOptions(this.options.unsubscriber, options.unsubscriber);
        //#endregion -- options

        //#region -- _action
        this._action = function(options, email, action) {
            if (!Egghead.fn.checkEmailSyntax(email)) {// !email || ! /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(email)){
                alert("Email is not valid");
                return false;
            }
            options.data["email"] = email;
            options.data["action"] = action;

            Egghead.services.ajax.load({ service_fn: "/Subscribe"
				, data: '{"options": ' + JSON.stringify(options.data) + '}'
				, success: options.success
				, error: options.error
            });

            return true;
        }

        //#endregion -- _action
    }

    //#region -- prototype subscribe/unsubscribe
    Egghead.Subscriber.prototype = {
        subscribe: function(email) { return this._action(this.options.subscriber, email, "subscribe"); }
		, unsubscribe: function(email) { return this._action(this.options.unsubscriber, email, "unsubscribe"); }
		, tellafriend: function(name, email, friendname, friendemail) {
		    this.options.data["name"] = friendname;
		    this.options.data["referername"] = name;
		    this.options.data["refereremailaddress"] = email;
		    return this._action(this.options, friendemail, "tellafriend");
		}
    }
    //#endregion -- prototype subscribe/unsubscribe

    //#region -- TellAFriend
    Egghead.TellAFriend = function() {
        //#region -- collectData
        var collectData = function(dataContainer) {
            var data = { name: $("#name", dataContainer).val(), email: $("#email", dataContainer).val(), friends: [] }

            if (data.name.trim() === "" || data.email.trim() === "") {
                alert("Please enter your name / email");
                return false;
            }
            if (!Egghead.fn.checkEmailSyntax(data.email)) {
                alert("Your email is not valid, please check it");
                return false;
            }

            $("[id^=fn_]", dataContainer).each(function(i, item) {
                var no = $(item).attr("id").split("_")[1];
                data.friends.push({ name: $(item).val(), email: $("#fe_" + no, dataContainer).val(), no: no });
            });
            var found = false;
            for (var i = 0; i < data.friends.length; i++) {
                var item = data.friends[i];
                if (item.email.trim() === "") continue;

                found = true;
                if (!Egghead.fn.checkEmailSyntax(item.email)) {
                    alert("Friend email at possition " + item.no + " is invalid, please check it");
                    return false;
                }
            }
            if (!found) {
                alert("You did not enter any friend's email to subscribe");
                return false;
            }

            return data;
        }
        //#endregion -- collectData

        //#region -- subscribe
        var subscribe = function(dataContainer) {
            Egghead.services.ajax.ucUpdate({ controlPath: "Subscription/TellAFriend"
				, data: Egghead.fn.formToJson($("[name]", dataContainer))
				, success: function(data, ajaxResult) {
				    if (data.result === "success") {
				        alert("Your friends successfully subscribed");
				        Egghead.defaults.dialogcnt().dialog("close");
				        return;
				    }
				    else {
				        alert(data.message);
				    }
				}
				, error: function(msg) {
				    alert("Erorr while subscribing friends");
				}
            });
        }
        //#endregion -- subscribe

        //#region -- initialize control
        Egghead.services.ajax.ucLoad({ controlPath: "Subscription/TellAFriend", data: {}
			, success: function(msg, result) {
			    if (result === "success") {
			        var dialog = Egghead.fn.dialog({ height: 320, width: 580, title: "Tell a friend" }, msg.d);

			        var cntFriends = $("#cntFriends", dialog);
			        $("#f_subscribe", cntFriends).button()
					.each(function() { this.dataContainer = cntFriends; return this; })
					.click(function() {
					    var data = collectData(this.dataContainer);
					    if (!data) return false;

					    subscribe(this.dataContainer);

					    return false;
					});
			    }
			    else alert("Error while loading Teall A Friend control");
			}
			, error: function(msg) { alert("Error while loading Teall A Friend control"); }
        });
        return false;
        //#endregion -- initialize control
    }
    //#endregion -- TellAFriend

})(jQuery);
//#endregion -- subscription/unsubscription

//#region -- addOnSubmit
(function($) {
    $.fn.extend({
        addOnSubmit: function(newFunction) {

            return this.each(function() {
                if (!this.onsubmithandler) {

                    this.onsubmithandler = [];
                    if (this.onsubmit) {
                        if (typeof this.onsubmit === "function") {
                            this.onsubmithandler.push(this.onsubmit);
                        }
                        else {
                            this.onsubmithandler.push(new Function(this.onsubmit));
                        }
                        $(this).removeAttr("onsubmit");
                    }

                    this.onsubmit = function() {
                        for (var i = 0; i < this.onsubmithandler.length; i++) {
                            this.handlevent = this.onsubmithandler[i];
                            if (this.handlevent()) {
                                continue;
                            }
                            return false;
                        }
                        return true;
                    }

                }

                this.onsubmithandler.push(newFunction);

                return this;
            });

        }
    })
})(jQuery);
//#endregion -- addOnSubmit

//#region -- Cart Variants
(function($) {
    $.fn.extend({//only one dialog will be shown, no need for each
        cartVariantPopup: function() {
            this.css("cursor", "pointer");

            return this.click(function() {
                var productid = $(this).attr("productid");

                Egghead.services.ajax.ucLoad({ data: { productid: productid }
					, controlPath: "Order/CartVariantPopup"
					, success: function(msg) {
					    var dialog = Egghead.fn.dialog({ height: 300, width: 430
							, title: "Please select which variant you would like to add to your basket"
					    }
						, msg.d);

					    $("#btnAddToBasket", dialog).button().click(function() {
					        var query = "";
					        $("input[id^=variant]", dialog).each(function() {
					            if ($(this).val() > 0) {
					                query += "$" + $(this).attr("id").substring(7)
										+ "_" + $(this).val();
					            }
					        })
					        if (query) {
					            window.location = Egghead.application.path() + "/addtocart.aspx?productid=" + productid + "&variants=" + query + "&ReturnUrl=" + escape(window.location);
					        }
					        else {
					            alert("Nothing to add!");
					        }
					    });

					    $("input[id^=variant]", dialog)
						.keypress(Egghead.fn.isInt)
						.keydown(function(event) {
						    if (event.keyCode != 38 && event.keyCode != 40) return;
						    var inputs = $("input[id^=variant]");
						    for (var i = 0; i < inputs.length; i++) {
						        if ($(inputs[i]).attr("id") == $(this).attr("id")) {
						            if (event.keyCode == 38) if (i > 0) $(inputs[i - 1]).focus();
						            if (event.keyCode == 40) if (inputs.length > i) $(inputs[i + 1]).focus();
						        }
						    }
						})
						.focus(function() { if ($(this).val() == 0) $(this).val(''); })
						.blur(function() { if ($(this).val() == '') $(this).val('0'); });

					}
					, error: function(msg) { alert("Error while loading cart variants control"); }
                });
            });
        }
    });
})(jQuery);
//#endregion -- Cart Variants


//#region -- Slider
(function($) {
    $.fn.extend({
        productSlider: function() {
            //#region variables
            var container = this;
            container.slidetype = this.attr("slidetype");
            //#endregion

            //#region -- command
            var command = function() {

                var pagenum = $(this).attr("pagenum");
                var direction = $(this).attr("direction");
                var catID = $(this).attr("catID");
                //alert("id: " + $(this).attr("id") + ", pagenum: " + pagenum + ", slidetype: " + container.slidetype);

                $(this).unbind('click', false);

                Egghead.services.ajax.ucLoad({ controlPath: 'slider/slidetype'
					, data: { slidetype: container.slidetype, pagenum: pagenum }
					, success: function(response, result) {

					    if (jQuery.trim(direction) == 'left') {
					        container.find('#slider_body').append($(response.d).find('#slider_body_inner'));
					    }
					    else {
					        container.find('#slider_body').prepend($(response.d).find('#slider_body_inner'));

					        container.find('#slider_body_inner:first').css('margin-left', -container.find('#slider_body_inner').width());
					    }

					    if ($(response.d).find('.slider_left_arrow').length != 0) {
					        container.find('.slider_left_arrow, .slider_left_arrow_disabled').replaceWith($(response.d).find
('.slider_left_arrow'));
					    }
					    if ($(response.d).find('.slider_left_arrow_disabled').length != 0) {
					        container.find('.slider_left_arrow, .slider_left_arrow_disabled').replaceWith($(response.d).find
('.slider_left_arrow_disabled'));
					    }

					    if ($(response.d).find('.slider_right_arrow').length != 0) {
					        container.find('.slider_right_arrow, .slider_right_arrow_disabled').replaceWith($(response.d).find
('.slider_right_arrow'));
					    }
					    if ($(response.d).find('.slider_right_arrow_disabled').length != 0) {
					        container.find('.slider_right_arrow, .slider_right_arrow_disabled').replaceWith($(response.d).find
('.slider_right_arrow_disabled'));
					    }

					    container.find('.slider_left_arrow').attr('disabled', 'disabled');
					    container.find('.slider_right_arrow').attr('disabled', 'disabled');

					    container.find('.slider_left_arrow').children().attr('disabled', 'disabled');
					    container.find('.slider_right_arrow').children().attr('disabled', 'disabled');

					    //alert(response.d);
					    //container.initialize();
					    SetupTooltips();

					    if (jQuery.trim(direction) == 'left') {

					        container.find('#slider_wrapper').css("overflow", "hidden");
					        container.find('#slider_body').css("width", "1676px");
					        container.find('#slider_body_inner:first').animate({
					            'margin-left': -container.find('#slider_body_inner').width()
					        },
					            1500, function() {
					                $(this).remove();

					                container.find('#slider_wrapper').css("overflow", "visible");
					                container.find('#slider_body').css("width", "auto");
					                container.initialize();
					            });
					    }
					    else {

					        container.find('#slider_wrapper').css("overflow", "hidden");
					        container.find('#slider_wrapper').css("overflow", "hidden");
					        container.find('#slider_body').css("width", "1676px");
					        container.find('#slider_body_inner:first').animate({
					            'margin-left': 0
					        },
					            1500, function() {
					                container.find('#slider_body_inner:last').remove();

					                container.find('#slider_wrapper').css("overflow", "visible");
					                container.find('#slider_body').css("width", "auto");
					                container.initialize();
					            });
					    }
					}
					, error: function(response, result) {
					    alert("Error while loading slide items");
					}
                });
            }

            //#endregion

            //#region -- initialize
            this.initialize = function() {

                this.left = $(".slider_left_arrow", this);
                this.right = $(".slider_right_arrow", this);

                this.left.click(command);

                this.right.click(command);
            }

            //#endregion -- initialize

            this.initialize();

            return this;
        }
    })
})(jQuery);
//#endregion -- Slider

//#region -- compareProductDialog 
(function($) {
    $.fn.extend({
        compareProductDialog: function(options) {



            //#region -- options 
            var defaults = { productids: []
				, variantids: []
				, controlPath: 'compare/ProductDialog'
				, error: function(response, result) {

				    alert("Error while loading Product Compare dialog");
				}
            };
            var container = this;

            Egghead.fn.mergeOptions(defaults, options);

            if (defaults.productids.length + defaults.variantids.length < 2) {
                alert("Please, select more products to compare");
                return this;
            }

            //#endregion -- options 

            //#region -- variantChanged 
            var variantChanged = function() {
                var variantids = [];
                $("[id$=ddlVariant]").each(function(index, item) {
                    variantids.push($(item).val());
                });

                Egghead.services.ajax.ucLoad({ controlPath: defaults.controlPath
					, data: { productids: "", variantids: variantids.join('_') }
					, error: function(resonse, result) {
					    alert('1');
					}
					, success: function(response, result) {
					    if (result === "success") {
					        Egghead.defaults.dialogcnt().empty().html(response.d);
					        $("[id$=ddlVariant]").change(variantChanged);
					    }
					}
                });
            }

            //#endregion -- variantChanged 

            //#region -- Initialize
            this.initialize = function() {
                Egghead.services.ajax.ucLoad({ controlPath: defaults.controlPath
					, data: { productids: defaults.productids.join('_'), variantids: defaults.variantids.join('_') }
					, error: function(resonse, result) {

					}
					, success: function(response, result) {
					    if (result === "success") {
					        Egghead.fn.dialog({ title: "Compare products", width: 875, height: 850 }, response.d);
					        $("[id$=ddlVariant]").change(variantChanged);
					        //alert(response.d);
					    }
					}
                });
            }

            //#endregion -- Initialize 
            this.initialize();

            return this;
        }
    })
})(jQuery);

//#endregion -- compareProductDialog

//#region -- compareProductList
(function($) {
    $.fn.extend({
        compareProductList: function(options) {

            var defaults = { buttonTitle: 'Compare products', mainContainer: '#divCompareProducts', productContainer: '#divProductsCompare', compareContainer: '#divSelectedProducts' }
            Egghead.fn.mergeOptions(defaults, options);
            var container = this;
            container.options = defaults;

            var hrefBase = container.find("#hidBaseUrl").val();
            var partLink = container.find("#hidPartLink").val();
            var controlId = container.find("#hidSearchControl").val();
            var previousOrder = container.find("#hidSortOrder").val();
            var previousColumn = container.find("#hidSortcolumn").val();
            var pageNo = container.find("#hidPageNumber").val();
            var totalSelectedProducts = container.find("#hidSelectedProducts").val();
            var selectedIds = container.find("#hidSelectedPrdList").val();
            var showAllVal = container.find("#hidShowAllLink").val();
            //#region -- create url for selected checkbox
            var createHref = function(value, checked, clear, isSorting) {
                var hrefPart = controlId + "=" + escape(partLink);
                var showAlllink = "";
                //alert(showAllVal);
                if (showAllVal == "False") {
                    showAlllink = "|";
                }
                else {
                    showAlllink = "1|"
                }

                if (isSorting == false) {
                    return hrefBase + "&" + hrefPart + escape((checked ? "|addpid=|" : "|rempid=|") + value) + PreparePagingString(isSorting) + prepareSortingString(null) + "|showall=|" + showAlllink;
                }
                else {
                    return hrefBase + "&" + hrefPart + PreparePagingString(isSorting) + prepareSortingString(value) + "|showall=|" + showAlllink;
                }
            };
            //#endregion

            var PreparePagingString = function(isShorting) {
                if (isShorting == true) {
                    return escape("|pgno=|1");
                }
                else {
                    if (pageNo > 0) {

                        return escape("|pgno=|") + pageNo;
                    }
                }

                return '';
            }

            var prepareSortingString = function(currentValue) {
                if (currentValue == null) {
                    currentValue = $("#ddlSort option:selected").val();
                }

                if (currentValue.indexOf('_') > 0) {
                    var column = currentValue.split('_')[0];
                    var order = currentValue.split('_')[1];
                    return escape("|order=|") + order + escape("|sortcolumn=|") + column;
                }
                else {
                    return escape("|order=|ASC") + escape("|sortcolumn=|") + currentValue;
                }
            }

            //#region -- Select Control's Change Event
            var selectChange = function() {
                var href = createHref($(this).val(), false, false, true);
                document.location = href;

                processCheckBoxAndButton();
            }
            //#endregion

            //#region -- checkboxClick
            var checkboxClick = function() {
                container.selection = [];


                var jsondata = {};
                $("#divInProgress").displayInProgress(jsondata);

                $(this).each(function(index, item) {
                    var i = $(item);
                    var value = i.attr("value");

                    if (i.attr("checked")) {
                        if (i.attr("preselected") && i.attr("preselected") == "false") {
                            document.location = createHref(value, i.attr("checked"), false, false);
                        }
                    }
                    else {
                        if (i.attr("preselected") && i.attr("preselected") == "true") {
                            document.location = createHref(value, i.attr("checked"), false, false);
                        }
                    }

                });
            }
            //#endregion -- checkboxClick

            // #region ExecuteMethod for Disabling checkbox control
            var processCheckBoxAndButton = function() {
                $('select').each(function() {
                    $('option', this).each(function() {

                        if ($(this).val().toLowerCase() == previousColumn) {
                            //$('#ddlSort option[value=' + previousColumn + ']').attr('selected', 'selected');
                            $(this).attr('selected', 'selected');
                        }
                        else if ($(this).val().toLowerCase() == previousColumn + '_' + previousOrder) {
                            $(this).attr('selected', 'selected');
                            //$('#ddlSort option[value=' + previousColumn + '_' + previousOrder + ']').attr('selected', 'selected');
                        }

                    })
                });

                var selectedItem = $("input[type=checkbox]", $(container.options.productContainer)).filter(":checked").length;

                if (selectedItem >= 2 || totalSelectedProducts >= 2) {

                    if (selectedItem >= 3 || totalSelectedProducts >= 3) {
                        $("input[type=checkbox]", $(container.options.productContainer)).filter(":not(:checked)").attr("disabled", "disabled");
                    }

                    container.selection = [];

                    var selectionToPush = selectedIds.split(",");

                    for (var i = 0; i < selectionToPush.length; i++) {
                        container.selection.push(selectionToPush[i]);
                    }

                    $("input[type=checkbox]", $(container.options.productContainer)).each(function(index, item) {
                        var ichk = $(item);
                        var value = ichk.attr("value");

                        //Push Values to the Selection Collection
                        if (ichk.attr("checked")) {
                            container.selection.push(value);
                        }
                        else {
                            //Disable CheckBox
                            if (selectedItem >= 3) {
                                ichk.attr("disabled", "disabled");
                            }
                        }
                    });
                }
                else if (selectedItem < 2 || totalSelectedProducts < 2) {
                    $("input[type=checkbox]", $(container.options.productContainer)).find(":not(:checked)").each(function(index, item) {
                        var i = $(item);
                        if (i.attr("disabled")) {
                            i.removeAttr("disabled");
                        }
                    });
                }

                var tempCount = 0;
                tempCount = totalSelectedProducts >= selectedItem ? totalSelectedProducts : selectedItem;


                //Enable Disable Buttons and set Button's Text
                $("input[type=button]", container).each(function(index, item) {
                    var i = $(item);
                    if (tempCount > 0)
                        i.val(tempCount ? container.options.buttonTitle + " (" + tempCount + ")" : container.options.buttonTitle);
                    else
                        i.val(tempCount ? container.options.buttonTitle : container.options.buttonTitle);

                    if (tempCount < 1) {
                        if (i.attr("disabled")) {
                            i.attr("disabled", "disabled");
                            $('#compareHeader').attr("disabled", "disabled");
                        }
                    }
                    else {
                        if (i.attr("disabled")) {
                            i.removeAttr("disabled");
                            i.css({ "display": '' });
                            $('#compareHeader').removeAttr("disabled");
                            $('#compareHeader').css({ "display": '' });
                            //Bind Click Event with Button
                            i.click(buttonClick);
                        }
                    }
                });
            }
            // #endregion

            //#region -- buttonClick
            var buttonClick = function() {
                $(this).compareProductDialog({ productids: container.selection });
            }
            //#endregion -- buttonClick



            //#region -- initialize
            this.initialize = function() {

                //Initialize Controls Collection
                container.buttons = $("input[type=button]", $(container.options.mainContainer));
                container.checkboxes = $("input[type=checkbox]", $(container.options.productContainer));
                container.compareCheckboxes = $("input[type=checkbox]", $(container.options.compareContainer));

                //container.sortcontrol = $("#ddlSort", $(container));

                container.selection = [];

                //Perform checks on checkbox and Enable or Disable this checkboxes
                processCheckBoxAndButton();

                container.checkboxes.click(checkboxClick);
                container.compareCheckboxes.click(checkboxClick);
                $("#ddlSort", $(container)).change(selectChange);
            }
            //#endregion -- initialize

            this.initialize();

            return this;
        }
    })
})(jQuery);
//#endregion -- compareProductList

(function($) {
    $.fn.extend({
        displayInProgress: function(options) {
            //#region -- options
            var defaults = {
                controlPath: '/InProgress'
				, error: function(response, result) {
				    alert("Error while loading In Progress dialog");
				}
            }

            Egghead.fn.mergeOptions(defaults, options);
            var container = this;
            container.options = defaults;


            //#endregion -- options

            //#region -- Initialize
            this.initialize = function() {



                Egghead.services.ajax.ucLoad({ controlPath: "/InProgress"
					, data: {}
					, error: function(resonse, result) {
					    //alert(result);
					}
					, success: function(response, result) {
					    if (result === "success") {
					        //alert("Branch Stock Levels");
					        
					        Egghead.fn.dialog({ title: "", width: 350, height: 150 }, "<table width='100%'><tr><td align='center'><img src='images/spinner.gif' border='0'/></td></tr></table>");
					        
					        $("a[role ^= 'button']").css({ "display": 'none' });
					        
					        $(".ui-resizable-handle", $(".ui-dialog")).css({ "display": 'none' });
					        $(".ui-dialog").css({ "background": 'transparent' });
					        $(".ui-dialog").css({ "border": '0px' });
					        
					    }
					}
                });
            }

            //#endregion -- Initialize 
            this.initialize();

            return this;
        }
    })
})(jQuery);

//#region -- additionalItems
(function($) {
    $.fn.extend({
        additionalItems: function(options) {
            var defaults = {
                productid: 201,
                quantity: "",
                controlPath: 'upsells/AdditionalItems',
                error:
		        function(response, result) {
		            alert("Error while loading Product Additional Items");
		        }
            }

            Egghead.fn.mergeOptions(defaults, options);
            var container = this;
            container.options = defaults;

            //#region -- updateDataEvent
            var updateDataEvent = function() {
                var cnt = Egghead.defaults.dialogcnt();
                var button = $(this);

                var products = $("input[type=checkbox][id^=productid]", cnt);
                var pids = [];
                products.each(function(index, item) {
                    if ($(this).attr("checked")) pids.push($(this).val());
                });

                if (pids.length > 0) {
                    //data = { pids: pids.join("_"), productid: container.options.productid };
                    data = Egghead.fn.formToJson($("[name]", $(cnt)));
                    data.buttonevent = button.attr("name");
                    data.productid = container.options.productid;

                    Egghead.services.ajax.ucUpdate({ controlPath: container.options.controlPath
                                        , data: data
                                        , error: function() { alert("Couldn't add item(s) to basket. Please close this dialog."); }
                                        , success: function(respose, result) {
                                            if (button.attr("name") == "checkouttop" || button.attr("name") == "checkoutbottom") {
                                                window.location = "shoppingcart.aspx";
                                            }
                                            else if (button.attr("name") == "continueshoppingtop" || button.attr("name") == "continueshoppingbottom") {
                                                window.location.reload(true);
                                            }
                                        }
                    });
                }
                else {
                    if (button.attr("name") == "checkouttop" || button.attr("name") == "checkoutbottom") {
                        window.location = "shoppingcart.aspx";
                    }
                    else if (button.attr("name") == "continueshoppingtop" || button.attr("name") == "continueshoppingbottom") {
                        closeDialog();
                    }
                }

                return true;
            };
            //#endregion -- updateDataEvent

            //#region -- close dialog
            var closeDialog = function() {
                //To Close Current Dialog
                Egghead.defaults.dialogcnt().empty();
                Egghead.defaults.dialogcnt().dialog("close");
            }
            //#endregion -- close dialog


            //#region -- Initialize Additional Items
            this.initialize = function() {
                Egghead.services.ajax.ucLoad({ controlPath: container.options.controlPath
					, data: { productid: container.options.productid, quantity: container.options.quantity }
					, error: container.options.error
					, success: function(response, result) {
					    if (result === "success") {
					        Egghead.fn.dialog({ title: "", width: 920, height: 650 },
					        response.d);

					        var cntbuttons = Egghead.defaults.dialogcnt();
					        $("#continueshoppingtop", cntbuttons).button().click(updateDataEvent);
					        $("#continueshoppingbottom", cntbuttons).button().click(updateDataEvent);
					        $("#checkouttop", cntbuttons).button().click(updateDataEvent);
					        $("#checkoutbottom", cntbuttons).button().click(updateDataEvent);

					        var cntclosebutton = Egghead.defaults.dialogcnt();
					        $("#closebutton", cntclosebutton).button().click(closeDialog);

					    }
					}
                });
            }
            //#endregion -- initialize Additional Items

            this.initialize();

            return this;
        }
    })
})(jQuery);
//#endregion -- additionalItems



//#region -- Initialize
$(function() {

    //#region -- ajax busy trailer
    $("body").append('<div id="ajaxBusy" style="z-index: 2000000;"><table width="100%"><tr><td align="center"><p><img src="images/spinner.gif" /></p></td></tr></table></div>');
    Egghead.busy.obj = $("#ajaxBusy").css({
        display: "none"
		, margin: "0px"
		, paddingLeft: "0px"
		, paddingRight: "0px"
		, paddingTop: "0px"
		, paddingBottom: "0px"
		, position: "absolute"
		, left: "3px"
		, top: "3px"
		, width: "0px"
    });

    $(document).ajaxStart(Egghead.busy.show)
		.ajaxStop(Egghead.busy.hide);

    $(document).mousemove(Egghead.busy.move);

    //#endregion -- ajax busy trailer

    //#region -- variant Popups
    $(".variantpopup").cartVariantPopup();
    $(".addreturnurl").each(function() {
        var url = $(this).attr("href");
        if (!url) return;
        url += "&ReturnUrl=" + escape(window.location);
        $(this).attr("href", url);
    });

    //#endregion -- variant Popups

    //#region -- datepickers
    $(".datepicker").datepicker();

    //#endregion -- datepickers

});

//#endregion -- Initialize


//#region Menu Delay Animation

var timer;
var originalHoveredMenuElement;
var newHoveredMenuElement;

var delay = 400;
var animationSpeed = 250;

$(document).ready(function() {

    $(".topnavlinklevel1").hover(
      function() {
          clearTimer();

          newHoveredMenuElement = $(this).parent().next();

          newHoveredMenuElement.parent().addClass("menuHover");

          setupMenuChangeTimer();
      },
      function() {

      }
    );
});

$(document).ready(function() {
    $(".topnavlinkmanufacturer").hover(
      function() {

          clearTimer();

          newHoveredMenuElement = $(this).next();

          newHoveredMenuElement.parent().addClass("menuHover");

          setupMenuChangeTimer();
      },
      function() {

      }
    );
});

$(document).ready(function() {
    $("#headernavbg").hover(
        function() {

        },
        function() {
            clearTimer();
            setupMenuHide();
        }
        );
});

function clearTimer() {

    if (newHoveredMenuElement) {
        newHoveredMenuElement.parent().removeClass("menuHover");
    }

    if (originalHoveredMenuElement) {
        originalHoveredMenuElement.parent().removeClass(animationSpeed);
    }

    if (timer) {
        clearTimeout(timer);
        timer = null
    }
}

function setupMenuChangeTimer() {
    timer = setTimeout(function() {
        newHoveredMenuElement.fadeIn(animationSpeed);
        if (originalHoveredMenuElement && newHoveredMenuElement[0] != originalHoveredMenuElement[0]) {
            originalHoveredMenuElement.fadeOut(animationSpeed);
        }
        originalHoveredMenuElement = newHoveredMenuElement;
    }, delay)
}

function setupMenuHide() {
    timer = setTimeout(function() {
        if (originalHoveredMenuElement) {
            originalHoveredMenuElement.fadeOut(animationSpeed);
        }
        clearTimer();
    }, delay)
}

//#endregion Menu Delay Animation
