var jQuery;

(function ($) {
    var win = $(window),
        images,
        activeImage = -1,
        activeURL,
        prevImage,
        nextImage,
        compatiblescrim,
        ie6 = !window.XMLHttpRequest,
        hiddenElements = [],
        preload = {},
        preloadPrev = new Image(),
        preloadNext = new Image(),
        scrim,
        focus,
        image,
        links,
        count;

    function stop() {
        preload.onload = null;
        preload.src = preloadPrev.src = preloadNext.src = activeURL;
        $([focus, image]).stop(true);
        $([links, image]).hide();
    }

    function animateBox() {
        $(image).css({
            backgroundImage: "url(" + activeURL + ")",
            visibility: "hidden",
            display: ""
        });
        $(image).width(preload.width);
        $(image).height(preload.height);
        $(links).css({
            visibility: "",
            display: ""
        });
        $(count).html(((images.length > 1) && (activeImage + 1) + " / " + (images.length)) || "");
        if (prevImage >= 0) {
            preloadPrev.src = images[prevImage][0];
        }
        if (nextImage >= 0) {
            preloadNext.src = images[nextImage][0];
        }
        $(focus).queue(function () {
            $(image).css({
                display: "none",
                visibility: "",
                opacity: ""
            }).fadeIn(600);
        });
    }

    function changeImage(imageIndex) {
        if (imageIndex >= 0) {
            activeImage = imageIndex;
            activeURL = images[activeImage][0];
            prevImage = (activeImage || (true ? images.length : 0)) - 1;
            nextImage = ((activeImage + 1) % images.length) || (true ? 0 : -1);
            stop();
            preload = new Image();
            preload.onload = animateBox;
            preload.src = activeURL;
        }
        return false;
    }

    $.fn.imgbox = function (options, linkMapper, linksFilter) {
        linkMapper = linkMapper ||
            function (el) {
                return [el.href, el.title];
            };
        linksFilter = linksFilter ||
            function () {
                return true;
            };
        var links = this;
        return links.unbind("click").click(function () {
            var link = this,
                startIndex = 0,
                filteredLinks,
                i = 0,
                length;
            filteredLinks = $.grep(links, function (el, i) {
                return linksFilter.call(link, el, i);
            });
            for (length = filteredLinks.length; i < length; i = i + 1) {
                if (filteredLinks[i] === link) {
                    startIndex = i;
                }
                filteredLinks[i] = linkMapper(filteredLinks[i], i);
            }
            return $.imgbox(filteredLinks, startIndex, options);
        });
    };

    function position() {
        var l = win.scrollLeft(),
            w = win.width();
        if (compatiblescrim) {
            $(scrim).css({
                left: l,
                top: win.scrollTop(),
                width: w,
                height: win.height()
            });
        }
    }

    function prev() {
        return changeImage(prevImage);
    }

    function next() {
        return changeImage(nextImage);
    }

    function setup(open) {
        if (open) {
            $("object").add(ie6 ? "select" : "embed").each(function (index, el) {
                hiddenElements[index] = [el, el.style.visibility];
                el.style.visibility = "hidden";
            });
        } else {
            $.each(hiddenElements, function (index, el) {
                el[0].style.visibility = el[1];
            });
            hiddenElements = [];
        }
        var fn = open ? "bind" : "unbind";
        win[fn]("scroll resize", position);
    }

    function exit() {
        if (activeImage >= 0) {
            stop();
            activeImage = prevImage = nextImage = -1;
            $(focus).hide();
            $(scrim).stop().fadeOut(600, setup);
        }
        return false;
    }

    $.imgbox = function (imagex, startImage, options) {

        if (typeof imagex === "string") {
            imagex = [
                [imagex, startImage]
            ];
            startImage = 0;
        }
        $(scrim).show();
        $(focus).show();
        setup(1);
        images = imagex;
        return changeImage(startImage);
    };

    $(function () {
        $("div").append(
            $([scrim = $('<div class="box scrim"/>')[0],
                links = $('<div class="box links"/>').append(
                    $('<a class="left" href="#">Previous&nbsp;</a>').click(prev)[0],
                    $('<a class="left" href="#">&#124; Next</a>').click(next)[0],
                    count = $('<div class="left count"/>')[0],
                    $('<a class="right" href="#">Close X</a>').click(exit)[0]
                )[0],
                focus = $('<div class="box focus"/>').append(
                    image = $('<div class="image"/>').click(next)[0]
                )[0]]).css("display", "none")
        );
    });

}(jQuery));

if (!/android|iphone|ipad|ipod|series60|symbian|windows ce|blackberry/i.test(navigator.userAgent)) {
    jQuery(function ($) {
        $("a[rel^='img']").imgbox({}, null, function (el) {
            return (this === el) || ((this.rel.length > 3) && (this.rel === el.rel));
        });
    });
}
