// IX_homeRotator plugin

// wrap it up with jQuery passed in as $ for name collision safety
(function($) {

	// plugin definition
	$.fn.IX_homeRotator = function(content,options) {

		// if the content didn't get created or isn't an object, bail now before errors get tossed
		if(content == undefined || typeof content !== "object") { return this; }

		// build main options before element iteration
		// extends exposed defaults property (see end of script)
		var opts = $.extend({}, $.fn.IX_homeRotator.defaults, options);

		// private variables	
		var $this 		= $(this).addClass(opts.classname || "rotator"), // the rotator container
			$slides		= $('ul.slides li', this), 						 // the slides
			$thumbwrap 	= $('<ul class="thumbnails"></ul>'),			 // the thumbnails
			$navigation = $('<div class="nav-rotator-inner"></div>'),	 // the next/prev navigation
			$next 		= $('<span class="next"></span>'),				 // next image
			$prev		= $('<span class="prev"></span>'),				 // prev image
			current		= opts.show || 0,								 // current displayed rotatee
			total		= $slides.length,								 // total number of rotatees
			animating	= false,										 // animation state; don't animate when this is true.
			timer		= 0;											 // used to reference a setTimeout


		// image preloading
		for(var i=0,length = content.length; i<length; i++) {
			if ( typeof content[i].image.toLowerCase() === 'string' ) { 
				$('<img>').attr("src", content[i].image.replace(/\s/g,"%20"));
			}
		}
		
		// loop over content object and build out each rotatee	
		for(var j=0;j<total;j++) {
			$slides.eq(j).data('needsMeta', 'true').css('background-image', 'url('+content[j].image+')').addClass(content[j].classname).wrapInner('<div class="content"></div>').append('<div class="decorator"></div>');

			
			if($slides.eq(j).find('a').length) { 
				$slides.eq(j).css('cursor','pointer');
				$slides.eq(j).bind('click', {index : j}, function(e){ 
					var _href = $(this).find('a')[0].href,
						WTquery = 'WT.ac=' + content[e.data.index].name;
					// console.log(_href);
					window.location = /\?{1}/.test(_href) ? _href + '&' + WTquery : _href + '?' + WTquery;
				});
			}
			$thumbwrap.append($.fn.IX_homeRotator.thumb.replace(/<%=thumbnail%>/g, j));
			if ($slides.eq(j).height() > $this.height()) { $this.height($slides.eq(j).height()); }
		}
		$slides.height($this.height());
		
		// make the thumbnail navigation
		$this.append($thumbwrap);
		$thumbwrap.wrap('<div class="thumbnav"></div>');
		var $thumbs = $thumbwrap.find('li');
		$thumbs.each(function(i){
			var $this = $(this);
			$this.append($.fn.IX_homeRotator.tooltip.replace(/<%=tooltip%>/g, content[i].tooltip));
		});
		
		// build the prev/next controls
		$navigation.append($next).append($prev);
		$this.append($navigation);
		$navigation.wrap('<div class="nav-rotator"></div>');
		
		
		// hide all but the default rotatee
		$slides.not(':eq('+current+')').hide();
		
		$('head').append('<meta name="WT.ad" content="'+content[current].name+'">');
		$slides.eq(current).addClass('on').data('needsMeta', 'nope');
		$thumbs.eq(current).addClass('current');

		// thumbnail click behavior.
		var thumbClick = function(e){
			var speed = opts.autospeed || 7000,
				next = e.data.next;
			if (next === current) {
				return;
			}
			if (next === 'inc') { 
				next = (current + 1 >= $slides.length) ?  0 : current + 1;
			}
			if (next === 'dec') {
				next = (current - 1 < 0) ? $slides.length - 1 : current - 1;
			}

			clearTimeout(timer);
			clearInterval($.fn.IX_homeRotator.rotate);
			cycle(next);
			timer = setTimeout(function(){ $.fn.IX_homeRotator.rotate = setInterval(function(){ $this.trigger('rotate'); },speed); }, opts.pause || 10000);
		}

		// the cycler
		var cycle = function(next) {
			if (!animating) {
				animating = true;
				
				nextimage = typeof(next) != 'undefined' ? next : current == total-1 ? 0 : current + 1;

				if($slides.eq(nextimage).data('needsMeta')=== 'true') {
					$('head').append('<meta name="WT.ad" content="'+content[nextimage].name+'">');
					$slides.eq(nextimage).data('needsMeta', 'nope');
				}
				
				$slides.eq(nextimage).show();
				
				$slides.eq(current).fadeOut(600, function () {
					$(this).removeClass('on'); 
					$slides.eq(nextimage).addClass('on'); 
				});
				
				$thumbs.eq(current).removeClass('current');
				
				current = nextimage;
				
				$thumbs.eq(current).addClass('current');
				
				animating = false;
			}
		};
		
		// arbitrarily pause the cycle.
		var pause = function () {
			clearInterval($.fn.IX_homeRotator.rotate);
		}
		
		// start auto rotation
		var play = function () {
			var speed = opts.autospeed || 7000;
			$.fn.IX_homeRotator.rotate = setInterval(function(){ $this.trigger('rotate'); },speed);
		}
		
		// start the auto rotating
		if(opts.auto) {
			play();
		}

		// return and iterate
		return this.each(function(){
			$thumbs.each(function(index){$(this).bind('click', {next: index}, thumbClick);});
			$next.bind('click', {next: 'inc'}, thumbClick);
			$prev.bind('click', {next: 'dec'}, thumbClick);
			$(this).bind('rotate',function() { 
				cycle();
				return false;
			});
		});
	}

	// exposed functions

	// default options
	$.fn.IX_homeRotator.defaults = {	
		transition : "fade",
		speed : 100,
		auto : true,
		usethumbs : true,
		autospeed : 7000, // time between auto-rotated slides
		pause: 7000 // pause after user selects slide before auto-rotate restarts
	};

	// inserted html templates
	$.fn.IX_homeRotator.thumb 	= '<li class="thumbnail"><%=thumbnail%></li>';
	$.fn.IX_homeRotator.tooltip	= '<div class="tooltip"><span class="content"><%=tooltip%></span></div>';


})(jQuery);
