(function($) {
		
    $.fn.extend({
	    createGallery: function(options) {
		    return this.each(function() {
			    var $this = $(this);
			    $(window).load(function()	{
				    $.wvGallery.init($this, $.extend({}, $.fn.createGallery.defaults, options));
			    });
		    });
	    }
    });
			
    $.fn.createGallery.defaults = {
	    url: '/AJAX/gallery_contents.aspx',
	    onLoad: null,
	    imageList: {},
	    images: 'div.showing li',
	    thumbsContainer: 'div.thumbs',
	    thumbs: 'div.thumbs li',
	    thumbFade: 0.7,
	    thumbFadeDuration: 200,
	    numThumbsShown: 5,
	    currentPosition: 0,
	    scrollDuration: 500,
	    fixHeight: true,
	    maxHeight: 0,
	    loadingClass: 'ajax_loading',
	    loadingOpacity: 0.7
    };

    $.extend({
		
	    wvGallery: {
			
		    _uID: 0,
		    settings: [],
			
		    init: function(jQobj, settings)	{
			    var pointer = this;
			    var inst = this._uID;
			    // Save settings
			    this.settings[inst] = settings;
			    // First, get and save the max height, and set up the required padding on the first item
			    this.setupFirstPicture(jQobj, this.settings[inst]);
			    // Add in the left and right arrows
			    this.createScrollButtons(jQobj, inst);
			    // Fetch results
			    $.getJSON(this.settings[inst].url, function(reply)	{
				    $.each(reply.images, function(i, image)	{
					    $('<li><a href="#"><img /></a><p></p></li>').find('img').attr('src', image.filename).css({
						    'height': image.height + "px",
						    'padding-top': (parseInt(pointer.settings[inst].maxHeight - image.height) / 2) + "px",
						    'padding-bottom': (parseInt(pointer.settings[inst].maxHeight - image.height) / 2) + "px"
					    }).end()
						    .find('p').text(image.caption || '').end()
						    .appendTo($(pointer.settings[inst].images).parent());
				    });
				    pointer.calculateScrollDistance(jQobj, pointer, inst);
				    // Set the width of the thumb container
				    pointer.setThumbContainerWidth(jQobj, pointer.settings[inst]);
				    // Position captions
				    pointer.positionCaptions(jQobj, pointer.settings[inst]);
				    // Set up the thumbnail fading
				    pointer.setThumbFade(jQobj, pointer.settings[inst]);
				    // Set up show/hide for captions
				    pointer.setCaptionFade(jQobj, pointer.settings[inst]);
				    // Set up selection of new image
				    pointer.showNewPicture(jQobj, pointer.settings[inst]);
					// Click for next image
					pointer.clickForNextImage(jQobj, pointer.settings[inst]);
				    // Hide the loader!
				    $(pointer.settings[inst].images).addClass('loaded');
				    pointer.settings[inst].loadScreen.fadeOut(1000, function()	{	$(this).remove();	});
				    pointer._uID++;
			    });
		    },
			
		    setupFirstPicture: function(jQobj, settings)	{
			    // Set the CSS to include 'zoom: 1' for ie
			    $(jQobj).find(settings.images).css('zoom', 1);
			    // Get the maximum height and save it
			    settings.maxHeight = parseInt($(jQobj).find(settings.images).find('a').attr('rel'));
			    // Get this image's height
			    var height = parseInt($(jQobj).find(settings.images).find('img').height());
			    // Get this image's padding-top - half the difference in heights
			    var paddingTop = parseInt((settings.maxHeight - height) / 2);
			    // Remove the padding from the height
			    height = settings.maxHeight - paddingTop;
			    // Now we have the heights we cam create the loading overlay
			    this.createLoader(jQobj, settings);
			    // Apply the padding and the height and also morph the loader
			    $(jQobj).find(settings.images).animate({
				    'height': height,
				    'paddingTop': paddingTop	
			    }, 1000);
			    settings.loadScreen.animate({
				    'height': settings.maxHeight			
			    }, 1000);
		    },
			
		    createLoader: function(jQobj, settings)	{
			    var pointer = this;
			    settings.loadScreen = $('<div></div>').addClass(settings.loadingClass).appendTo(document.body);	
			    settings.loadScreen.css({
				    'top': $(jQobj).find(settings.images).eq(0).offset().top,
				    'left': $(jQobj).find(settings.images).eq(0).offset().left,
				    'width': $(jQobj).find(settings.images).eq(0).width(),
				    'height': $(jQobj).find(settings.images).eq(0).height(),
				    'opacity': settings.loadingOpacity
			    });
		    },
		
		    createScrollButtons: function(jQobj, inst)	{
			    // Save a reference to this plugin
			    var pointer = this;
			    var settings = this.settings[inst];
			    // Check to see if the number of thumbs is greater than the required thumbs shown
			    if($(jQobj).find(settings.thumbs).length > settings.numThumbsShown)	{
				    // Create buttons
				    settings.previousButton = $('<span class="previousButton">Previous thumbnails</span>');
				    settings.nextButton = $('<span class="nextButton">Next thumbnails</span>');
				    // Stick them in at the beginning and end of the thumb container
				    $(jQobj).find(settings.thumbsContainer).prepend(settings.previousButton).append(settings.nextButton);
				    // Add functionality
				    settings.previousButton.click(function()	{	
					    pointer.scrollLeft(jQobj, pointer, inst)	
				    });
				    settings.nextButton.click(function()	{	
					    pointer.scrollRight(jQobj, pointer, inst)	
				    });
			    }
		    },
		
		    scrollLeft: function(jQobj, pointer, inst)	{
			    if(pointer.settings[inst].currentPosition < 0)	{
				    pointer.settings[inst].currentPosition = parseInt($(pointer.settings[inst].thumbs).parent().css('left')) + pointer.settings[inst].scrollDistance;
				    // Temporarily remove the click event from the button
				    pointer.settings[inst].previousButton.unbind('click');
				    // Animate the scrolling....
				    $(jQobj).find(pointer.settings[inst].thumbs).parent().animate({
					    left: '+=' + pointer.settings[inst].scrollDistance + 'px'
				    },
				    {
					    duration: pointer.settings[inst].scrollDuration,
					    complete: function()	{
						    pointer.settings[inst].previousButton.click(function()	{	pointer.scrollLeft(jQobj, pointer, inst)	});
					    }
				    });
			    }
		    },
			
		    scrollRight: function(jQobj, pointer, inst)	{
			    if(-(pointer.settings[inst].currentPosition - pointer.settings[inst].scrollDistance) < pointer.settings[inst].totalThumbContainerWidth)	{
				    // Save the new position
				    pointer.settings[inst].currentPosition = parseInt($(pointer.settings[inst].thumbs).parent().css('left')) - pointer.settings[inst].scrollDistance;
				    // Temporarily remove the click event from the button
				    pointer.settings[inst].nextButton.unbind('click');
				    // Animate the scrolling....
				    $(jQobj).find(pointer.settings[inst].thumbs).parent().animate({
					    left: '-=' + pointer.settings[inst].scrollDistance + 'px'
				    },
				    {
					    duration: pointer.settings[inst].scrollDuration,
					    complete: function()	{
						    pointer.settings[inst].nextButton.click(function()	{	pointer.scrollRight(jQobj, pointer, inst)	});
					    }
				    });
			    }
		    },
			
		    calculateScrollDistance: function(jQobj, pointer, inst)	{
			    // Get the width of one of the thumbs
			    pointer.settings[inst].thumbWidth = $(jQobj).find(pointer.settings[inst].thumbs).eq(0).width();
			    // Add on any margin and padding
			    pointer.settings[inst].thumbWidth += parseInt($(jQobj).find(pointer.settings[inst].thumbs).eq(0).css('margin-left'));
			    pointer.settings[inst].thumbWidth += parseInt($(jQobj).find(pointer.settings[inst].thumbs).eq(0).css('margin-right'));
			    pointer.settings[inst].thumbWidth += parseInt($(jQobj).find(pointer.settings[inst].thumbs).eq(0).css('padding-left'));
			    pointer.settings[inst].thumbWidth += parseInt($(jQobj).find(pointer.settings[inst].thumbs).eq(0).css('padding-right'));
			    // Calculate how much to scroll the thumbs
			    pointer.settings[inst].scrollDistance = pointer.settings[inst].numThumbsShown * pointer.settings[inst].thumbWidth;
		    },
		
		    setThumbContainerWidth: function(jQobj, settings)	{
			    settings.totalThumbs = $(jQobj).find(settings.thumbs).length;
			    settings.totalThumbContainerWidth = settings.totalThumbs * settings.thumbWidth;
			    $(jQobj).find(settings.thumbs).parent().css('width', settings.totalThumbContainerWidth + "px");
		    },
			
		    setThumbFade: function(jQobj, settings)	{
			    $(jQobj).find(settings.thumbs).find('img').hover(
				    function()	{
					    $(this).animate(
						    {	opacity: settings.thumbFade	},
						    {	duration: settings.thumbFadeDuration,	queue: false	});
				    },
				    function()	{
					    $(this).animate(
						    {	opacity: 1	},
						    {	duration: settings.thumbFadeDuration,	queue: false	});
				    }
			    );
		    },
			
		    showNewPicture: function(jQobj, settings)	{
			    // Loop through all the thumbs
			    $(jQobj).find(settings.thumbs).find('a').click(function()	{
				    // Calculate which thumbnail was clicked on
				    var index = $(this).parents('ul').children().index(this.parentNode);
				    // Hide the existing image and show the new one
				    $(jQobj).find(settings.images).removeClass('current').css('display', '').eq(index).addClass('current');
				    return false;							 
			    });
		    },
		
		    positionCaptions: function(jQobj, settings)	{
			    $(jQobj).find(settings.images).css({
				    'position': 'relative',
				    'zoom': 1
			    }).find('p').css({
				    'position': 'absolute',
				    'bottom': '0'
			    });
		    },
		
		    setCaptionFade: function(jQobj, settings)	{
			    $(jQobj).find(settings.images).find('p').each(function()	{
				    if($(this).text() == '')	$(this).css('visibility', 'hidden');
			    });
			    $(jQobj).find(settings.images).hover(
				    function()	{	$(this).find('p').fadeIn();		},
				    function()	{	$(this).find('p').fadeOut();	}
			    );
			},
			
			
            clickForNextImage: function(jQobj, settings)	{
				var index, length = $(jQobj).find(settings.images).length - 1;
				$(jQobj).find(settings.images).find('A').click(function()	{
					$(jQobj).find(settings.images).each(function(i)	{
						if($(this).is(':visible'))	{
							index = i;
						}
					});
					if(index >= length)	{
						$(jQobj).find(settings.thumbs).eq(0).find('a').click();
					}
					else	{
						$(jQobj).find(settings.thumbs).eq(index + 1).find('a').click();
					}
					return false;
				});
			}			
		
	    }
		
    });
	


$(function()	{
    $('div.gallery').createGallery({
        url: '/AJAX/gallery_contents.aspx?storycode=' + Config.get('storycode'),
			           numThumbsShown:6
			           });
});

})(jQuery);