﻿var orientation = 'left';
var last = -10;
(function($)
{
	$.fn.myGallery = function(options)
	{
		// Set the options.
		options = $.extend({}, $.fn.myGallery.defaults, options);

		// Go through the matched elements and return the jQuery object.
		return this.each(function()
		{
			var gallery = $(this);
			var wrap = $(options.wrapper, gallery);
			var container = $("ul:first", gallery);
			var lis = $("li", container);
			var as = $("a", wrap);
			
			as.fancybox({
				padding: '10px',
				callbackOnShow: function()
				{
					wrap.removeClass("animate");
				},
				callbackOnClose: function()
				{
					wrap.addClass("animate");
				}
			});
			
			var width = 0;
			lis.each(function() 
			{ 
				width += $(this).width();
			});
			container.width(width);
					
			var left = $("<div class='left' />").appendTo(gallery);
			var right = $("<div class='right' />").appendTo(gallery);
			
			wrap.mouseenter(function()
			{
				$(this).removeClass("animate");
			}).mouseleave(function()
			{
				$(this).addClass("animate");
			});
			
			right.mouseenter(function()
			{
				wrap.addClass("fast");
				orientation = 'left';
			}).
			mouseleave(function()
			{
				wrap.removeClass("fast")
			});

			left.mouseenter(function()
			{
				wrap.addClass("fast");
				orientation = 'right';
			}).
			mouseleave(function()
			{
				wrap.removeClass("fast")
			});
			
			wrap.addClass("animate");
			setTimeout(function() { $.fn.myGallery.animateGallery(wrap); }, 3000);
		});
	};
	// Public defaults.
	$.fn.myGallery.defaults = {
		wrapper: '.gwrap:first'
	};
	// Private functions.
	function func()
	{
		return;
	};
	// Public functions.
	$.fn.myGallery.animateGallery = function(container)
	{
		var c = $(container);
		if (c.hasClass("animate"))
		{
			speed = (c.hasClass("fast")) ? 100 : 200;
			var timeoutdelay = 0;
			if (orientation == 'left')
			{
				c.animate({ scrollLeft: '+=15px' }, speed, "linear", function()
				{
					if (last == parseInt(c.scrollLeft()))
					{
						timeoutdelay = 5000;
						orientation = orientation == 'left' ? 'right' : 'left';
					}
					last = parseInt(c.scrollLeft());
					setTimeout(function() { $.fn.myGallery.animateGallery(c); }, timeoutdelay);
				});
			}
			else
			{
				c.animate({ scrollLeft: '-=15px' }, speed, "linear", function()
				{
					if (last == parseInt(c.scrollLeft()))
					{
						timeoutdelay = 5000;
						orientation = orientation == 'left' ? 'right' : 'left';
					}
					last = parseInt(c.scrollLeft());
					setTimeout(function() { $.fn.myGallery.animateGallery(c); }, timeoutdelay);
				});
			}
		}
		else
		{
			setTimeout(function() { $.fn.myGallery.animateGallery(c); }, 100);
		}
	}
})(jQuery);
