(function($) {
    $.fn.gallery = function(options) {
        var defaults = {
            resize: true,
            filmstrip: false
        };

        var current = 0;
        options = $.extend(defaults, options);
        var timeout = null, title = "";
        var matchedObj = this;

        var showMaskControls = true;
        var html = $('<div class="overlay-gallery"><div class="overlay-gallery-mask">' +
                '<img src="" class="overlay-content"/><div class="overlay-gallery-left"/>' +
                '<div class="overlay-gallery-right"/><div class="filmstrip"/><a class="overlay-gallery-resize"/></div>' +
                '<div class="overlay-gallery-desc"/><a class="overlay-gallery-left-small"/>' +
                '<span class="overlay-gallery-pager"/><a class="overlay-gallery-right-small"/>' +
                '<a class="overlay-gallery-play"/><a class="overlay-gallery-close"/>' +
                '</div>');

        var w = 100,h = 100,l = (($(window).width() - 100) / 2),t = (($(window).height() - 100) / 2);
        var youtube = '<iframe title="YouTube video player" width="480" height="390" src="" frameborder="0" ' +
                'allowfullscreen></iframe>';
        var canClose = false;

        var controlsSelector = '.overlay-gallery-desc, .overlay-gallery-pager, .overlay-gallery-left-small, ' +
                '.overlay-gallery-right-small, .overlay-gallery-play, .overlay-gallery-close';
        var maskSelector = '.overlay-gallery-right, .overlay-gallery-left, .overlay-gallery-can-resize, .overlay-gallery .filmstrip';
        var overlay = function() {
            $(".overlay-gallery, .overlay-background").show();
            $(".overlay-background").css("opacity", 0.8);
        };

        var close = function() {
            stop();
            if (canClose) {
                $(".overlay-gallery").fadeOut(function() {
                    $(".overlay-background").hide().remove();
                    $(".overlay-gallery").remove();
                });
            }

        };

        var next = function() {
            stop();
            if (current < $(matchedObj).size() - 1) {
                $(matchedObj).eq(current + 1).click();
            } else if (current == $(matchedObj).size() - 1) {
                $(matchedObj).eq(0).click();
            }
        };
        var prev = function() {
            stop();
            if (current > 0) {
                $(matchedObj).eq(current - 1).click();
            } else if (current == 0) {
                $(matchedObj).eq($(matchedObj).size() - 1).click();
            }
        };

        var stop = function() {
            if (timeout != null) {
                clearInterval(timeout);
                timeout = null;
            }
        };

        var nextContinuous = function() {
            if (current < $(matchedObj).size() - 1) {
                $(matchedObj).eq(current + 1).click();
            } else if (current == $(matchedObj).size() - 1) {
                $(matchedObj).eq(0).click();
            }
        };

        var play = function() {
            stop();
            if ($(this).hasClass("overlay-gallery-pause")) {
                $(this).removeClass("overlay-gallery-pause");
            } else {
                nextContinuous();
                $(this).addClass("overlay-gallery-pause");
                timeout = setInterval(nextContinuous, 2000);
            }
        };

        var resizeFit = function(w1, h1, resize) {
            w = w1;
            h = h1;
            var winH = $(window).height() - 20;
            var winW = $(window).width() - 20;
            if (winW < w1 && resize != false) {
                w = winW;
                h = h1 / (w1 / winW);
            }
            if (winH < h1 && resize != false) {
                h = winH;
                w = w1 / (h1 / winH);
            }
            l = ((winW - w) / 2);
            t = ((winH - h) / 2);
            if (t < 0) {
                t = 0;
            }
            if (l < 0) {
                l = 0;
            }
        };


        var resize = function() {
            $(".overlay-gallery-resize").removeClass("overlay-gallery-can-resize").hide();
            var img = $(".overlay-gallery-mask .overlay-content").css({width:"", height:""});
            $(".overlay-gallery-mask").css({width:img.width() + "px", height: img.height() + "px"});
            $(".overlay-gallery .filmstrip").css({width:(img.width() - 50) + "px"});

            resizeFit(img.width(), img.height(), false);
            h += $(".overlay-gallery-desc").height() + 24;
            $(".overlay-gallery-left, .overlay-gallery-right").css({width: (img.width() / 2) + "px"});
            $(".overlay-gallery").css({
                width: w + "px",
                height: h + "px",
                left: l + "px",
                top: t + ($(document).scrollTop()) + "px"
            });
        };
        var init = function() {
            $(".overlay-gallery-resize").hide();
            if ($(".overlay-background").size() == 0) {
                $('<div class="overlay-background"/>').appendTo("body").hide().click(close);
                $("body").append(html.hide());

                $(".overlay-gallery-resize").click(resize);
                $(".overlay-gallery-left, .overlay-gallery-left-small").click(prev);
                $(".overlay-gallery-right, .overlay-gallery-right-small").click(next);
                $(".overlay-gallery-play").click(play);

                $(".overlay-gallery-close").click(close);
                $(".overlay-gallery-mask").mouseover(
                        function() {
                            if (showMaskControls) {
                                $(maskSelector).fadeIn();
                            }
                        }).mouseleave(function() {
                    $(maskSelector).fadeOut();
                });
            }
        };

        var openFilmstrip = function() {
            $(".filmstrip").css("width", (w - 48) + "px").empty();
            $(matchedObj).each(function(i) {
                $(".overlay-gallery .filmstrip").append($(this).clone().click(stop).click(open));
            });
            $(".filmstrip").filmstrip();
        };


        var loadComplete = function() {
            var img = $(this);

            //img.hide();

            //$(".overlay-gallery-mask").prepend(img);
            $(controlsSelector).hide();
            $(".overlay-gallery-desc").html(title + "&nbsp;");
            $(".overlay-gallery-pager").html((current + 1) + " / " + $(matchedObj).size());
            resizeFit(img.width(), img.height(), showMaskControls);
            $(".overlay-gallery-mask").add(img).css({width: w + "px", height: h + "px"});
            $(".overlay-gallery").animate({
                width: w + "px",
                height: h + "px",
                left: l + "px",
                top: (t + $(document).scrollTop()) + "px"
            }, function() {
                if (!img.is(":visible")) {
                    img.fadeIn(1000);
                }

//                img.fadeIn(1000, function() {
//
//                    //$(".left, .right, .filmstrip, .scroll-left, .scroll-right").hide();
//                });
                if (current > 0) {
                    var left = $(".overlay-gallery-left").css({
                        width: (img.width() / 2) + "px"
                    }).fadeIn();
                }
                if (current < $(matchedObj).size() - 1) {
                    var right = $(".overlay-gallery-right").css({
                        width: (img.width() / 2) + "px"
                    }).fadeIn();
                }

                if (timeout != null) {
                    $(".overlay-gallery-play").addClass("overlay-gallery-pause");
                }

                var diffHeight = $(".overlay-gallery-desc").height() + 23;
                if (t < diffHeight && showMaskControls) {
                    $(".overlay-gallery-resize").show().addClass("overlay-gallery-can-resize");
                    $(".overlay-gallery-mask").animate({height: h - diffHeight}, function() {
                        $(controlsSelector).fadeIn();
                    });
                } else {
                    $(".overlay-gallery-resize").show().removeClass("overlay-gallery-can-resize").hide();
                    h += diffHeight;
                    $(".overlay-gallery").animate({height: h + "px",top: (t + $(document).scrollTop()) + "px"},
                            function() {
                                $(controlsSelector).fadeIn();
                            });
                }
                if (options.filmstrip) {
                    openFilmstrip();
                }
                $(controlsSelector + "," + maskSelector).hide();
                canClose = true;
            });
        };

        var open = function() {
            init();
            canClose = false;
            current = 0;
            var href = $(this).attr("href");
            $(matchedObj).each(function(i) {
                if ($(this).attr("href") == href) {
                    current = i;
                }
            });
            title = $(this).attr("title");
            overlay();

            $(".overlay-gallery").css({
                width: w + "px",
                height: h + "px",
                left: l + "px",
                top: (t + $(document).scrollTop()) + "px"
            });
            try {
                $(".overlay-content.youtube").remove();
                $(".overlay-content").fadeOut(1000, function() {
                    $(this).remove();

                });
                var img = $('<img src="' + href + '"/>');
                showMaskControls = true;
                if (href.indexOf("youtube.com") != -1) {
                    var img = $(youtube).attr("src", href).addClass("youtube");
                    showMaskControls = false;
                } else {
                    img.hide();
                }
                stop();
                $(".overlay-gallery-mask").prepend(img);
                img.addClass("overlay-content");
                img.load(loadComplete);
            } catch(e) {
                alert(e);
            }
            return false;
        };

        return this.each(function() {
            $(this).click(open);
        });
    }
})(jQuery);
