/**
 * scrollerSnippet
 * This is a jQuery plugin for creating a scrollerSnippet.
 */
jQuery.fn.scrollerSnippet = function() {
	
	return $(this).each(function() {
		
		var elem = $(this);
		var animationDuration = 800; // how long the slide animation lasts
		this.animationType = 'bounce'; // the animation type
		this.fade = false;
		this.numScrollerItems = 3; // the number of scrollerItems
		var scrollerItemSwitchTime = 4000; // switch time
		this.currentItem = 1; // the current item
		var scrollerSnippetIntervalID = null; //stores the interval driving the scroller.
		var scrollerSnippetActive = true; //toggles the scroller on and off
		var scrollerItemHeight = 0; // height of the whole scroller
		var imgPause = '/javascript/pantheon/snippets/Scroller/pause.png'; // location of the play/pause images
		var imgPlay = '/javascript/pantheon/snippets/Scroller/play.png';
		this.heightArray = []; // an array containing the heights of each itemBox	
		var that = this; /* we're assigning a reference to the current instantiation of the plugin
		since we need to pass this reference to the closure called via window.setInterval */
		
		// set the switch time
		scrollerItemSwitchTime = elem.attr('pausetime') * 1000;
		this.animationType = elem.attr('animation');
		
		// set up the animation type
		switch (this.animationType) {
			case 'slide':
				this.animationType = 'easeOutCubic';
				break;
			case 'spring':
				this.animationType = 'easeOutElastic';
				break;
			case 'fade':
				this.animationType = 'easeOutCubic';
				this.fade = true;
			case 'bounce':
			default:
				this.animationType = 'easeOutBack';
		}
		
		// activate the scroller
		elem.addClass('active');
		
		// how many scrollerItems do we have?
		this.numScrollerItems = $('.scrollerSnippetInner .scrollerSnippetItem', elem).length;
		
		// no scroller items?
		if (this.numScrollerItems < 1) return;
		
		// now to generate the scrollerControls!
		for (var i = 1; i <= this.numScrollerItems; i++) {
			$('div.scrollerSnippetControls', elem).append("<a href='#" + i + "' id='scrollerButton" + i + "' class='scrollerItemSelector'>" + i + "</a>");
		}
		$('div.scrollerSnippetControls', elem).append("<a href='#' id='pause-play'><img src='" + imgPause + "' alt='Pause' /></a>");
		
		// show the scrollerControls
		$('div.scrollerSnippetControls', elem).addClass('displayInBrowser');
		
		// get the scrollerWidth
		scrollerItemWidth = elem.width();
		
		// store the scrollerItem heights in the heightArray
		var itemCount = 1;
		$('div.scrollerSnippetInner div.scrollerSnippetItem', elem).each(function() {
			$(this).css('left', itemCount == 1 ? 0 : scrollerItemWidth * (itemCount - 1));
			that.heightArray[itemCount] = $(this).height() + 30;
			itemCount++;
			if ($(this).height() > scrollerItemHeight) scrollerItemHeight = $(this).height();
		});
		
		// set the scroller to the height of the tallest item
		//elem.height(this.heightArray[1]);
		//elem.height(scrollerItemHeight + 35);
		
		//by checking for xml http request we can reliably detect if it is IE or below as IE previously used ActiveX
		if (typeof XMLHttpRequest == "undefined") {
			elem.css('height', scrollerItemHeight + 35);
		}
		else {
			elem.css('min-height', scrollerItemHeight + 35);
		}
		
		// start the scroller
		play();
		
		// select the first selector
		$('div.scrollerSnippetControls #scrollerButton' + this.currentItem, elem).addClass('current');
		
		// when a control is clicked (focuses - device independant) switch to the relevant  item
		$('div.scrollerSnippetControls a.scrollerItemSelector', elem).focus(function() {
			//get the item number to switch to and set the currentItem appropriatly
			
			var href = $(this).attr('href');
			var index = href.indexOf('#');
			var switchTo = parseInt(href.substr(index + 1));
			that.currentItem = switchTo;
			
			var itemPosition = "-" + scrollerItemWidth * (that.currentItem - 1);
			
			var newHeight = that.heightArray[that.currentItem];
			
			// change height
			//$(elem).animate({height: newHeight}, 400);
			//$(elem).css('height', newHeight + 'px');
			
			// change the item
			//$('.scrollerSnippetInner', elem).animate({'left': itemPosition + 'px'}, 400, 'easeOutBack');
			$('.scrollerSnippetInner', elem).css('left', itemPosition + 'px');
			
			//add the class 'current' to the current item selector.
			$('a.scrollerItemSelector', elem).removeClass('current');
			$('div.scrollerSnippetControls #scrollerButton' + that.currentItem, elem).addClass('current');
			
			// pause
			pause();
			
			return false;
		});
		
		// safari doesn't seem to think click is focus so we route the event
		$('div.scrollerSnippetControls a.scrollerItemSelector', elem).click(function() {
			$(this).focus(); 
			
			//prevent the default action (following the href).
			return false;
		});
		
		// someone clicks the play/pause button
		$('div.scrollerSnippetControls #pause-play', elem).click(function() {
			if (scrollerSnippetActive) {
				pause();
			}
			else {
				play();
			}
			return false;
		});
		
		// pause
		function pause() {
			scrollerSnippetActive = false;
			$('div.scrollerSnippetControls a#pause-play', elem).html("<img src='" + imgPlay + "' alt='Play' />");
			// clear interval
			window.clearInterval(scrollerSnippetIntervalID);
		}
		
		// toggle play
		function play() {
			scrollerSnippetActive = true;
			$('div.scrollerSnippetControls a#pause-play', elem).html("<img src='" + imgPause + "' alt='Pause' />");

			// we're creating an interval on switchScrollerItem, which (below) creates an anonymous function so 
			// that multiple scrollers on one page are possible.
			scrollerSnippetIntervalID = window.setInterval(switchScrollerItem(animationDuration, scrollerSnippetActive, that.currentItem, elem, scrollerItemWidth, that), scrollerItemSwitchTime);
		}
		
		
		// change the current scroller item
		// this is a closure which uses the passed reference 'that' in order to
		// manipulate the original plugin instantiation. This is a bit of a long-winded way of doing it
		// but it is necessary for multiple scrollers to work (props to Slick Rick').
		function switchScrollerItem(animationDuration, scrollerSnippetActive, currentItem, elem, scrollerItemWidth, that) 
		{
			var animationDuration = animationDuration;
			var scrollerSnippetActive = scrollerSnippetActive;
			var currentItem = currentItem;
			var elem = elem;
			var scrollerItemWidth = scrollerItemWidth;
			var that = that;

			return function () {
			
				if (!scrollerSnippetActive) {
					return;
				}
				
				if (that.currentItem == that.numScrollerItems) {
					var opts = {
						left: ("0")
					};
					var change = '0';
					that.currentItem = 1;
				}
				else {
					var opts = {
						left: ("-" + scrollerItemWidth * that.currentItem + "px")
					};
					var change = '-' + scrollerItemWidth * that.currentItem + 'px';
					that.currentItem++;
					
				}
				
				// animate the item change.
				
				if (that.fade) $('.scrollerSnippetItem', elem).fadeOut(500); // fade
				
				//setTimeout("$('.scrollerSnippetInner', elem).animate(opts, animationDuration, that.animationType); // animate
				
				if (that.fade) {
					setTimeout(function() {
						var theElem = elem;
						var theChange = change;
						$('.scrollerSnippetInner', elem).css('left', change);
					}, 500);
				} else {

					$('.scrollerSnippetInner', elem).animate(opts, animationDuration, that.animationType); // animate
				}
				
				if (that.fade) $('.scrollerSnippetItem', elem).fadeIn(500); // unfade
				
				
				
				if (that.fade) {
					setTimeout(function() {
						var theElem = elem;
						var theCurrentItem = that.currentItem;
							
						$('a.scrollerItemSelector', theElem).removeClass('current');
						$('div.scrollerSnippetControls #scrollerButton' + theCurrentItem, theElem).addClass('current');
						
					}, 500);
				} else {
					$('a.scrollerItemSelector', elem).removeClass('current');
					$('div.scrollerSnippetControls #scrollerButton' + that.currentItem, elem).addClass('current');
				}
			}
		}
	});
}



 $(document).ready(function() {
   $('div.scrollerSnippet').scrollerSnippet();
 });
