/// <reference path="jquery-1.3.2-vsdoc.js" />
function MarkElementAsActive(element, ajaxLoad) {
    var href = element.attr("href");
    var selector;
    var substringPos = href.indexOf("#");
    if (substringPos > -1) {
        selector = href.substring(substringPos);
    }
    else {
        var elementId = element.attr("data-containerId");
        selector = "#" + elementId;
        element.attr("href", selector);
        var div;
        if ($(selector).length) {
            div = $(selector);
        }
        else {
            div = $("<div id='" + elementId + "' class='tabcontent inactive'>").html("Please wait");
            div.appendTo("#tabcontentcontainer");
        }
        if (ajaxLoad) {
            $.ajax({
                url: href,
                type: "GET",
                success: function(result) {
                    div.html(result);
                }
            });
        }
    }
    
    if (selector) {
        $("#tabcontentcontainer div.current").removeClass("current").addClass("inactive");
        $(selector).removeClass("inactive").addClass("current");
        $("#ddimagetabs li.current").removeClass("current").addClass("inactive");
        element.parent().addClass("current").removeClass("inactive");
    }

}


$(function() {
    $("#ddimagetabs a").click(function(e) {
        e.preventDefault();
        MarkElementAsActive($(this), true);
    });

    $("#ddimagetabs li.current a").click();

    $("a.view_review_link").live("click", function(e) {
        e.preventDefault();
        MarkElementAsActive($("#reviewTab"), false);
        if ($("#reviewlist").length === 0) {
            var url = this.href;
            $.ajax({
                url: url,
                type: "GET",
                success: function(result) {
                    $("#reviews").prepend(result);
                    $(".reviews_loader").remove();
                    $("#reviewform").hide();
                    BindForm();
                }
            });
        }
        else {
            $("#reviewform").hide();
            $("#reviewlist").show();
        }
    });

    $("a.write_review_link").live("click", function(e) {
        e.preventDefault();
        MarkElementAsActive($("#reviewTab"), false);
        if ($("#reviewform").length === 0) {
            var url = this.href;
            $.ajax({
                url: url,
                type: "GET",
                success: function(result) {
                    $("#reviews").prepend(result);
                    $(".reviews_loader").remove();
                    $("#reviewlist").hide();
                    BindForm();
                }
            });
        }
        else {
            $("#reviewform").show();
            $("#reviewlist").hide();
        }
    });
    
    $("div.pager a").live("click", function(e) {
        e.preventDefault();
        var url = this.href;
        $("#reviewlist").block();
        $.ajax({ 
            url: url,
            type: "GET",
            success: function(result) {
                $("#reviewlist").unblock();
                $("#reviewlist").remove();
                $("#reviews").prepend(result);
            }
        });
    });

    $("#products_see_more").click(function() {
        $("#ddimagetabs ul li:eq(0) a").click();
    });

    var carouselImages = $("ul.carousel_images li").length;
    if ($("ul.carousel_images li").length > 3) {
        // Set up the side pods! :)
        var left = $("<div class='carousel_nav'><span style='position: absolute; top: 30%; left:0'>&laquo;</span></div>").css({ left: 0, top: 0 });
        var right = $("<div class='carousel_nav'><span style='position: absolute; top: 30%; right:0'>&raquo;</span></div>").css({ right: 0, top: 0 });
        var minLeft = (carouselImages * 118 - 18) * (-1) + $(".carousel_container").width();
        $("div.carousel_container").prepend(left).append(right);
        left.hide();
        // Now set up the events...
        left.click(function() {
            var carousel = $(this).parent().find("ul");
            var currentLeft = carousel.position().left;
            var newLeft = (currentLeft + 95) > 0 ? 0 : (currentLeft + 95);
            $(this).parent().find("ul").animate({ left: newLeft + "px" }, function() {
                right.css({ display: "block" }).animate({ opacity: 0.5 });
            });
            if (newLeft === 0) {
                $(this).fadeOut();
            }
        });
        right.click(function() {
            var carousel = $(this).parent().find("ul");
            var currentLeft = carousel.position().left;
            var newLeft = (currentLeft - 95) < minLeft ? minLeft : (currentLeft - 95);
            $(this).parent().find("ul").animate({ left: newLeft + "px" }, function() {
                left.css({ display: "block" }).animate({ opacity: 0.5 });
            });
            if (newLeft === minLeft) {
                $(this).fadeOut();
            }
        });

    }


    $("#product_image ul.carousel_images a").click(function(e) {
        e.preventDefault();
        var newsrc = this.href;
        var zoomable = $(this).attr("data-zoomImageHref");
        var image = $("<img>").attr("src", newsrc).attr("alt", $(this).attr("title")).addClass("main_product_image");
        if (zoomable) {
            var href = $("<a>").attr("href", zoomable);
            var clickToZoom = $("<span class='zoom_flash'>Click to zoom</span>");
            href.append(image).append(clickToZoom);
            $("#product_image .product_main_image").empty().append(href);

        }
        else {
            $("#product_image .product_main_image").empty().append(image);
        }
        $(this).closest("ul")
                .children(".selected").removeClass("selected").addClass("unselected").end()
               .end()
               .closest("li").addClass("selected");

    });

    $("a.popup_link").click(function(e) {
        e.preventDefault();
        var header = $(this).text();
        var title = $(this).attr("title");
        var explanation = $("<div>").addClass("nwoexplanation").append("<h4>" + header + "</h4>").append("<p>" + title + "</p>").click(function() {
            $(this).remove();
        });
        $(this).after(explanation);
    });

    $("#product_image .product_main_image a").live("click", function(e) {
        e.preventDefault();
        var zoomlink = this.href;
        $parent = $(this).parent();
        $parent.block({ message: "<img src='/_RMVirtual/Images/ajax-loader.gif' alt='Loading' />", fadeIn: 0, css: { backgroundColor: 'transparent', border: 'none'} });
        $("<img>").bind("load", function() { // Note need to set src after bind :).
            $this = $(this);
            $parent.unblock({ fadeOut: 0 });
            var maxHeight = $(window).height() * 0.9;
            var maxWidth = $(window).width() * 0.9;
            var imageHeight = this.height;
            var imageWidth = this.width;
            var containerHeight = maxHeight > imageHeight ? imageHeight : maxHeight;
            var containerWidth = maxWidth > imageWidth ? imageWidth : maxWidth;
            var modalLeft = ($(window).width() - containerWidth) / 2;
            $this.width(containerWidth);
            $this.height("auto");
            var $controls = $("<div>").addClass("zoom_controls");
            var $container = $("<div>").addClass("zoom_container").append($this).append($controls);

            $("<a>").text("Zoom In").addClass("control_zoom_in").click(function(e) {
                e.preventDefault();
                var maxZoom = imageWidth * 3;
                var $img = $(this).parent().parent().children("img");
                var current = ($img.width() / maxZoom);
                var newValue = current + 0.1 > 1 ? 1 : current + 0.1;
                var newWidth = maxZoom * newValue;
                var newHeight = (newWidth / $img.width()) * $img.height();
                var yoffSet = e.pageY - $container.offset().top;
                var xoffSet = e.pageX - modalLeft;
                var newTop = (yoffSet / containerHeight) * (containerHeight - newHeight);
                var newLeft = (xoffSet / containerWidth) * (containerWidth - newWidth);
                $img.animate({ top: newTop + "px", left: newLeft + "px", width: newWidth + "px" }, 200);

            }).appendTo($controls);
            $("<a>").text("Zoom Out").addClass("control_zoom_out").click(function(e) {
                e.preventDefault();
                var maxZoom = imageWidth * 3;
                var $img = $(this).parent().parent().children("img");
                var current = ($img.width() / maxZoom);
                var lowerLimit = containerWidth / maxZoom;
                var newValue = current - 0.1 < lowerLimit ? lowerLimit : current - 0.1;
                var newWidth = maxZoom * newValue;
                var newHeight = (newWidth / $img.width()) * $img.height();
                var yoffSet = e.pageY - $container.offset().top;
                var xoffSet = e.pageX - modalLeft;
                var newTop = (yoffSet / containerHeight) * (containerHeight - newHeight);
                var newLeft = (xoffSet / containerWidth) * (containerWidth - newWidth);
                $img.animate({ top: newTop + "px", left: newLeft + "px", width: newWidth + "px" }, 200);
            }).appendTo($controls);
            $("<a>").text("Close").addClass("control_close").click(function() { $.unblockUI(); }).appendTo($controls);
            $controls.css({ position: "absolute", zIndex: 2, backgroundColor: "#000000", opacity: 0.5, bottom: "20px" });
            $controls.css({ left: ((containerWidth - 250) / 2.0) + "px" });
            $.blockUI({
                message: $container,
                css: {
                    top: "25px",
                    left: modalLeft + 'px',
                    height: containerHeight,
                    width: containerWidth,
                    overflow: "hidden"
                }
            });
            $this.bind("mousemove", function(e) {
                var yoffSet = e.pageY - $container.offset().top;
                var xoffSet = e.pageX - modalLeft;
                var minTop = containerHeight - $this.height();
                var newTop = (yoffSet / containerHeight) * minTop;
                newTop = newTop < minTop ? minTop : newTop;
                var newLeft = (xoffSet / containerWidth) * (containerWidth - $this.width());
                $this.css({ top: newTop + "px", left: newLeft + "px", position: "absolute" });

            });
            $this.bind("mousewheel", function(e, delta) {
                e.preventDefault();
                var maxZoom = imageWidth * 3;
                var newValue;
                var current = ($this.width() / maxZoom);
                // Zoom in
                if (delta > 0) {
                    newValue = current + 0.05 > 1 ? 1 : current + 0.05;
                }
                else if (delta < 0) {
                    var lowerLimit = containerWidth / maxZoom;
                    newValue = current - 0.05 < lowerLimit ? lowerLimit : current - 0.05;
                }

                // Need to calculate new tops and lefts for zoomed out images...
                var newWidth = maxZoom * newValue;
                var newHeight = (newWidth / $this.width()) * $this.height();
                var yoffSet = e.pageY - $container.offset().top;
                var xoffSet = e.pageX - modalLeft;
                var newTop = (yoffSet / containerHeight) * (containerHeight - newHeight);
                var newLeft = (xoffSet / containerWidth) * (containerWidth - newWidth);
                $this.css({ top: newTop + "px", left: newLeft + "px", width: newWidth + "px", height: "auto" });

            });
        }).attr("src", zoomlink).attr("alt", "Zoom");
    });
});

