/*
 * jQuery Div Slide Plugin v1.0 beta
 *
 *
 * Usage:
 * 	$(selector).divslide({
		delay: (int), //default 1000
		nagivator: (bool), // default true
		onSlideComplete: (call back fx)
	});
 *
 *
 * Copyright (c) 2010 Ming Teoh
 * Version: 1.0 (2010-06-24)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Tested with: jQuery v1.4.2
 */
(function($) {
	
	$.fn.divslide = function(options) {
		var $_currentSlide = 0;
		var $_maxSlide;
		var $_currentTimer = null;
		var $_options;
		var $ds = $(this);
		
		// Default options 
		var defaults = { 
			delay: 1000,
			navigator: true,
			onSlideComplete : function (obj,activeSlide){}
		}; 		
		
		// Overwrite defaults
		$_options = $.extend({}, defaults, options); 

		//prepare data
		$_maxSlide = $ds.find(".slide").length;
		if($_options.navigator == true) $ds.append('<div class="slidenav"></div>');
		$.each($ds.find(".slide"),function(i,theslide){
			$(theslide).attr("id","slide_"+i);
			if($_options.navigator == true && $_maxSlide > 1) {
				$(".slidenav").append('<div class="slidenavcell" id="slidenavcell_'+i+'">'+(i+1)+'</div>');
				$(".slidenavcell").last().click(function(){
					$_currentSlide = i;
					$ds._currentSlide();
				});
			}
		})
		
		//set styles
		if($_options.navigator == true)
			$ds.append('<style>\n.slidenav {position:absolute;bottom:10px;color:#000} \n.slidenavcell {float:left;height:20px;width:20px;text-align:center;font-weight:bold;border:1px solid #CCC;cursor:pointer;margin:1px;} \n.selected{background-color:#FF8209;} \n</style>');
		
		//for calling next slide
		$ds._nextSlide = function() {
			var $_nextSlide = $_currentSlide + 1;
			if($_nextSlide == $_maxSlide) $_nextSlide = 0;
			
			$(".slide").hide();
			$("#slide_"+$_nextSlide).show();
			$_currentSlide = $_nextSlide;
			$ds._newTimer();
		};
		
		//for calling current slide
		$ds._currentSlide = function() {
			$(".slide").hide();
			$("#slide_"+$_currentSlide).show();
			$ds._newTimer();
		};
		
		//set timer
		$ds._newTimer = function() {
			if(typeof $_currentTimer != null) clearTimeout($_currentTimer);
			$_currentTimer = setTimeout(function(){
				$ds._nextSlide();
				if(typeof $_options.onSlideComplete == "function") 
					$_options.onSlideComplete($ds,$("#slide_"+$_currentSlide));
			},$_options.delay);
			if($_options.navigator == true) $ds._resetNavCell();
		};
		
		//reset nav cell color
		$ds._resetNavCell = function(){
			$(".slidenavcell").removeClass('selected');
			$("#slidenavcell_"+$_currentSlide).addClass('selected');
		};
		
		//start the loop
		$ds._currentSlide();
		return $ds;
	};
})(jQuery);