(function( $ ){
    var imageCount = 0;
    var currentPage;
    var gallery;
    var pageLoading = false;
    var lock = false;

    var defaults = {
        mainImage:"#rightColumn",
        thumbs:"#bottomGallery",
        thumbExtraName:"_min",
        thumbCount:10,
        fadeOpacity:0.4,
        fadeSpeed:200,
        previous:"#galleryPrevious",
        next:"#galleryNext",
        pageNav:"#bottomGalleryNav"
    };
    var options;

    var methods = {
        init : function( settings ) {

            currentPage = 1;
            currentImage = 1;

            options = $.extend(defaults, settings);

            return this.each(function(){

                gallery = $(this);

                //find all thumbs
                gallery.find(".thumb").each(function(){
                    var el = $(this);

                    //load main image on click
                    el.click(function(){
                        if(!animationInProgress() && !el.hasClass("active") && !lock){
                            return methods.loadImage(el.attr("id").split("-")[1]);
                        }
                        else{
                            return false;
                        }
                    //fade to full opacity on mouseenter
                    }).hover(function(){
                        el.stop().fadeTo(options.fadeSpeed,1);
                    }, function(){
                        //fade to partial opacity on mouseleave if thumb's not active
                        if(!el.hasClass("active")){
                            el.stop().fadeTo(options.fadeSpeed,options.fadeOpacity);
                        }
                    });
                });

                //number of thumbs
                imageCount = gallery.find(".thumb").size();

                //create desired number of thumb containers and append thumbs to them
                for(var i = 1;i<=options.thumbCount;i++){
                    gallery.append('<div class="thumbContainer" id="thumbContainer-' + i + '"></div>');
                    $("#thumb-" + i).appendTo("#thumbContainer-" + i).fadeTo(0,options.fadeOpacity);
                }

                //page navigation
                var pageCount = Math.ceil(imageCount/options.thumbCount);
                for(var i = 1;i<=pageCount;i++){
                    var link = $('<a href="#" class="galleryPage" id="galleryPage-' + i + '">' + i + ' </a>');
                    if(i == 1){
                        link.addClass("selected");
                    }
                    link.click(function(){
                        if(!animationInProgress() && !lock){
                            return methods.page($(this).attr("id").split("-")[1]);
                        }
                        else{
                            return false;
                        }
                    });
                    link.appendTo(options.pageNav);
                }

                //previous button
                $(options.previous).click(function(){
                    if(!animationInProgress() && !lock){
                        return methods.previous();
                    }
                    else{
                        return false;
                    }
                });

                //next button
                $(options.next).click(function(){
                    if(!animationInProgress() && !lock){
                        return methods.next();
                    }
                    else{
                        return false;
                    }
                });

            });
        },
        next : function( ) {
            if(currentImage < imageCount && $(":animated").size() < 1){
                var goTo = currentImage + 1;
                if(goTo <= currentPage * options.thumbCount){
                    return methods.loadImage(goTo);
                }
                else{
                    return methods.page(currentPage + 1);
                }
            }
            return false;
        },
        previous : function( ) {
            if(currentImage > 1 && $(":animated").size() < 1){
                var goTo = currentImage - 1;
                if(goTo > ((currentPage - 1) * options.thumbCount)){
                    return methods.loadImage(goTo);
                }
                else{
                    return methods.page(currentPage - 1,options.thumbCount);
                }
            }
            return false;
        },
        page: function(page,imageNum){
            if(page != currentPage){

                currentPage = parseInt(page);

                $(".galleryPage.selected").removeClass("selected");
                $("#galleryPage-" + currentPage).addClass("selected");

                imageNum = typeof(imageNum) != 'undefined' ? imageNum : 1;
                pageLoading = true;

                $(".thumb").removeClass("active");

                $(".thumbContainer").each(function(){
                    var container = $(this);
                    var curThumb = container.find(".thumb");

                    var pagePosition = parseInt(container.attr("id").split("-")[1]);
                    var newThumbNum = ((currentPage - 1) * options.thumbCount + pagePosition);
                    var newThumb = $("#thumb-" + newThumbNum);

                    if(curThumb.attr("id") != undefined){
                        curThumb.fadeOut(options.fadeSpeed,function(){
                            
                            curThumb.appendTo(gallery);
                            if(newThumb.attr("id") != undefined){
                                var opacity = options.fadeOpacity;
                                if(pagePosition == imageNum){
                                    opacity = 1;
                                }
                                newThumb.appendTo(container).fadeTo(options.fadeSpeed,opacity);
                            }
                        });
                    }
                    else{
                        if(newThumb.attr("id") != undefined){
                            setTimeout(function(){
                                var opacity = options.fadeOpacity;
                                if(pagePosition == imageNum){
                                    opacity = 1;
                                }
                                newThumb.appendTo(container).fadeTo(options.fadeSpeed,opacity);
                            },options.fadeSpeed);
                        }
                    }
                });
            
                return methods.loadImage((currentPage-1) * options.thumbCount + imageNum);
            }
            return false;

        },
        loadImage: function(index){

            //need to make shure index IS actually an int
            index = parseInt(index);            

            currentImage = index;

            var thumbSrc = $("#thumb-" + index).attr("src");
            var dotPosition = thumbSrc.lastIndexOf(".");
            var imagePath = thumbSrc.substring(0,dotPosition-(options.thumbExtraName).length);
            var imageExtension = thumbSrc.substring(dotPosition,thumbSrc.length)
            
            //new image source
            var imageSrc = imagePath + imageExtension;
            var img = $(options.mainImage).find("img");

            //there is already an image in the container
            if(img.attr("src") != undefined){
                methods.lock(true);
                //after new image is loaded show it and hide (and remove!) the old one
                var newImg = $('<img src="' + imageSrc + '" />').load(function(){
                    methods.lock(false);
                    //not changing page
                    if(!pageLoading){
                        //unselect the active thumb
                        $(".thumb.active").removeClass("active").fadeTo(options.fadeSpeed, options.fadeOpacity);
                        //select active thumb according to the index
                        $("#thumb-" + index).addClass("active").fadeTo(options.fadeSpeed,1);
                    }
                    //changing page
                    else{
                        pageLoading = false;
                        $("#thumb-" + index).addClass("active");
                    }

                    img.fadeOut("fast",function(){
                        newImg.appendTo(options.mainImage).fadeIn("fast");
                        img.remove();
                    });
                });
            }
            //no image has been loaded yet
            else{
                $("#thumb-" + index).addClass("active").fadeTo(options.fadeSpeed,1);
                //append the first image to the mainImage container
                methods.lock(true);
                $('<img src="' + imageSrc + '" />').load(function(){
                    methods.lock(false);
                    $(this).appendTo(options.mainImage).show();
                });
            }
            return false;
        },
        lock:function(l){
            lock = l;
        }
    };

    $.fn.gallery = function(method){

        if ( methods[method] ) {
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.gallery' );
        }

        return this;
    };
})(jQuery);
