﻿/// <reference path="jquery-1.3.2.min-vsdoc.js" />

var AnimThumb = function(element, options) {
    element = $(element);
    element.data("hovering", true);
    var settings = $.extend({
        scaleFactor: 1.7,
        speed: 340,
        clickCallback: function() { }
    }, options || {});
    if (typeof (settings.speed) == "string") {
        switch (settings.speed) {
            case "slow":
                settings.speed = 1000;
                break;
            case "normal":
                settings.speed = 500;
                break;
            case "fast":
                settings.speed = 250;
                break;
            default:
                settings.speed = 500;
                break;
        }
    }

    var startSize = {
        w: parseInt(element.attr("width")),
        h: parseInt(element.attr("height"))
    };
    var endSize = {
        w: startSize.w * settings.scaleFactor,
        h: startSize.h * settings.scaleFactor
    };
    var pos = {
        t: element.offset().top,
        l: element.offset().left
    };
    var idParts = /^gallery_thumb-([0-9]+)_idx-([0-9]+)$/i.exec(element.attr("id")),
        imgID = parseInt(idParts[1]),
        index = parseInt(idParts[2]);

    if (!element.data("placeholderCreated")) {
        $("<span id='placeholder-" + index + "'></span>")
            .css({
                display: "block",
                width: startSize.w + "px",
                height: startSize.h + "px",
                marginTop: (140 - startSize.h) / 2 + "px",
                border: "solid 1px transparent",
                zIndex: 0
            })
            .insertBefore(element);
        element.data("placeholderCreated", true);
    }

    element
        .addClass("anim_thmb")
        .css({
            zIndex: 1000,
            position: "absolute",
            left: pos.l + "px",
            top: pos.t + "px",
            marginTop: 0
        })
        .appendTo(document.body)
        .mouseout(function() {
            $(this).unbind("mouseout").unbind("click").data("hovering", false);
            $("#ts-" + imgID)
                .css({ zIndex: 100 })
                .animate(
                    {
                        width: startSize.w + "px",
                        height: startSize.h + "px",
                        left: pos.l + "px",
                        top: pos.t + "px",
                        opacity: 0.0
                    },
                    settings.speed,
                    function() { $("#ts-" + imgID).remove(); }
                );
            $(this)
                .css({ zIndex: 200 })
                .animate(
                    {
                        width: startSize.w + "px",
                        height: startSize.h + "px",
                        top: pos.t + "px",
                        left: pos.l + "px"
                    },
                    settings.speed
                );
        })
        .click(function() {
            $(this).trigger("mouseout");
            settings.clickCallback(index, imgID);
        });

    element.animate(
        {
            width: endSize.w + "px",
            height: endSize.h + "px",
            top: (pos.t - ((endSize.h - startSize.h) / 2)) + "px",
            left: (pos.l - ((endSize.w - startSize.w) / 2)) + "px"
        },
        settings.speed
    );

    $("<div id='ts-" + imgID + "' class='shadow'></div>").insertBefore(element);
    $("#ts-" + imgID)
        .css({
            width: startSize.w + "px",
            height: startSize.h + "px",
            left: pos.l + "px",
            top: pos.t + "px",
            opacity: 0.0
        })
        .animate(
            {
                width: (endSize.w * 1.1) + "px",
                height: (endSize.h * 1.1) + "px",
                left: pos.l - (startSize.w / 8) + "px",
                top: pos.t - (startSize.h / 8) + "px",
                opacity: 0.2
            },
            settings.speed
        );
};

if (typeof Crispulo == "undefined") { Crispulo = {}; }
if (typeof Crispulo.Gallery == "undefined") { Crispulo.Gallery = {}; } 

