(function($){
	/**
	 * jQuery Plugin to form a simple content fader/rotator for BSRO
	 *
	 * usage:
	 * $('#adRotator').bsroAdRotator({width: 500, height: 100}); //set different width for rotator
	 * $('#adRotator').bsroAdRotator({interval: 5000, transitionRate: 250}); //hold on each slide longer, transition faster
	 * $('#adRotator').bsroAdRotator({autoHide: true}); //hide the "controls" bar when not hovering on the slide
	 * $('#adRotator').bsroAdRotator({countdownEnabled: true}); //enable support for countdown banners as specified by markup
	 * $('#adRotator').bsroAdRotator({countdownEnabled: true, countdownInterval: 8000}); //increase or decrease the interval a countdown banner is displayed for
	 * $('#adRotator').bsroAdRotator({controlStyle: 'numeric'}); //change how the navigation is rendered ('numeric': 1-based list of integers for each slide, 'bullet': the bullet character for each slide)
	 */
	$.fn.bsroAdRotator = function(options, callback){	
		callback = ($.isFunction(callback)) ? callback : function(){} ;
		var constants = {
			millsecondsPerDay: 1000 * 60 * 60 * 24,
			controlStyleNumeric: "numeric",
			controlStyleBullet: "bullet"
		};
		var settings = {
			width:667
			,height:176
			,interval:4000
			,transitionRate:500
			,autoHide:false
			,id:'ad-rotator-container'
			,countdownEnabled:false
			,countdownInterval:4000
			,countdownPrompt:'Hurry! Offers end in:'
			,countdownPluginUrl:'/scripts/jquery/jquery.countdown.min.js'
			,controlStyle:constants.controlStyleNumeric
			,rotateCounter:0
		}, elem = {}, timer = false
		$.extend(true, settings, options);

		var methods = {
			init: function(){
				//buid working set
				elem.items = elem.source.children();
				settings.transitionDisabled = (elem.items.length === 1);
				//TODO test detach/attach/clone with flash and custom scripts
				elem.source.after(methods.rotator()).detach();
				methods.start();
				callback();
				
				$('#ad-rotator-container .buttons').delegate('a','click', function() { methods.trackButtons( this ); return true; } );
				$('#ad-rotator-container').delegate('.ad-content img','click', function() { methods.trackBanners( this ); return true; } );
								
				return true;
			}
			,rotator: function(){
				elem.rotator = $('<div>', {
					id:'ad-rotator-container'
					,width: settings.width
					,height: settings.height
				}).hover(function(){
						//pause
						methods.pause();
						if(settings.autoHide){ elem.toolbar.stop(true, true).fadeIn('fast'); }
					},function(){
						//resume
						methods.resume();
						if(settings.autoHide){ elem.toolbar.stop(true, true).fadeOut(); }
					})
				.data('currentPosition', -1)
				.append($(elem.items[0]).children().eq(0).clone())
				.append(methods.toolbar());
					return elem.rotator;
			}
			,toolbar: function(){
				elem.toolbar = $('<div>', {
					"class": 'toolbar'
				}).append(methods.buttons())
				  .append(methods.controls())
				  .append(methods.countdown());				  
				if(settings.autoHide ) { 
					elem.toolbar.hide(); 
				} else {
					elem.toolbar.fadeIn('fast');
				}
				return elem.toolbar;
			}
			,buttons: function(item){
				if (elem.buttons == null) {
					elem.buttons = $('<div>', {
						"class": 'buttons'
					}).append($(elem.items[0]).children().eq(1).html());
				}
				
				return elem.buttons;
			}
			,trackButtons: function(button){
				var buttonName;

				switch( button.id ) {
					case 'track-print' :
						buttonName = 'Click Print';
						break;
					case 'track-print-and-sched' :
						buttonName = 'Click Schedule Appointment';
						break;
					case 'track-learn-more' :
						buttonName = 'Click Learn More';
						break;
					default :
						buttonName = 'Button Click';
						break;
				}
				
				$.trackEvent( 'Tire Rotator Banner', buttonName, 'Clicks', elem.rotator.data('currentPosition'), false );
				return true;				
			}
			,trackBanners: function(banner){
				var bannerName = $( banner ).attr( 'alt' );
				
				$.trackEvent( 'Tire Rotator Banner', 'Click Banner', bannerName, elem.rotator.data('currentPosition'), false );
				return true;				
			}
			,controls: function(){
				if(settings.transitionDisabled) {
					elem.controls = null;
				} else{
					elem.controls = $('<div>', {
						"class":'controls'
					})
					elem.items.each(function(i, v){
						$('<a>',{
							href: '#'+ i
							,text: (settings.controlStyle == constants.controlStyleBullet) ? '•' : i + 1
							,"class": (i === 0) ? 'current' : null
							,click: function(){
								if(!$(this).hasClass('current')){
									methods.pause();
									methods.transition(i);
								}
								return false;
							}
						}).appendTo(elem.controls)
						  .track({'category':'Tire Rotator Banner', 'action': 'Click Navigation Number', 'label': i });
					});
				}
				return elem.controls;
			}
			,countdown: function(item){
				if (elem.countdown == null) {						
					elem.countdown = $('<div class="countdown">'
						+ '<span class="prompt">' + settings.countdownPrompt + '</span>'
						+ '<span class="dd">00</span><span class="separator">:</span>'
						+ '<span class="hh">00</span><span class="separator">:</span>'
						+ '<span class="mm">00</span><span class="separator">:</span>'
						+ '<span class="ss">00</span>'
						+ '<span class="overlay"></span>'
						+ '</div>')
						.hide();
				}		
				return elem.countdown;				
			}
			,start: function(){
				if(elem.controls !== null){
					methods.transition(0, true);
				}
			}
			,pause: function(){
				window.clearTimeout(timer);
			}
			,resume: function(interval){
				interval = interval || settings.interval;
				if (timer > 0) {
					window.clearTimeout(timer);
				}
				timer = window.setTimeout(function(){
					methods.transition();
				},  interval + settings.transitionRate);
			}
			,transition: function(to, immediate){
				var next = ((arguments.length == 0) ? elem.rotator.data('currentPosition') + 1 : Math.min(elem.items.length, to)) % elem.items.length;
				var duration = immediate ? 0 : settings.transitionRate;
				var interval = settings.interval;
				
				// Fade the current ad content out and create the new content with a fade in
				$(elem.rotator).children().eq(0).stop(true, true).fadeOut(duration);
				$(elem.items[next]).children().eq(0).clone().hide().prependTo(elem.rotator).fadeIn(duration, function(){
					$(this).siblings(".ad-content").remove();
					elem.rotator.data('currentPosition', next);
					$('a', elem.controls).removeClass('current').eq(next).addClass('current');
				});
				
				var bannerName = $('#ad-rotator-container .ad-content img').attr( 'alt' );

				if ( arguments.length == 0 ) $.trackEvent( 'Tire Rotator Banner', 'Advance Automatically', ++settings.rotateCounter, undefined, true  );
				
				// If countdown elements are present then initialize the countdown behavior for the ad. Change
				// the interval for the next transition to use the countdown interval specified in settings.
				var countdownElements = $(elem.items[next]).children().eq(2);
				if (countdownElements.length > 0 && settings.countdownEnabled) {
					interval = settings.countdownInterval;	
					var expiration = $('.expiration-date', countdownElements);
					if (expiration.length > 0) {
						var ts = Date.parse(expiration.text());
						if (!isNaN(ts)) {
							$(elem.countdown).countdown({ to: ts + constants.millsecondsPerDay }).fadeIn(duration);
						}
					} else {
						$(elem.countdown).fadeOut(duration);
					}
				} else {
					$(elem.countdown).fadeOut(duration);
				}
				
				// Update the buttons for the ad using whatever was provided with the content.
				var buttons = $(elem.items[next]).children().eq(1);
				if (buttons.children('a').length > 0) {
					
					// If the buttons list is a different length (e.g. changing from a standard promo to a learn more) try
					// to make the transition as smooth as possible.
					// TODO: Look to a better ad type recognition system possible using custom attributes or classes.
					if (buttons.children('a').length != elem.buttons.children('a').length) {
						elem.buttons.fadeOut(duration / 2, function() {
						  	elem.buttons.html(buttons.html()).fadeIn(duration / 2);
						});
					} else {
						elem.buttons.html(buttons.html()).fadeIn(duration);	
					}
					
					// Setup a click handler to resume the interval when clicked
					elem.buttons.children('a').click(function() {
						methods.resume(interval);
					});
					
					// Update the content to trigger the click event of the first button and use the pointer cursor
					$(elem.rotator).children().eq(0).click(function() {
						elem.buttons.children('a').eq(0).get(0).onclick();
					});
					$(elem.rotator).children().eq(0).css('cursor', 'pointer');
				} else {
					elem.buttons.fadeOut(settings.transitionRate, function() {
						elem.buttons.html('');
					});		
				}			
				
				// Call resume to setup the next transition
				methods.resume(interval);
			}
		};

		return this.each(function(){
			elem.source = $(this);

			// If using the coundown script load the plugin before initializing unless already loaded
			if (settings.countdownEnabled && $.fn['countdown'] == null) {
				$.getScript(settings.countdownPluginUrl || '/scripts/jquery/jquery.countdown.min.js', function() {
					methods.init();
				});
			} else {
				methods.init();
			}				
		});
	};

	//enable adRotator
})(jQuery);