function BindForm() {
    $("#reviews form").fancyvalidate({
        submitHandler: function(form) {
            $(form).block();
            $(form).ajaxSubmit({
                success: function(result) {
                    $(form).unblock();
                    if ($(result).is(".product_review_list")) {
                        $("#reviewlist").replaceWith($(result));
                        $("#reviewform").remove();
                    }
                    else if ($(result).is(".review_form")) {
                        $("#reviewform").replaceWith($(result));
                        BindForm();
                    }
                }
            });
        }
    });
    $("input[name=Rating]").stars();
}

(function($) {
    $.fn.stars = function() {
        var starcontainer = $("<span>").addClass("review_stars");
        var ratingLabel = $("<label>").addClass("rating_label");
        var parent = $(this).parent();
        var accum = [];
        $(this).each(function() {
            var label = $(this).next("label");
            var radio = $(this);

            var img = $("<img />").attr("data-relatedInput", this.id).attr("src", "/_RMVirtual/images/customer_rating_empty.gif").attr("alt", label.text()).hover(function() {
                $(this).attr("src", "/_RMVirtual/images/customer_rating_full.gif").prevAll("img").attr("src", "/_RMVirtual/images/customer_rating_full.gif");
                $(this).nextAll("img").attr("src", "/_RMVirtual/images/customer_rating_empty.gif");
                ratingLabel.text($(this).attr("alt"));
                var relatedInputId = $(this).attr("data-relatedInput");
            }, function() {
                var radio = parent.find("input[type=radio]:checked")
                if (radio.length === 0) {
                    $(this).parent().children("img").attr("src", "/_RMVirtual/images/customer_rating_empty.gif");
                    ratingLabel.text("");
                }
                else {
                    var id = $(radio).attr("id");
                    var img = starcontainer.find("img[data-relatedInput='" + id + "']");
                    img.attr("src", "/_RMVirtual/images/customer_rating_full.gif").prevAll("img").attr("src", "/_RMVirtual/images/customer_rating_full.gif");
                    img.nextAll("img").attr("src", "/_RMVirtual/images/customer_rating_empty.gif");
                    ratingLabel.text(img.attr("alt"));
                }
                var relatedInputId = $(this).attr("data-relatedInput");
            }).click(function() {
                var radio = parent.find("input[type=radio]:checked");
                radio.removeAttr("checked");
                var relatedInputId = $(this).attr("data-relatedInput");
                radio = $("#" + relatedInputId);
                radio.attr("checked", true);
                radio.closest("form").validate().element(radio);
            }).appendTo(starcontainer);
            accum.push(img);
            if (radio.is(":checked")) {
                for (var i = 0; i < accum.length; i++) {
                    accum[i].attr("src", "/_RMVirtual/images/customer_rating_full.gif");
                }
            }
            label.hide();
            radio.hide();
        });
        starcontainer.append(ratingLabel);
        parent.prepend(starcontainer);
        return this;
    }

})(jQuery);