(function gallery() {
    var _previewShowing = false,
        _previewScrolling = false,
        _category = $("#current-category").val(),
        _currentLiId = 0, // id of the li element for the current thumb
        _liCount = $("#thumbs li ul li").length, // total number of thumbs (li) in category
        previewImage = {},
        previewWindow = $("#preview");

    $("#gallery-categories li a").removeClass("current-category");
    $("#gallery-categories li a." + _category).addClass("current-category");
    $("#gallery-categories li a.current-category").click(function(e) { e.preventDefault(); });

    function DisplayPreview(index, imgId) {
        _currentLiId = index; //debugger;
        LoadPreviewImageData(imgId);

        $("#overlay")
            .css({
                display: "block",
                opacity: 0,
                width: document.body.clientWidth + "px",
                height: document.body.clientHeight + "px"
            })
            .fadeTo("slow", 0.7, function() {
                //debugger;
                $("#preview_previous, #preview_next").hide().css({ top: ($(window).height() / 2) + $(window).scrollTop() + "px" });
                $("#preview_close").hide().css({ top: $(window).height() + $(window).scrollTop() - 34 + "px" });
                previewWindow.show();
                var previewOptions = {
                    display: "none",
                    opacity: 0.0,
                    width: 0,
                    height: 0,
                    top: ($(window).height() / 2) + $(window).scrollTop() + "px",
                    left: $(window).width() / 2 + "px"
                };
                ResizePreviewWindow(imgId, previewOptions);
            });
        return false;
    }

    function ResizePreviewWindow(imgId, initialSettings) {

        var center = {
            x: $(window).width() / 2,
            y: ($(window).height() / 2) + $(window).scrollTop()
        };
        var speed = _previewShowing ? 600 : 1000;

        previewWindow
            .css(initialSettings)
            .animate(
                {
                    opacity: 1.0,
                    width: previewImage.scaledWidth + "px",
                    height: previewImage.scaledHeight + 28 + "px",
                    top: (center.y - ((previewImage.scaledHeight + 80) / 2)) + "px",
                    left: (center.x - ((previewImage.scaledWidth + 28) / 2)) + "px"
                },
                speed,
                function() {
                    //debugger;
                    $("#preview_title").hide().html(previewImage.title).fadeIn("slow");
                    var prevImgStyles = "margin: 26px auto 0; " +
                        "width: " + previewImage.scaledWidth + "px; height: " + previewImage.scaledHeight + "px;";
                    $("#preview_image").hide().append(
                        "<img src='/Content/images/gallery/" + previewImage.name + "' alt='" +
                            previewImage.title + "' style='" + prevImgStyles + "' id='preview_img' " +
                            "width='" + previewImage.scaledWidth + "' height='" + previewImage.scaledHeight + "' />"
                    ).fadeIn("slow", function() {
                        $(".preview_button").fadeIn("slow", function() {
                            $(this).each(function() {
                                $(this).fadeTo(1200, 0.5);
                            });
                        });
                    });

                    $("#preview_img").click(function() {
                        ClosePreviewWindow();
                    });

                    _previewShowing = true;
                    _previewScrolling = false;
                });
    }

    function ClosePreviewWindow() {
        var prevObj = {
            width: 0,
            height: 0,
            left: "50%",
            top: "50%"
        };
        previewWindow
            .fadeOut(1000, function() {
                $("#preview_title").html("");
                $("#preview_image")
                    .find("#preview_img")
                        .remove()
                    .end()
                    .css("display", "none");
                previewWindow.css(prevObj)
                _previewShowing = false;
            });

        $(".preview_button")
            .fadeOut(800);

        var overObj = {
            display: "none",
            opacity: 0.0
        };
        $("#overlay")
            .fadeOut(1000, function() {
                $("#overlay").css(overObj);
            });

    }

    function LoadPreviewImageData(id) {
        $.ajax({
            url: "/gallery/" + _category + "/preview/",
            data: { id: id },
            type: "GET",
            async: false,
            success: function(data) {
                previewImage = data;
            },
            error: function(data) {
                //debugger;
                var text = data.responseText;
                // TODO: remove next line and display proper error message
                //$("#jsonerror").html(text);
            },
            dataType: "json"
        });
    }

    // register page events
    $("ul#thumbs li a img").mouseover(function() {
        var elem = arguments[1] || this;
        if (!$(elem).data("hovering")) {
            new AnimThumb($(elem), { clickCallback: DisplayPreview });
        }
    });
    $(".preview_button")
        .hover(
            function() { $(this).fadeTo("normal", 1.0); },
            function() { $(this).fadeTo("normal", 0.5); }
        )
        .not("#preview_close")
        .click(function(e) {
            if (_previewScrolling) {
                e.preventDefault();
                return;
            }
            _previewScrolling = true;

            if ($(this).attr("id") == "preview_next") {
                _currentLiId++;
                if (_currentLiId >= _liCount) { _currentLiId = 0; }
            }
            else {
                _currentLiId--;
                if (_currentLiId < 0) { _currentLiId = _liCount - 1; }
            }
            var image = $("img[id$=_idx-" + _currentLiId + "]");
            var imgId = /^gallery_thumb-([0-9]+)_idx-[0-9]+$/i.exec(image.attr("id"))[1];
            var position = previewWindow.position();
            var previewOptions = {
                display: "none",
                width: previewWindow.width() + "px",
                height: previewWindow.height() + "px",
                top: position.top,
                left: position.left
            };

            $("#preview_img").fadeOut(600, function() {
                $(this).remove();
                LoadPreviewImageData(imgId);
                ResizePreviewWindow(imgId, previewOptions);
            });
            $("#preview_title").fadeOut(600);
            return false;
        });

    $("#preview_close")
        .click(function() {
            ClosePreviewWindow();
            return false;
        });

    // trigger an auto preview if the current page is loading from a click on a footer preview
    if (Crispulo.Gallery.redirectingFromFooter) {
        var id = Crispulo.Gallery.footerRedirectImageId;
        var image = $("img[id^=gallery_thumb-" + id + "]");
        if (image) {
            image.trigger("mouseover").stop(true, false);
            $("#ts-" + id).stop(true, false);
            window.setTimeout(function() { image.trigger("click"); }, 80);
        }
    }
})();