(function (){
	jQuery.fn.promoRevolver = function(){
		function repeat(str,n){
			return new Array(n+1).join(str);
		}
		return this.each(function(){
			//Variables
			var $wrapper = jQuery('> div', this).css('overflow','hidden'),
			  	$items = $wrapper.find('> div.promo'),
				$single = $items.filter(':first'),
				singleHeight = $single.innerHeight(),
				$currentPage = 0,
				slides = Array('1.jpg','2.jpg','3.jpg','4.jpg'),
				urls = Array('/crawley/', '/event-types/family-arrive-and-drive/', '/event-types/adult-arrive-and-drive/', '/event-types/stag-and-hen/'),
				pages = slides.length,
				imagesPath = '/wp-content/themes/teamsport/images/mainPromo/';
			
			jQuery(".offerLink").remove();
			jQuery($wrapper).wrapInner('<a href="#"/>');
			
			link = $wrapper.find('> a');
			ie6Link = jQuery('#offerLink a');
			jQuery(link).attr("href",urls[$currentPage]);
			jQuery(ie6Link).attr("href",urls[$currentPage]);
			$wrapper.scrollTop(singleHeight);
			/*$wrapper.filter(':not(:animated)').animate({
				scrollTop : '+=' + singleHeight
			}, 10000);*/

			//TASKS
			function slide(){
				//1. First set the visibility of the top one to none
				$items.filter(':last').css('visibility','hidden');
				$wrapper.filter(':not(:animated)').animate({
					scrollTop : '-=' + singleHeight
				}, 3000, function(){
					//RUNS WHEN SLIDE UP IS DONE
					if(($currentPage + 1) >= pages){
						$currentPage = 0;
					}else{
						$currentPage += 1;
					}
					
					//2. Then set the background of the wrapper to the background of the next item
					wrapperBgImage = imagesPath + slides[$currentPage];
					$wrapper.css('background-image','url(\''+wrapperBgImage+'\')');
					$wrapper.css('background-position','center');
					
					//3. Then move the wrapper back down
					$wrapper.scrollTop(singleHeight);
					
					//4. Set the background of the last div to current
					if(($currentPage + 1) >= pages){
						nextPage = 0;
					}else{
						nextPage = $currentPage + 1;
					}
					nextImage = imagesPath + slides[nextPage];
					$items.filter(':first').css('background-image','url(\''+nextImage+'\')');
					
					jQuery(link).attr("href", urls[$currentPage]);
					jQuery(ie6Link).attr("href",urls[$currentPage]);
				});
			};
			
			jQuery(document).everyTime(8000, function(i) {
				slide();
			});
			window.slide = slide;
		});
	};
})(jQuery)
