/**
 * Carousel 1.0 (2011 11 12)
 * Gajus Kuizinas
 * 
 * Copyright 2011 Anuary Ltd, http://anuary.com/
 */
(function($){
	var ay	=
	{
		options:
		{
			item: {width: 0},
			callback: null
		}
	};
	
	$.fn.ayCarousel	= function(options)
	{	
		var instance	= 
		{
			item: null,
			animated: false,
			options: {},
			selector:
			{
				carousel: $(this),
				container: $(this).find('div.container'),
				navigation: $(this).find('div.navigation'),
				items: $(this).find('div.container > *')
			},
			fn:
			{
				init: function()
				{
					instance.selector.items.fadeOut(0);
						
					instance.options.item.width	= $(instance.selector.items[0]).width();
					
					var container_width	= instance.options.item.width * instance.selector.items.length;
					var middle_item		= Math.ceil((instance.selector.items.length)/2);
					
					//var middle_item	= 10;
					
					if(instance.selector.items.length %2 == 0)
					{
						container_width	+= instance.options.item.width;
					}
					else
					{
						--middle_item;
					}
					
					//middle_item	= 0;
					
					instance.selector.container.css({
						width: container_width,
						left: (instance.selector.carousel.width()-container_width)/2
					});
					
					instance.item	= $(instance.selector.items[middle_item]);
					
					instance.fn.centerTo();
					
					instance.selector.navigation.click(instance.fn.triggerNavigation);
				},
				triggerNavigation: function()
				{					
					if(instance.animated)
					{
						return;
					}
					
					instance.animated			= true;
					
					var next					= $(this).hasClass('next');
										
					var initial_frame_position	= instance.selector.container.position().left;
					
					/*if(next)
					{
						var item	= ;
					}
					else
					{
						var item	= instance.selector.container.find('> *:last');
					}*/
					
					//console.log(item);
					
					instance.item	= next ? instance.item.next() : instance.item.prev();
					
					instance.fn.centerTo();
					
					instance.selector.container.animate({left: initial_frame_position+(next ? -1 : 1)*instance.options.item.width}, 500, null, function(){		
						if(next)
						{
							$(this).find('> *:last').after($(this).find('> *:first'));
						}
						else
						{
							$(this).find('> *:first').before($(this).find('> *:last'));
						}
						
						$(this).css('left', initial_frame_position);
						
						instance.animated	= false;
						
						
					});
				},
				centerTo: function()
				{
					instance.selector.items.fadeTo(250, .5).removeClass('active');
					
					instance.item.fadeTo(250, 1).addClass('active');
				}
			}
		};
		
		// initialize the script
		instance.options	= $.extend({}, ay.options, options);
			
		instance.fn.init();
	};
})($);
