/*
 * jQuery Scroller v1.0 by Craig Freer / Together Agency
 * Derived from easySlider by Alen Grakalic
 */
 
;(function($) {

	$.fn.scroller = function(){

		this.each(function() {

			var i = 1; //iteration
			var ml = null; //margin-left
			var tot = null; //total li's
			var start = null;
			var promo = true;


			function checkloop() {
				$("ul li:nth-child("+i+")", obj).animate({'marginLeft': ml}, 1000, 'easeInCubic', function() {				
					i = (i+1>tot) ? 1 : i+1; //increment
					timeout = setTimeout(function(){ animate(); }, 500);
				});
			}

			function animate() {
				clearTimeout(start); //kill the start timer
				$("ul li:nth-child("+i+")", obj).animate({'marginLeft': 0}, 1500, 'easeOutCubic', function() {
					timeout = setTimeout(function(){ checkloop(); }, 4000);
				});
			}

			//run
			var obj = $(this);
			tot = $('li', obj).length;
			ml = $("li:first-child", obj).width();
			if ((ml>0) && (tot>0)) {

				if (promo) {
					//promo mode, add in new promo nodes.
					var promocode = '<li class="promo"><a href="/feel-great-giveaway/"><span class="hidden">The Feel Great Giveaway</span></a></li>';
					for (var j=tot; j>0; j--) { //backwards since we're changing tot.
						//add in new promo items, before every odd index.
						if (j % 2) {
							$('li:nth-child('+j+')', obj).before(promocode);
							j--;
						}
					}
					//reset tot
					tot = $('li', obj).length;
				} else {
					//change seed, non promo mode is random.
					i = Math.floor(Math.random()*(tot)+1);
				}
				//we have enough to work, begin!
				start = setTimeout(function() { animate(); }, 4000); //4s delay post load.
			}

		});
	};
})(jQuery);
