;(function($) {
    $.fn.gallery = function(settings) {
        var config = {
            loadFilter: ".gallery:first",
            template: '<div class="gallery-jquery"><div class="gallery-current" /><div class="gallery-next" /><div class="gallery-index-prev" /><div class="gallery-index"><div class="gallery-index-mover"><div class="gallery-index-item"><div class="gallery-index-item-mask" /></div></div></div><div class="gallery-index-next" /><div class="gallery-caption" /></div>',
            slideEase: $.easing ? "easeOutExpo" : "swing",
            slideSpeed: 1000,
            maskOpacity: 0.73
        };
 
        if (settings) $.extend(config, settings);
 
        return this.each(function() {
            var content = $(this).children().remove();
            var gallery = $(config.template);
            
            $(this).append(gallery);
            
            var galleryIndex = $(".gallery-index", gallery);
            var galleryIndexWidth = galleryIndex.width();
            var galleryIndexMover = $(".gallery-index-mover", gallery);
            var galleryItemTemplate = $(".gallery-index-item", galleryIndexMover);
            var galleryItemWidth = galleryItemTemplate.outerWidth(true);
            var galleryIndexPrevious = $(".gallery-index-prev", gallery);
            var galleryIndexNext = $(".gallery-index-next", gallery);
            
            galleryItemTemplate = galleryItemTemplate.remove();
            content = $(config.loadFilter, content);
            
            var galleryItems = $(".galleryitem", content);
            var numItems = galleryItems.length;
            var galleryItemOffset = 0;
            var itemsPerPage = Math.floor(galleryIndexWidth / galleryItemWidth);
            var numPages = Math.floor((numItems * galleryItemWidth) / galleryIndexWidth);
            if ((numItems * galleryItemWidth) % galleryIndexWidth) numPages++;
            
            gallery.data("galleryIndexWidth", galleryIndexWidth);
            gallery.data("galleryItemWidth", galleryItemWidth);
            gallery.data("itemsPerPage", itemsPerPage);
            gallery.data("numPages", numPages);
            gallery.data("numItems", numItems);

            //console.log("galleryIndexWidth = " + galleryIndexWidth);
            //console.log("galleryItemWidth = " + galleryItemWidth);
            //console.log("itemsPerPage = " + itemsPerPage);
            //console.log("numPages = " + numPages);
            
            galleryItems.each(function(idx) {
                var galleryItem = $(this);
                var caption = $(".caption", galleryItem);
                var largeImage = $(".largeimage img", galleryItem).addClass("large");
                var thumbnail = $(".thumbnail img", galleryItem);
                if (!thumbnail.length || thumbnail.attr("src").indexOf("resource") != -1) thumbnail = $(".largeimage img", galleryItem).clone().addClass("thumbnail");
                var item = galleryItemTemplate.clone();
                var mask = $(".gallery-index-item-mask", item);
                mask.css("opacity", 0.73).append('<span>' + (idx + 1) + ' of ' + numItems + "</span>");
                thumbnail.appendTo(item);
                caption.add(largeImage).hide().appendTo(item);
                
                item
                    .appendTo(galleryIndexMover)
                    .css({left: galleryItemOffset})
                    .mouseenter(function() { PopThumb(gallery, $(this)); });

                galleryItemOffset += galleryItemWidth;
                
            });
            
            galleryIndexPrevious.click(function() { SlidePrevious(gallery); });
            galleryIndexNext.click(function() { SlideNext(gallery); });
            
            GoTo(gallery, 1);
        });
        
        function SlideTo(gallery, page) {
            //console.log("SlideTo(gallery, " + page + ")");
            if (page == gallery.data("currentPage")) return;
            var oLeft = 0;
            if (page > 1) {
                var itemWidth = gallery.data("galleryItemWidth");
                var itemsPerPage = gallery.data("itemsPerPage");
                oLeft = itemWidth * itemsPerPage * (page - 1) * -1;
            }
            //console.log("easing = " + config.slideEase);
            var galleryIndexMover = $(".gallery-index-mover", gallery);
            galleryIndexMover.animate(
                    { left: oLeft },
                    config.slideSpeed,
                    config.slideEase);
            gallery.data("currentPage", page);
            
            $(".gallery-index-prev", gallery).toggleClass("gallery-index-prev-inactive", page == 1);
            $(".gallery-index-next", gallery).toggleClass("gallery-index-next-inactive", page == gallery.data("numPages"));
                      
        }

        function SlideToItemPage(gallery, item) {
            //console.log("SlidetoItemPage()");
            if (!item) {
                item = GetCurrentItem(gallery);
                if (!item) return;
            }
            var page = GetItemPage(gallery, item);
            if (page == gallery.data("currentPage")) return;
            SlideTo(gallery, page);
           
        }
        
        function GetItemPage(gallery, item) {
            //console.log("GetItemPage()");
            if (!item) {
                item = GetCurrentItem(gallery);
                if (!item) return;
            }
            var index = GetItemIndex(gallery, item);
            var itemsPerPage = gallery.data("itemsPerPage");
            var page = Math.floor(index / itemsPerPage);
            if (index % itemsPerPage) page++;
            
            return page;
        }
        function SlidePrevious(gallery) {
            //console.log("SlidePrevious()");
            var currPage = gallery.data("currentPage");
            if (currPage == 1) return;
            SlideTo(gallery, currPage - 1);
        }
        
        function SlideNext(gallery) {
            //console.log("SlideNext()");
            var currPage = gallery.data("currentPage");
            if (currPage == gallery.data("numPages")) return;
            SlideTo(gallery, currPage + 1);
        }
        
        function GetCurrentItem(gallery) {
            //console.log("GetCurrentItem()");
            return $(".gallery-item-active", gallery);
        }
        
        function GetCurrentPage(gallery) {
            var itemIndex = GetCurrentItemIndex(gallery);
        }
        
        function GetItemIndex(gallery, item) {
            //console.log("GetItemIndex()");
            if (!item) {
                item = GetCurrentItem(gallery);
                if (!item) return;
            }
            var index = item.add(item.siblings()).index(item) + 1;
            return index;
        }
        
        function PopThumb(gallery, thumb) {
            $(".gallery-index-item-zoom", gallery).remove();
            if (thumb.hasClass("gallery-item-active")) return;
            var idx = thumb.parent().children().index(thumb) + 1;
            var popped = thumb.clone();
            popped.addClass("gallery-index-item-zoom");
            var thumbPosition = thumb.position();
            var galleryIndexMover = thumb.closest(".gallery-index-mover");
            var indexPosition = galleryIndexMover.position();
            var oLeft = galleryIndexMover.offsetParent().position().left + indexPosition.left + thumbPosition.left;
            indexPosition = thumb.closest(".gallery-index").position();
            var oTop = indexPosition.top + thumbPosition.top;

            popped
                .css({
                    left: oLeft,
                    top: oTop
                })
                .fadeIn("fast")
                .click(function() { GoTo(gallery, idx, thumb)})
                .mouseleave(function() { $(this).remove(); })
                .appendTo(gallery);
     
        }
        
        function GoTo(gallery, idx, thumb) {
            var item = thumb;
            if (!item) item = $(".gallery-index-item:nth-child(" + idx + ")", gallery);
            if (!item.length || item.hasClass("gallery-item-active")) return;
            item.siblings().removeClass("gallery-item-active")
            var next = $(".gallery-next", gallery);
            var current = $(".gallery-current", gallery);
            var caption = $(".gallery-caption", gallery);
            var largeImageURL = $("img.large", item).attr("src");
            var itemCaption = $(".caption", item).clone();
            $(".gallery-index-item-zoom", gallery).fadeOut("normal", function() { $(this).remove });
            item.addClass("gallery-item-active");
            
            SlideToItemPage(gallery, item);
            
            next.css("background-image", "url('" + largeImageURL + "')").show();
            current.fadeOut("normal", function() {
                current.css("background-image", next.css("background-image")).show();
            });
            
            caption.children().remove();
            caption.append(itemCaption);
            itemCaption.fadeIn("slow");
            
            
            //For some reason, links do not open if in a popup window, this is the fix.
              $("a", caption).each(function() {
                  var href = $(this).attr("href");
                    $(this).click(function() {      
                      if (href != null) {
                        newwindow = window.open($(this).attr("href"),'_blank');
                        if (window.focus) {newwindow.focus()}
                      }
                      return false;
                });
              }); 
        }
    };

    $(document).ready(function() {
        $("a.gallery,a>.gallery").popup({target: '#container'});
        //window.setTimeout(function() {
            $("a.gallery img, a>.gallery img, img.gallery").buttonOverlay({text: 'View Gallery', type: 'button-overlay-gallery'});
        //}, 250);
        
    });
})(jQuery);
