/*
	tt.offerCarousel.js
	
	Version: 	0.1 
	Author: 	Matt Kersley
	
	---------------------------------------------------------------------------------------
	
	DESCRIPTION:
		This plugin turns any unordered list into an offer box carousel
	
	---------------------------------------------------------------------------------------	
*/

(function($) {	
	
	$.fn.offerCarousel = function(options) {
		
		//cache $(this) to save memory
		var $container = $(this);

		//default options/settings
		var settings = $.extend({
			delay					: 50,	//delay between each slide
			imageArray				: [],		//array of background image URLs
			prevNextOn				: true,		//next and previous conrols included
			itemsViewable			: 1,		//number of list items to be displayed
			itemWidth				: 300,		//width of each list items
			itemHeight				: 300,		//height of list items
			animatedSlide			: true,		//animate slide, or just "flick it"?
			slideSpeed				: 250,		//speed of slide transition
			controlsPosition		: 'above',	//where controls show [above]/[below]
			automatic				: true,		//is the animation/flick automatic?
			infoBackgroundOn		: true,		//add div for information background?
			infoBackgroundColor		: '000',	//info div background color
			infoBackgroundOpacity	: 0.4		//info div background opacity
		}, options || {});
		
		//strip deeplink javascript calls out of page
		//fixes script being called by $container.children() below
		$('#' + $container.attr('id') + ' script[src*=JS.aspx?lid]').remove();
		
		
		//check for offer item elements
		if($container.children().length > 0){
			
			//wrap list in div
			$container.wrap('<div id="slider"></div>');
			
			$('#slider').css({width:settings.itemWidth * settings.itemsViewable,height:settings.itemHeight,overflow:'hidden',position:'relative'});
						
			//set viewable area of items container
			$container.css({
				'position'	: 	'relative',
				'width'		: 	settings.itemWidth * $container.children().length,
				'height'	: 	settings.itemHeight,
				'margin'	: 	0, 
				'padding'	: 	0, 
				'list-style': 	'none'
			});
				
			//loop through each of the container elements "items"
			$container.children().each(function(i){
				
				//cache "this" to save memory
				var $childNode = $(this);
				
				//add a css class to the item for custom styling
				$childNode.attr('id', $childNode.parent().attr('id') + '-item-' + i)
				
				//add styling which has to be applied for viewable items
				$childNode.css({
					'position'	: 	'relative',
					'float'		: 	'left',
					'width'		: 	settings.itemWidth,
					'height'	: 	settings.itemHeight,
					'overflow'	: 	'hidden'
				});
				
				//set position of first item
				if(i===0){
					$childNode.css('left', '0');
				}
				
				//add background image if imageArray has been defined in options
				if(settings.imageArray.length > 0){
					$childNode.css('background', 'url('+settings.imageArray[i]+') no-repeat');
				}
				
				//wrap any content of the item in its own div
				$childNode.wrapInner('<div class="offer-content" style="width:100%;position:absolute;z-index:1;"></div>');
				
				//add extra div for info background if needed
				if(settings.infoBackgroundOn){
					$childNode.prepend('<div class="offer-content-background" style="width:100%;"></div>');
					$('#'+$childNode.attr('id')+' .offer-content-background').css({
						'backgroundColor'	:	'#' + settings.infoBackgroundColor ,
						'height'			:	$('#'+$childNode.attr('id')+' .offer-content').height() ,
						'width'				:	'100%', 
						'opacity'			:	settings.infoBackgroundOpacity,
						'position'			:	'absolute',
						'z-index'			:	'1'
					});
				}
				
				//if settings.nextPrevOn is true, add prev and next controls
				if(settings.prevNextOn && settings.itemsViewable <= 1){
				
					//instantiate next/prev controls string construction
					strControls = 	'<div class="next-prev-controls">';
				
					//check if not first item, add previous image/link
					if(i !== 0){
					
						strControls += 	'<a class="prev" href="#' + $childNode.parent().attr('id') + '-item-' + (i-1) + '">';
					
						if(settings.prevImageURL !== ''){
							strControls += '<img src="' + settings.prevImageUrl + '"" alt="previous" />';
						} else {
							strControls += 'prev'
						}
					
						strControls += '</a>';
					
					}
			
					//add next image/link for all but the last item
					if(i === 0 || i !== $container.children().length-1) {
						
						strControls += 	'<a class="next" href="#' + $childNode.parent().attr('id') + '-item-' + (i+1) + '">';
		
						if(settings.nextImageURL !== ''){
							strControls += '<img src="' + settings.nextImageUrl + '"" alt="next" />';
						} else {
							strControls += 'next'
						}
		
						strControls += '</a>';
					}
				
					//close controls string
					strControls +=	'</div>';
				
					//add controls for next/previous images based on position option
					if(settings.controlsPosition === 'below'){
						$childNode.append(strControls);
					} else {
						$childNode.prepend(strControls)
					}
					
				}
				
				//assign click event handler to prev control to slide left
				$('#' + $childNode.attr('id') + ' a.prev').bind('click', function(){
				
					//if settings.animatedSlide is true, and there is no animation in progress animate it
					if(settings.animatedSlide && $container.not(':animated').length > 0){
						$container.stop().animate({marginLeft:(parseInt($container.css('margin-left'))+settings.itemWidth*settings.itemsViewable)},settings.slideSpeed);
					}
					
					//prevent default link behaviour
					return false;
				});
				
				//assign click event handler to prev control to slide right
				$('#' + $childNode.attr('id') + ' a.next').bind('click', function(){
				
					//if settings.animatedSlide is true, and there is no animation in progress animate it
					if(settings.animatedSlide && $container.not(':animated').length > 0){
						$container.stop().animate({marginLeft:(parseInt($container.css('margin-left'))-settings.itemWidth*settings.itemsViewable)},settings.slideSpeed);
					}
					
					//prevent default link behaviour
					return false;
				});
				
				//add fade/highlight functionality to controls
				$('.next-prev-controls a').fadeTo(0,0.5).hover(
					function(){$(this).stop().fadeTo(700,1);},
					function(){$(this).stop().fadeTo(700,0.5);}
				);
				
			});
			
			
			//if "automatic" option is set to true, slide based on duration
			if (settings.automatic) {
							
				//set duration an run function to slide
				autoSlide($container, settings);
				
			}
			
		} //end of selector check
		
		//otherwise alert the user no results were returned from one of their selectors
		else {
			alert('Please provide a container and item selector which returns results');
		}

	};
	
	
	//automatic slide function
	function autoSlide($container, settings, isBeingHoveredOver) {
		
		//Store hover state for pausing animated carousel when hovered over
		if(isBeingHoveredOver == null){isBeingHoveredOver = false;}
		$container.hover(
			function(){isBeingHoveredOver = true;},
			function(){isBeingHoveredOver = false;}
		);
		
		//perform slide based on settings.delay option
		setTimeout(function(){
			
			//dont do anything if the scroll is already in progress
			if($container.not(':animated').length > 0 && isBeingHoveredOver === false){
			
				//get current margin and total length of items
				var currentPos = parseInt($container.css('margin-left'))*-1;
				var lengthCount = parseInt((settings.itemWidth*$container.children().length)-settings.itemWidth*settings.itemsViewable)
				
				//if current margin is less than the total length of items, slide left
				if(currentPos < lengthCount){
					if(settings.animatedSlide){
						$container.stop().animate({marginLeft:(parseInt($container.css('margin-left'))-settings.itemWidth*settings.itemsViewable)},settings.slideSpeed);
					}
					else{
						$container.css({marginLeft:(parseInt($container.css('margin-left'))-settings.itemWidth*settings.itemsViewable)});
					}
				} 
				
				//otherwise, go back to first item
				else {
					
					//if speed isn't an integer, alert user
					if(typeof settings.slideSpeed == 'string'){alert('slideSpeed needs to be in milliseconds')}
					
					//otherwise slide back to first item
					else{
						if(settings.animatedSlide){
							//delay is made longer due to number of items to slide past
							var delay = parseInt(settings.slideSpeed) * $container.children().length;
						
							//perform slide
							$container.stop().animate({marginLeft:0},delay);
						}
						
						else{
							$container.css({marginLeft:0});
						}
					}
				}
			}
			
			//call function again to automate next slide
			autoSlide($container,settings, isBeingHoveredOver);
			
		},settings.delay);
	};

	
})(jQuery);
