(function ($) {

    jQuery.fn.center = function () {
        this.css("position", "absolute");
        this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
        this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
        return this;
    }

})(jQuery);

(function ($) {

    $.log = function (message) {
        if (window.console) {
            console.debug(message);
        }
    };

})(jQuery);

(function ($) {

    jQuery.fn.rating = function () {

        var api;

        if (!$(this).data("rating"))
            api = new ratingApi($(this), { name: "test" });
        else
            api = $(this).data("rating");

        $(this).data("rating", api);

        return api;

    };

    var ratingApi = function (container, settings) {

        var starApi;

        _init = function () {

            for (var i = 0; i <= 5; i = i + .5) {
                container.append("<input type=\"radio\" name=\"" + settings.name + "\" value=\"" + i + "\" />");
            }

            starApi = container.stars({
                split: 2,
                cancelShow: false
            });

        };

        this.value = function () {
            var ui = container.data("stars");
            return ui.options.value;
        };

        _init();

    };

})(jQuery);

(function ($) {

    $.fn.aperionDialog = function (options) {

        var isMethodCall = typeof options === "string",
            args = Array.prototype.slice.call(arguments, 1),
            returnValue = this;
        
        if (isMethodCall) {

            $(this).each(function () {

                var instance = $.data( this, "dialog" ),
					methodValue = instance && $.isFunction( instance[options] ) ?
						instance[ options ].apply( instance, args ) :
						instance;

				if ( methodValue !== instance && methodValue !== undefined ) {
					returnValue = methodValue;
					return false;
				}

            });

        } else {

            var settings = $.extend({}, $.fn.aperionDialog.defaults, options);

            $(this).each(function () {

                var dialog = new $.Dialog(settings, this);

                $.data( this, "dialog", dialog );
                
            });

        }

    };

    $.Dialog = function(options, element) {
        if (arguments.length) {
            this._createDialog(options, element);
        }
    }

    $.Dialog.prototype = {
        options: {},    
        _createDialog: function(options, element) {

            this.trigger = $(options.trigger);
            this.options = $.extend({}, $.fn.aperionDialog.defaults, options);
            this.template = $.fn.aperionDialog.buildTemplate($(element), options);
            
            var self = this;
            
            this.trigger.bind("click", function() {
                self.show();
            });

        },
        show: function() {

            if ($.isFunction(this.options.onBeforeShow)) {
                this.options.onBeforeShow( this.template );
            }

            this.template.overlay(this.options.overlay).load();
            
        }
    };

    $.fn.aperionDialog.defaults = {
        root: "body",
        closeTrigger: ".close",
        popupId: "__popup",
        wrapperClass: "popupContent",
        overlay: {
            api: true,
            color: "#ccc",
            expose: {
                color: "#000",
                loadSpeed: "fast"
            },
            absolute: false,
            top: "center",
            speed: "fast"
        }
    };

    $.fn.aperionDialog.buildTemplate = function (ctrl, options) {
    
        ctrl.wrap("<div id=\"" + options.popupId + "\" class=\"popup\"></div>");
        ctrl.wrap("<div class=\"" + options.wrapperClass + "\"></div>");

        $("#" + options.popupId).prepend("<div class=\"popupTitle\"><b>aperion</b>audio<a class=\"close\" href=\"javascript:void(0);\">close</a></div>");
        $("#" + options.popupId).appendTo(options.root);

        ctrl.show();

        return $("#" + options.popupId);

    };

})(jQuery);

jQuery.popup = function(options) {

    var templateHtml = "";
    templateHtml += "<div id=\"__popup\" class=\"popup\">";
    templateHtml += "    <div class=\"popupTitle\"><b>aperion</b>audio</div>";
    templateHtml += "    <div class=\"popupContent\"/>";
    templateHtml += "</div>";

    options = jQuery.extend(true, {
        popupElement: "#__popup",
        rootElement: "body",
        templateHtml: templateHtml,
        overlayOptions: {
            api: true,
            color: "#ccc",
            expose: {
                color: "#000",
                loadSpeed: "fast"
            },
            absolute: false,
            top: "center",
            speed: "fast"
        }
    }, options);

    $(options.rootElement).prepend(options.templateHtml);

    var popupCtrl = $(options.popupElement);
    
    options.onLoad(popupCtrl.find(".popupContent"));

    var overlayApi = popupCtrl.overlay(options.overlayOptions);

    overlayApi.load();

}