/*
* Special event for image load events
* Needed because some browsers does not trigger the event on cached images.

* MIT License
* Paul Irish     | @paul_irish | www.paulirish.com
* Andree Hansson | @peolanha   | www.andreehansson.se
* 2010.
*
* Usage:
* $(images).bind('load', function (e) {
*   // Do stuff on load
* });
* 
* Note that you can bind the 'error' event on data uri images, this will trigger when
* data uri images isn't supported.
* 
* Tested in:
* FF 3+
* IE 6-8
* Chromium 5-6
* Opera 9-10
*/
(function($) {
    $.event.special.load = {
        add: function(hollaback) {
            if (this.nodeType === 1 && this.tagName.toLowerCase() === 'img' && this.src !== '') {
                // Image is already complete, fire the hollaback (fixes browser issues were cached
                // images isn't triggering the load event)
                if (this.complete || this.readyState === 4) {
                    hollaback.handler.apply(this);
                }

                // Check if data URI images is supported, fire 'error' event if not
                else if (this.readyState === 'uninitialized' && this.src.indexOf('data:') === 0) {
                    $(this).trigger('error');
                }

                else {
                    $(this).bind('load', hollaback.handler);
                }
            }
        }
    };
} (jQuery));


/*! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
* Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
* Thanks to: Seamus Leahy for adding deltaX and deltaY
*
* Version: 3.0.4
* 
* Requires: 1.2.2+
*/

