﻿/// <reference path="TheFarm.js" />
/// <reference path="cufon-yui.js" />

/// <reference path="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1-vsdoc.js" />

var Caraousell = (function ($) {
	var current = 1;
	var myInterval;
	var LockUserActions = false;
	var PrivateMethod = function () {

	};

	var MoveBack = function (itemNumber) {
		LockUserActions = true;
		jQuery('.cItem[data-sortOrder="' + itemNumber + '"]').animate({
			left: "-946px"
		}, 1500, null, function () {
			//after animation is complete.
			jQuery(this).css({ 'left': '946px' }); //move it back to the starting posistion
			LockUserActions = false; 			//Unlock it.
		});
	};

	var Rotate = function (itemNumber) {
		
		var count = $('.cItem').length;
		var previous = itemNumber - 1;
		if (itemNumber > count) {
			current = 1;
			itemNumber = current;
		}
		var newItem = $('.cItem[data-sortOrder="' + itemNumber + '"]');

		newItem.animate({
			left: "0px"
		}, 1500, null, MoveBack(previous));
	};

	var GoBackOne = function (itemNumber) {
		LockUserActions = true;
		var currentItem = $('.cItem[data-sortOrder="' + itemNumber + '"]');
		var newItemId = itemNumber - 1;
		if (newItemId < 1) {//if the id for the data-sortOrder is less then 0 set it to the last item.
			newItemId = $('.cItem').length;
		}
		var newItem = $('.cItem[data-sortOrder="' + newItemId + '"]');
		current = newItemId;
		newItem.css({ 'left': '-946px' });	//push the new item to stage right ready to enter.
		currentItem.animate({				//move current off to stage right
			left: "946px"
		}, 1500, null, null);
		newItem.animate({					//move the new item to be on the stage
			left: "0px"
		}, 1500, null, function () { LockUserActions = false; });
	};

	return {
		Init: function () {

			//move all items accross off the stage.
			$('.cItem').css({ 'left': '946px' });

			//set the first item to the stage.
			var firstItem = $('.cItem:first');
			firstItem.css({ 'left': '0px' });

			//start the rotation if we have more then one element
			if ($('.cItem').length > 1) {
				Caraousell.StartRotation();
				//add the button listners.
				jQuery('.caraousell span.button.prev').click(function () {
					Caraousell.MovePrevious();
				});
				jQuery('.caraousell span.button.next').click(function () {
					Caraousell.MoveNext();
				});
			}
		},

		StopRotation: function () {
			clearInterval(myInterval);
		},

		StartRotation: function () {
			myInterval = setInterval(function () { Rotate(++current); }, 5000);
		},

		MoveNext: function () {
			if (!LockUserActions) {
				Caraousell.StopRotation();
				Rotate(++current);
				Caraousell.StartRotation();
			}
		},

		MovePrevious: function () {
			if (!LockUserActions) {
				Caraousell.StopRotation();
				GoBackOne(current);
				Caraousell.StartRotation();
			}
		},

		PublicFunction: function () {

		}
	}
})(jQuery);
