/*******************************************************************************
	jQuery.jadrotate (beta!)
	------------------------
	
	This is a simple ad rotator that will rotate a set of images smoothly. Takes in an object as a parameter
	of options:
		* interval 
			-> The time interval between the rotation of the images, the minimum is 3secs or 3000ms.
			   Defaults to 3000.
		* rotation
			-> This options specifies if the widget will rotate or not. Values are either 'on' or 'off'.
			   Defaults to 'on'.
		* listSelector (new in 1.3!)
			-> The selector used to find the list inside the #jadrotate-list container(not neccessarily li).
			   No longer constrained to list elements. Defaults to 'li'.			   
	This is still in testing...
	
	@example
		conforms to the following markup:
		
		<script>
			$(function () {
				$.jadrotate({
					interval : 3000
				});
			});
		</script>
		
		<div id="jadrotate-box">
			<div>
				<ul id="jadrotate-list">
					<li class="jadrotate:activate(test-active) asdf asdff">advertisement 1</li>
					<li class="jadrotate:activate(test-active)">advertisement 2</li>
					<li class="asdf jadrotate:activate(test-active)  asdff">advertisement 3</li>
					<li class="jadrotate:activate(test-active)">advertisement 4</li>
					<li class="jadrotate:activate(test-active)">advertisement 5</li>
					<li class="asdf asdff jadrotate:activate(test-active)">advertisement 6</li>
				</ul>
			</div>
			<div style="float: right; padding-top: 20px;">
				<a href="#1"><img src="img/1.jpg" class="jadrotate-img" alt="hellow from image 1" style="width: 500px; height: 400px;"/></a>
				<a href="#2"><img src="img/2.jpg" class="jadrotate-img" alt="hellow from image 2" style="width: 500px; height: 400px;"/></a>
				<a href="#3"><img src="img/3.jpg" class="jadrotate-img" alt="hellow from image 3" style="width: 500px; height: 400px;"/></a>
				<a href="#4"><img src="img/4.jpg" class="jadrotate-img" alt="hellow from image 4" style="width: 500px; height: 400px;"/></a>
				<a href="#5"><img src="img/5.jpg" class="jadrotate-img" alt="hellow from image 5" style="width: 500px; height: 400px;"/></a>
				<a href="#6"><img src="img/6.jpg" class="jadrotate-img" alt="hellow from image 6" style="width: 500px; height: 400px;"/></a>
			</div>
		</div>
	
	Hooks for the markup:
	---------------------
		-> #jadrotate-box
			|_ #jadrotate-list
			|_ .jadrotate-img 
			
		-> 	jadrotate:activate(<your-class-here>)
			 - The class that is activated when the list is hovered.
			 
		->  .jadrotate-active
			 - A class that is given by jadrotate to the list item which is active.
			 
	Tested on JSLint (http://jslint.com/) with the following warnings:
		-> Implied global: window 102,236
		
			
	LM: 12-12-09

	@dependencies jquery 1.3.2
	
	@author Rafael Gandionco (http://elrafa.0fees.net) "Write Less, Destroy More"
	@version 1.3
	
********************************************************************************/