(function($) {

    var types = ['DOMMouseScroll', 'mousewheel'];

    $.event.special.mousewheel = {
        setup: function() {
            if (this.addEventListener) {
                for (var i = types.length; i; ) {
                    this.addEventListener(types[--i], handler, false);
                }
            } else {
                this.onmousewheel = handler;
            }
        },

        teardown: function() {
            if (this.removeEventListener) {
                for (var i = types.length; i; ) {
                    this.removeEventListener(types[--i], handler, false);
                }
            } else {
                this.onmousewheel = null;
            }
        }
    };

    $.fn.extend({
        mousewheel: function(fn) {
            return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
        },

        unmousewheel: function(fn) {
            return this.unbind("mousewheel", fn);
        }
    });


    function handler(event) {
        var orgEvent = event || window.event, args = [].slice.call(arguments, 1), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
        event = $.event.fix(orgEvent);
        event.type = "mousewheel";

        // Old school scrollwheel delta
        if (event.wheelDelta) { delta = event.wheelDelta / 120; }
        if (event.detail) { delta = -event.detail / 3; }

        // New school multidimensional scroll (touchpads) deltas
        deltaY = delta;

        // Gecko
        if (orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS) {
            deltaY = 0;
            deltaX = -1 * delta;
        }

        // Webkit
        if (orgEvent.wheelDeltaY !== undefined) { deltaY = orgEvent.wheelDeltaY / 120; }
        if (orgEvent.wheelDeltaX !== undefined) { deltaX = -1 * orgEvent.wheelDeltaX / 120; }

        // Add event and delta to the front of the arguments
        args.unshift(event, delta, deltaX, deltaY);

        return $.event.handle.apply(this, args);
    }

})(jQuery);
