
(function($)
{
function SaltGalleryHolder(gallery)
{
	this.galleries = [];
	this.gallery = gallery;
	this.activeGallery = -1;
}
SaltGalleryHolder.galleryHolders = [];
SaltGalleryHolder.getInstance = function(object)
{
	for(var i in SaltGalleryHolder.galleryHolders)
	{
		if(SaltGalleryHolder.galleryHolders[i].get().is($(object).selector))
		{
			return(SaltGalleryHolder.galleryHolders[i]);
		}
	}
	
	var rtn = new SaltGalleryHolder(object);
	SaltGalleryHolder.galleryHolders.push(rtn);
	return rtn;
}
$pr = SaltGalleryHolder.prototype;
$pr.addGallery = function(gal)
{
	if(typeof gal == 'object' && gal.isGallery == true)
	{
		this.galleries.push(gal);
	}
}
$pr.setActiveGalleryHolder = function(gal)
{
	for(var i in this.galleries)
	{
		if(this.galleries[i].id == gal.id)
		{
			if(this.activeGallery >=0 && i != this.activeGallery)
			{
				this.galleries[this.activeGallery].close();
			}
			this.activeGallery = i;
		}
	}
}
$pr.get = function()
{
	return $(this.gallery);
}

function SaltGallery(element, options)
{
	if(typeof element == 'undefined') return this;

	// initialise the elements
	this.element			= $(element);
	var id					= this.element.attr('id');
	this.id					= id.split('-')[1];
	
	// initialise the variables
	this.running			= false;
	this.timer				= null;
	this.counter			= 0;
	this.length				= this.element.children().length;
	
	// initialise the settings
	this.animationtype		= options.animationtype;
	this.speed				= options.speed;
	this.easing				= options.easing;
	this.autorun			= options.autorun;
	this.timeout			= options.timeout;
	this.containerheight	= options.containerheight;
	this.gallerydelegate	= options.gallerydelegate;
	this.imageClick			= options.imageClick;
	this.gallerycontainer	= options.gallerycontainer;
	this.clickthroughClass	= options.clickthroughClass;
	
	this.cb_imageDisplay	= options.onImageDisplay;
	this.cb_mageUnload		= options.onImageUnload;
	this.cb_startTransition	= options.onStartTransition
	
	this.holder				= null;
	
	this.initialimage		= null;
	
	SaltGallery.objects[this.id] = this;
	
	this.isImagePreloaded = false;
	
	this.init();
}
SaltGallery.objects = {};
SaltGallery.getGalleryByName = function(name)
{
	return SaltGallery.objects[name];
}
_$pr = SaltGallery.prototype;
_$pr.isGallery = true;

_$pr.init = function()
{
	var p = this;
	var hasInitialImage = false;
	
	if(this.gallerycontainer)
	{
		this.holder = $(this.gallerycontainer);
	} else
	{
		this.holder = $('div#gallery-'+this.id);
	}
	
	var initialimg = $('img',this.holder);
	if(initialimg.length > 0)
	{
		hasInitialImage = true;
		if (!this.isImagePreloaded)
		{
			this.initialimage = initialimg;
			var op = this.initialimage[0];
			$(op).load(function()
			{
				p.isImagePreloaded = true;
				p.init();
			});
			
			var src = op.src;
			op.src = '';
			op.src = src;
			
			return;
		}
	}
	
	var css = {
		'position'	: 'relative',
		'overflow'	: 'hidden'
	};
	this.holder.css(css);
	
	this.holder.height(this.holder.innerHeight());
	this.holder.wrapInner(this.createWrapper());
	this.imageItem = $('div.SaltGalItem', this.holder);
	if(this.holder.length < 1)
	{
		this.holder = $('<div class="item-gallery"></div>');
		this.element.before(this.holder);
	}
	
	this.holder = SaltGalleryHolder.getInstance(this.holder);
	this.holder.addGallery(this);
	
	this.element.click(function(e,skipImage)
	{
		if(e.target.nodeName.toLowerCase() != 'a')
		{
			var a = $(e.target).parent('a')[0];
		} else
		{
			var a = $(e.target);
		}
	
		if($(a).length>0)
		{
			var gallery		= SaltGallery.getGalleryByName($(this).attr('id').split('-')[1]);
			
			gallery.goGalByAnchor($(a), skipImage);
		}
		
		return false;
	});
	
	// trigger the first gallery item
	if(hasInitialImage)
	{
		this.goGalByNum(0,true);
	}
}

_$pr.createWrapper = function()
{
	var p = this;
	var $wrapper = $('<div class="SaltGalItem" id="SaltGalItem-'+this.id+'">');
	var css = {
		'position'	: 'absolute',
		'top'		: '0px',
		'z-index'	: 2
	}
	$wrapper.css(css);
	
	if(typeof this.imageClick == 'function')
	{
		$wrapper.click(function(e)
		{
			if(p.running)
			{
				return false;
			}
			p.imageClickCallback(e);
		});
	}

	
	return $wrapper;
}

_$pr.imageClickCallback = function(e)
{
	if(typeof this.imageClick == 'function')
	{
		this.imageClick(e,this);
	}
}

_$pr.goGalByNum = function(position,skipImage)
{
	$($('a', $('>*',this.element)[position])[0]).trigger('click',skipImage);
}

_$pr.goNextGalItem = function()
{
	this.goGalByNum(this.setCounter(this.getCounter()+1));
}

_$pr.setCounter = function(counter)
{
	if(counter < 0)
	{
		this.counter = this.length-1;
	} else if(counter >= this.length)
	{
		this.counter = 0;
	} else
	{
		this.counter = counter;
	}
	
	return this.counter;
}

_$pr.getCounter = function()
{
	return this.counter;
}

_$pr.goGalByAnchor = function(a, skipImage)
{
	this.holder.setActiveGalleryHolder(this);

	if(this.running)
	{
		return false;
	}
	
	clearTimeout(this.timer);
	
	this.running = true;
	
	// set up the image packet
	var p = this;
	var parentcontainer			= a.parent();
	this.imagepacket			= {};
	this.imagepacket.href		= a.attr('href');
	this.imagepacket.ct			= $('.'+this.clickthroughClass, parentcontainer).attr('href');
	this.imagepacket.metafields	= [];
	
	// set the counter
	this.setCounter(parentcontainer.index());
	
	// add and remove the selected class
	$('.sel',this.element).removeClass('sel');
	parentcontainer.addClass('sel');
	
	$.each(parentcontainer.children(),function(key, value)
	{
		var op = $(value);
		if(op.attr('href') != a.attr('href') && op.attr('className') != p.clickthroughClass)
		{
			p.imagepacket.metafields.push(op.clone());
		}
	});
	
	if(skipImage)
	{
		this.running = false;
		this.restarttimer();
		this.onImageDisplay();
		return true;
	}
	
	// test for animation type
	if(this.animationtype == 'crossfade' || this.animationtype == 'slide' || this.animationtype == 'slidefade')
	{
		this.stage2();
	} else
	{
		// fade the image down
		this.imageItem.fadeOut(this.speed, function()
		{
			var gallery		= SaltGallery.getGalleryByName($(this).attr('id').split('-')[1]);
			
			gallery.stage2();
		});
	}
}

_$pr.stage2 = function()
{
	this.onStartTransition();

	var img = $('<img class="SaltGalImg-'+this.id+'" />').load(function()
	{
//		var galleryName = $(this).attr('class').split('-')[1];
//		setTimeout("SaltGallery.getGalleryByName('"+galleryName+"').stage3()", 1000);
//		return;
	
		var gallery		= SaltGallery.getGalleryByName($(this).attr('class').split('-')[1]);
		setTimeout(function(){gallery.stage3()}, 100);
		
//		gallery.stage3();
	});

	this.oldImageItem = this.imageItem;
//	this.imageItem.remove();
	
	this.imageItem = $(this.createWrapper()).appendTo(this.holder.get());
	if(this.imagepacket.ct)
	{
		var a = $('<a href="'+this.imagepacket.ct+'"></a>');
		a.append(img);
		this.imageItem.append(a);
	} else
	{
		this.imageItem.append(img);
	}
	
	// set up the images for their transition
	this.setupImage();
	
	for(var i=0 ;i < this.imagepacket.metafields.length ; i++)
	{
		this.imageItem.append(this.imagepacket.metafields[i]);
	}
	
	img.attr('src', this.imagepacket.href);
}

_$pr.setupImage = function()
{
	if(this.animationtype == 'crossfade')
	{
		this.oldImageItem.css('z-index',1);
		this.imageItem.css('opacity',0);
	} else if(this.animationtype == 'slide')
	{
		this.imageItem.css({left:this.oldImageItem.width()});
	} else if(this.animationtype == 'slidefade')
	{
		this.oldImageItem.css('z-index',1);
		this.imageItem.css('opacity',0);
		this.imageItem.css({left:this.oldImageItem.width()});
	}
}

_$pr.stage3 = function()
{
	var p = this;
	var t = $(this.imageItem.children()[0]);
	var h = t.attr('height') || t.height() || (t.css('height').split('px')[0]);
	
	
	this.imageItem.height(h);

	
	if(this.animationtype == 'crossfade')
	{
		this.oldImageItem.animate({opacity:0},{duration:this.speed, easing:this.easing});
		this.imageItem.animate({opacity:1},{duration:this.speed, easing:this.easing, complete:function()
		{
			var gallery		= SaltGallery.getGalleryByName($(this).attr('id').split('-')[1]);
			gallery.onImageDisplay();
		}});
	} else if(this.animationtype == 'slide')
	{
		this.imageItem.animate({left:0},{duration:this.speed, easing:this.easing});
		this.oldImageItem.animate({left:-this.oldImageItem.width()},{duration:this.speed, easing:this.easing, complete:function()
		{
			var gallery		= SaltGallery.getGalleryByName($(this).attr('id').split('-')[1]);
			gallery.onImageDisplay();
		}});
	} else if(this.animationtype == 'slidefade')
	{
		this.imageItem.animate({left:0, opacity:1},{duration:this.speed, easing:this.easing});
		this.oldImageItem.animate({left:-this.oldImageItem.width(), opacity:0},{duration:this.speed, easing:this.easing, complete:function()
		{
			var gallery		= SaltGallery.getGalleryByName($(this).attr('id').split('-')[1]);
			gallery.onImageDisplay();
		}});
	}
		this.holder.get().stop(true, false);
		this.holder.get().animate({height:h},{duration:this.speed, easing:this.easing,step:function()
		{
			$(p.gallerydelegate).height($(this).height()+2);
		}});
}

_$pr.close = function()
{
	$('.sel',this.element).removeClass('sel');

	this.imageItem.animate({opacity:0},{duration:this.speed, easing:this.easing, complete:function()
	{
		var gallery		= SaltGallery.getGalleryByName($(this).attr('id').split('-')[1]);
		gallery.cleanupOnClose();
	}});
	this.holder.get().animate({height:1},{duration:this.speed, easing:this.easing});
}
_$pr.cleanupOnClose = function()
{
	this.running = false;
	this.imageItem.remove();
	this.restarttimer();
}

_$pr.onImageDisplay = function()
{
	this.cleanup();
	
	if(typeof this.cb_imageDisplay == 'function')
	{
		this.cb_imageDisplay(this,this.imageItem, this.imagepacket);
	}
}
_$pr.onStartTransition = function()
{
	if(typeof this.cb_startTransition == 'function')
	{
		this.cb_startTransition(this,this.imageItem, this.imagepacket);
	}
}

_$pr.cleanup = function()
{
	this.running = false;
	if(this.oldImageItem) this.oldImageItem.remove();
	
	this.restarttimer();
}

_$pr.restarttimer = function()
{
	if(this.autorun)
	{
		var p = this;
		this.timer = setTimeout(function()
		{
			p.goNextGalItem();
		}, this.timeout);
	}
}

delete _$pr;
delete $pr;


	$.fn.SaltGallery = function(options)
	{
		this.each(function()
		{
			var settings =
			{
				animationtype: 'crossfade',
				speed: 'normal',
				easing: 'linear',
				autorun: false,
				timeout: 2000,
				containerheight: 'auto',
				gallerydelegate: '.gallerydelegate',
				gallerycontainer: null,
				imageClick: null,
				clickthroughClass: null,
				onImageDisplay: null,
				onStartTransition: null,
				onImageUnload: null
			};
			
			if(options)
			{
				$.extend(settings, options);
			}
			
			var elements = $(this).children();
		
			if (elements.length >= 1)
			{
				var gallery = new SaltGallery($(this),settings);
			}
		});
	};
})(jQuery)	