(function ($) { // be a good citizen avoid globals...but the dollar sign is mine!
var opt,
	MIN_INTERVAL = 3000,
	_defaultOpt = {
		interval : MIN_INTERVAL,
		rotation : 'on',
		listSelector : 'li'
	},
	_queue = 0,
	_timer;
			
$.jadrotate = function (_o) {

	opt = $.extend({}, _defaultOpt, _o);
	
	// group the selectors //
	var $jAdBox = $('#jadrotate-box'),
		$jAdList = $jAdBox.find('#jadrotate-list'),
		$jAdImg = $jAdBox.find('.jadrotate-img'),
		$jAdListLi = $jAdList.find(opt.listSelector),
		$jAdImgCon = $jAdBox.find(':has(.jadrotate-img):not(a)');		
	
	var class2Activate,
		class2ActivateObj = {},
		checker,
		DELAY = opt.interval,
		
		// http://www.globalnerdy.com/2009/11/09/taking-javascript-performance-to-the-extreme-with-thomas-fuchs/ (slide 51)
		_w = window;	
		
	if (opt.interval) { //set minimum interval...
		if (opt.interval < MIN_INTERVAL) {
			opt.interval = MIN_INTERVAL;
		}
	}
	
	// a bunch of friendly error handlers //
	if ($jAdListLi.length !== $jAdImg.length) {throw 'jadrotate:ERROR -> The number of list does not match the number of images to rotate!';}
	if ($jAdBox.length <= 0) {throw 'jadrotate:ERROR -> #jadrotate-box is missing. jadrotate needs to be contained inside an element with an id="jadrotate-box"!';}
	if ($jAdList.length <= 0) {throw 'jadrotate:ERROR -> #jadrotate-list is missing. jadrotate needs an element that has and id="jadrotate-list" to contain the lists!';}
	if ($jAdImg.length <= 0) {throw 'jadrotate:ERROR -> .jadrotate-img is missing. Their are no images to rotate!';}
	if ($jAdListLi.length <= 0) {throw 'jadrotate:ERROR -> ' + opt.listSelector + ' can\'t be found!';}
	
	// find the parent container of the images and give it a relative position...
	if ($jAdImgCon.length > 0) {
		$jAdImgCon.css({
			position : 'relative'
		});  
	}	
	
	// stack the images one on top of the other...
	$jAdImg.css({
		position: 'absolute',
		display : 'none'
	});
	
	// display the first image
	$($jAdImg.get(_queue)).css('display', 'block');	
	
	// get the class to activate when hovered...
	$jAdListLi.each(function (_index) {
		var me = $(this);
		if ($.trim(this.className) !== '') {
			class2Activate = /jadrotate:activate\(.{1,}\)/.exec(this.className);
			if (class2Activate !== null) {
				me.removeClass(class2Activate[0]);
				class2ActivateObj[_index] = class2Activate[0]
												.replace(/^.*jadrotate:activate\(/, '')
												.replace(')', '');
			}
		}
	});
	
	var __removejAdrotateActiveClass = function (_index, _me) {
		if (typeof class2ActivateObj[_index] !== 'undefined') {
			_me.removeClass(class2ActivateObj[_index]);
		}
	};
	
	var __removeAllCustomActivateClass = function () {
		// http://yuiblog.com/blog/2006/09/26/for-in-intrigue/
		var p;		
		$jAdListLi.removeClass('jadrotate-active');
		for (p in class2ActivateObj) {
			if (class2ActivateObj.hasOwnProperty(p)) {
				$jAdListLi.removeClass(class2ActivateObj[p]);
			}			
		}
	};
	
	var __addjAdrotateActiveClass = function (_index, _me) {
		_me.addClass('jadrotate-active');
		if (typeof class2ActivateObj[_index] !== 'undefined') {
			_me.addClass(class2ActivateObj[_index]);
		}
	};
	
	var __doRotation = function () {
		if ($.trim(opt.rotation).toLowerCase() === 'on') {
			_w.clearTimeout(_timer);
			// http://www.learningjquery.com/2007/01/effect-delay-trick
			$($jAdImg.get(_queue)).animate({opacity : 1.0}, 500, function () {				
				_queue++;	
				if (_queue > ($jAdListLi.length-1)) {
					_queue = 0;					
				}
				else {
				__removeAllCustomActivateClass();	   
				__addjAdrotateActiveClass(_queue, $($jAdListLi.get(_queue)));
				}
				var $pme = $(this);		
				$($jAdImg.get(_queue)).hide().fadeIn('slow', function () {					
					if (_queue === 0) { // for some reason img[0] does not fadein(WTF)...so foce the last image to fadeOut...
						__removeAllCustomActivateClass();	   
						__addjAdrotateActiveClass(_queue, $($jAdListLi.get(_queue)));
						$pme.fadeOut('slow');						
					}
					else {
						$pme.hide();
					}					
					_timer = _w.setTimeout(__doRotation, opt.interval); // call again...recursive call to simulate rotation...					
				});
			});
		}
	};	
	
	// handle list hover events here //		
	$jAdListLi
		.live('mouseover', function () {
			if ($.trim(opt.rotation).toLowerCase() === 'on') {
				_w.clearTimeout(_timer);
			}
			_w.clearTimeout(checker);			
			var me = $(this),
				indx = $jAdListLi.index(this);						
			
			$jAdImg.hide();
			$($jAdImg.get(indx)).fadeIn('slow');
			_queue	= indx;
			
			__removeAllCustomActivateClass();	   
			__addjAdrotateActiveClass(_queue, me);														
		})
		.live('mouseout', function () {
			var me = $(this),
				indx = $jAdListLi.index(this);
							
			checker = _w.setTimeout(function () { // para dili m tok-an....
				__removejAdrotateActiveClass(me, indx);
				__doRotation(); // rotate..	
			}, DELAY);			
		});
	
	// initialization calls....but not all init actions are called here.... //	
	(function () {	
		__addjAdrotateActiveClass(_queue, $($jAdListLi.get(_queue)));
		_w.setTimeout(function () {		
			__doRotation();
		}, opt.interval);			
	})();	

};
})(window.jQuery);