jQuery.addToCart = function (options) {

    var templateHtml = "";
    templateHtml += "<p><span class=\"productTitle\"></span>&nbsp;has been added to your cart.</p>";
    templateHtml += "<p>";
    templateHtml += "    <img class=\"close\" src=\"/app_themes/aperion/images/buttons/continue_shopping.gif\" />&nbsp;&nbsp;";
    templateHtml += "    <a href=\"/Basket/ShoppingCart.aspx\"><img src=\"/app_themes/aperion/images/buttons/view_cart_btn.gif\" /></a>";
    templateHtml += "</p>";

    options = jQuery.extend(true, {
        qty: 1,
        productNameElement: ".productTitle",
        productName: "The item",
        showPopup: true,
        rootElement: "body",
        onItemAdded: {},
        templateHtml: templateHtml
    }, options);

    $.ajax({
        url: options.serviceBaseUrl + "/ClientServices/Cart.svc/AddToCart",
        data: "skuId=" + options.sku + "&qty=" + options.qty + "&r=" + Math.random(),
        success: function (data) { console.log(data); }
    });

    if (options.showPopup) {

        $.popup({
            onLoad: function (parent) {
                parent.html(templateHtml);
                parent.find(options.productNameElement).text(options.productName);
            }
        });

    }

    if (typeof options.onItemAdded == "function")
        options.onItemAdded(options);

    return this;

};

jQuery.addToWishlist = function(options) {

    var templateHtml = "";
    templateHtml += "<p><span class=\"productTitle\"></span>&nbsp;has been added to your wishlist.</p>";
    templateHtml += "<p>";
    templateHtml += "    <img class=\"close\" src=\"/app_themes/aperion/images/buttons/continue_shopping.gif\" />&nbsp;&nbsp;";
    templateHtml += "    <a href=\"/Profile/AccountInfo.aspx?tabId=3\"><img src=\"/app_themes/aperion/images/buttons/view_wishlist_btn.gif\" class=\"WishlistLink\" /></a>";
    templateHtml += "</p>";

    options = jQuery.extend(true, {
        productNameElement: ".productTitle",
        productName: "The item",
        showPopup: true,
        rootElement: "body",
        onItemAdded: {},
        templateHtml: templateHtml
    }, options);

    $.ajax({
        url: options.serviceBaseUrl + "/ClientServices/Cart.svc/AddToWishlist",
        data: "skuId=" + options.sku,
        success: function(data) { }
    });

    if (options.showPopup) {

        $.popup({
            onLoad: function(parent) {
                parent.html(templateHtml);
                parent.find(options.productNameElement).text(options.productName);
                parent.find("a.WishlistLink").rollover("/app_themes/aperion/images/buttons/view_wishlist_btn_over.gif");
            }
        });

    }

    if (typeof options.onItemAdded == "function")
        options.onItemAdded(options);

    return this;

};

jQuery.fn.hoverClass = function(className) {

    this.each(function() {

        var $this = $(this);

        $this.hover(function() {
            $this.addClass(className);
        },
        function() {
            $this.removeClass(className);
        });

    });

    return this;

}

jQuery.fn.rollover = function(onImage, offImage) {
    return this.each(function() {    
        var currentImage = $(this).attr("src");            
        $(this).hover(function() {
            $(this).attr("src", onImage);
        }, function() {	
            if (offImage && offImage != "")
                $(this).attr("src",offImage);    
            else
                $(this).attr("src", currentImage);    
        });
        
    });
}

jQuery.fn.aperionBox = function() {
    $(this).find(".header .info").wrap("<div class=\"stripe\"><div class=\"west\"><div class=\"east\"></div></div></div>");
    $(this).find(".content .info").wrap("<div class=\"north\"><div class=\"west\"><div class=\"east\"><div class=\"south\"><div class=\"ne\"><div class=\"nw\"><div class=\"se\"><div class=\"sw\"></div></div></div></div></div></div></div></div>");
    $(this).addClass("roundContainer");
}
