﻿$(document).ready(function()
{
	$.fn.ImageCarousel = function()
	{
		return this.each(function()
		{
			var container = $(this);
			var clip = container.children('.clip');
			var list = clip.children('ul');
			var items = list.children();
			var prev = container.children('.nav').children('.prev');
			var next = container.children('.nav').children('.next');

			var side_item_width = parseInt(container.attr('side-item-width'), 10);
			var spacer_width = parseInt(container.attr('spacer-width'), 10);
			var item_width = parseInt(container.attr('item-width'), 10) + spacer_width;

			var list_width = item_width * items.length
			list.width(list_width);

			var clip_width = ((side_item_width * 2) + spacer_width) + item_width;
			clip.width(clip_width);
			container.width(clip_width);

			var split = Math.ceil(items.length / 2);
			var split_index = items.length % 2 == 0 ? split : split - 1;
			for(var i = 0, j = split_index; i < split; i++, j++)
			{
				items.eq(i).css('left', (item_width * j) + "px");
			}
			for(var i = split, j = 0; i < items.length; i++, j++)
			{
				items.eq(i).css('left', (item_width * j) + "px");
			}
			list.css('left', -(item_width * split_index - (side_item_width + spacer_width)) + 'px');

			var first_index = split;
			var last_index = split - 1;
			var last_position = item_width * (items.length - 1);
			var all_complete = 0;
			var animating = false;

			prev.click(function()
			{
				if(!animating)
				{
					animating = true;
					items.animate({ left: '+=' + item_width + 'px' }, 400, null, function()
					{
						all_complete++;
						if(all_complete == items.length)
						{
							items.eq(last_index).css('left', "0px");

							first_index = last_index;
							if(last_index == 0)
							{
								last_index = items.length - 1;
							}
							else
							{
								last_index--;
							}

							all_complete = 0;
							animating = false;
						}
					});
				}
			});

			next.click(function()
			{
				if(!animating)
				{
					animating = true;
					items.animate({ left: '-=' + item_width + 'px' }, 400, null, function()
					{
						all_complete++;
						if(all_complete == items.length)
						{
							items.eq(first_index).css('left', last_position + "px");

							last_index = first_index;
							if(first_index == items.length - 1)
							{
								first_index = 0;
							}
							else
							{
								first_index++;
							}

							all_complete = 0;
							animating = false;
						}
					});
				}
			});
		});
	};

	$('#Carousel').ImageCarousel();
});