/**
 * Gallery with sliding thumbs
 *
 * http://www.whiteoctober.co.uk
 * Dave Fletcher
 *
 * Licensed under the MIT (MIT-LICENSE.txt)
 *
 *
 */

jQuery.iFadingGallery = {
	
	// properties
	imageContainer: null,
	thumbArray: null,
	thumb: null,
	imagePreloader: null,

	/**
	 * selects a thumbnail
	 */	
	selectThumb: function() {
		
		$(this.mainpiccontainer).empty();
		if (this.rel == 'flash')
		{
			this.gallery.mainpiccontainer.append('<div id="galleryfalshcont"></div>');
			var so = new SWFObject(this.href, "galleryfalshcont", "630", "380", "7");
			so.write("galleryfalshcont");
		}
		else
		{
			this.gallery.imagePreloader.src = this.href;	
		}
		this.gallery.currentThumb = this;
		
		this.gallery.titleel.empty().append($(this).find('img').attr('alt'));

		return false;
	},


	/**
  * Performs all the actions once we've preloaded the image
  */
	replaceImage: function() {

		this.gallery.mainpiccontainer.append('<img src="'+this.src+'" style="display: none;" />');
		
		jQuery.iFadingGallery.centreImage(this.gallery, this.height, this.width);
		
		this.gallery.mainpiccontainer.find('img').fadeIn();
		
	},	

	/**
  * Resizes the image container
  */
	centreImage: function(gallery, heightNew, widthNew) {

		gallery.mainpiccontainer.find('img')
			.css('marginLeft', Math.floor((430-widthNew)/2))
			.css('marginTop', Math.floor((286-heightNew)/2));
					
	},

	
	/**
	 * Builds the gallery
	 */
	innit: function(options) {
		
		return this.each(
			function() {
				
				el = this;
				
				// bind the click event to the selectThumb function on each thumbnail
				$(this).find('.workthumbs a').bind('click', jQuery.iFadingGallery.selectThumb).each( function()
				{
					this.gallery = el;
					this.mainpiccontainer = $(el).find('.work-container');
				
				});
				this.titleel = $(this).find('h1');
				this.thumbs = $(this).find('.workthumbs a');
				this.mainpiccontainer = $(this).find('.work-container');
				this.imagePreloader = new Image();
				this.imagePreloader.gallery = this;
				
				$(this.imagePreloader).bind('load', jQuery.iFadingGallery.replaceImage);
				
				var strcurrentsrc = this.mainpiccontainer.find('img').attr('src');

				if (this.thumbs.get(0).rel == 'img')
				{
					$(this.mainpiccontainer).empty();
					this.imagePreloader.src = strcurrentsrc;
				}
					
				//if (this.mainImage.height() > 0) this.mainpiccontainer.height(this.mainImage.height());
				
			}
		);
	}

};

jQuery.fn.extend ({
	
	FadingGallery: jQuery.iFadingGallery.innit
	
});