(function($) {
	GS.extend('carousel', function($data) {
		var wrapper = $('#gshome-carousel'),
			data = $data,
			items = $('.carousel', wrapper),
			ul = $('.carousel-wrapper', wrapper),
			controls = $('#carousel-controls', wrapper),
			next = $('#gs-continueto'),
			previous = $('#gs-backto'),
			width = false,
			height = false,
			position = 0,
			total;

		function Init() {
			items.each(function() {
				if (!height) {
					height = $(this).outerHeight();
				}
				if (!width) {
					width = $(this).outerWidth()+40;
				}
				$(this).css('width', width);
				return this;
			}).css({
				'float' : 'left',
				'height' : height
			}).show();

			total = items.length;

			wrapper.css({
				'overflow' : 'hidden',
				'clear' : 'both',
				'margin' : '-20px',
				'padding' : '20px'
			});
			ul.css({
				'position' : 'relative',
				'width' : width*total,
				'height' : height-10
			});

			$('li', controls).each(function($i) {
				$(this).data('position', $i);
			});
			$('a', controls).bind('click', HandleControlsClick);

			next.bind('click', HandleNext);
			previous.bind('click', HandlePrevious);

			Annotate();
		}

		function HandleNext() {
			position++;
			if (position >= total) {
				position = total-1;
			}
			Animate();
		}

		function HandlePrevious() {
			position--;
			if (position < 0) {
				position = 0;
			}
			Animate();
		}

		function HandleTick() {
			position++;
			if (position >= total) {
				position = 0;
			}
			Animate();
		}

		function HandleControlsClick() {
			var li = $(this).parent();
			position = li.data('position');
			Animate();
			return false;
		}

		function Animate() {
			var goTo = 0 - ( position * width );
			ul.animate({
				'left' : goTo
			}, 400, 'swing');

			$('li', controls).removeClass().addClass('slide-btn');
			$('li:nth-child('+(position+1)+')', controls).removeClass().addClass('slide-btn-active');

			Annotate();
		}

		function Annotate() {
			var text_next = false,
				text_previous = false;
			if (position == 0) {
				previous.hide();
				text_next = data[1];
			} else if (position == data.length-1) {
				next.hide();
				text_previous = data[data.length-2];
			} else {
				text_next = data[position+1];
				text_previous = data[position-1];
			}
			if (text_next) {
				$('span', next).html(text_next);
				next.show();
			}
			if (text_previous) {
				$('span', previous).html(text_previous);
				previous.show();
			}
		}

		Init();
	});

})(jQuery);
