;(function($) {

    var defaults = {
	maxthumbs: 1,
	thumbnailcaption: false,
	displaycontainer: 'div.viewer div.image',
	captioncontainer: 'div.viewer div.caption',
	pager: 'div.viewer div.pages',
	pagerBetween: ' / ',
	prevDiv: 'div.viewer div.prev',
	nextDiv: 'div.viewer div.next',
	thumbs: 'ul li',
	galleryimages: 'ul li div.images',
	gallerycaption: 'ul li div.caption'
    };

    $.fn.gallery = function(settings) {
	$.extend(this, {

	    currentImage: 0,
	    currentGallery: 0,

	    init: function() {
		
		var $childrens = $(this.galleryimages, this);

		$.each($childrens, function(index) {
		    var $childs = $($childrens[index]).children();
		    $.each($childs, function(sub) {
			if (sub < gallery.maxthumbs) {
			    $childs.eq(sub).show();
			} else {
			    $childs.eq(sub).hide();
			}

			$childs.eq(sub).click(function() {
			    gallery.selectGallery(index, 0);
			    return false;
			});
		    });
		});

		if (! this.thumbnailcaption) {
		    $(this.gallerycaption, this).hide();
		}

                this.selectGallery(0, 0);
                this.setPager();

	    },

	    selectGallery: function(index, numimage) {

		var numimages = $(this.galleryimages).eq(index).children().length;
		if (! numimage || numimage < 0) { numimage = 0; }
		if (numimage > (numimages-1)) { numimage = 0; }

		this.currentImage = numimage;
		this.currentGallery = index;

		var caption = ($(this.gallerycaption, this).eq(index).html() || '');

		$(this.galleryimages, this).find('img.selected').removeClass('selected');
		$(this.galleryimages + ':eq(' + index + ')').find('img').addClass('selected');

		var image = $(this.galleryimages + ':eq(' + index + ')').find('a:eq(' + numimage + ')');
		var imageurl = image.attr('href');
		image = $('img', image).clone();

		if (imageurl) {
		    image.attr('src', imageurl).removeAttr('href');
		    image.attr('width', 320);
		    image.attr('height', 205);
		    $(this.displaycontainer, this).empty().append(image);
		}
		
		$(this.captioncontainer).empty().append(caption);

		$(this.pager, this).empty().append((numimage+1) + this.pagerBetween + numimages);

	    },

	    next: function() {
		this.selectGallery(this.currentGallery, (this.currentImage+1));
	    },

	    prev: function() {
		this.selectGallery(this.currentGallery, (this.currentImage-1));
	    },

	    setPager: function() {
		var $_this = gallery;
		$(this.prevDiv, this).click(function(event) {
		    $_this.prev();
		    event.preventDefault();
		    return false;
		});

		$(this.nextDiv, this).click(function(event) {
		    $_this.next();
		    event.preventDefault();
		    return false;
		});
	    }

	});

	$.extend(this, defaults, settings);
	var gallery = this;
	gallery.init();


    }

})(jQuery);

