/**
 * jQuery TOOLS plugin :: tabs.slideshow 1.0.0
 * 
 * Copyright (c) 2009 Tero Piirainen
 * http://flowplayer.org/tools/tabs.html#slideshow
 *
 * Dual licensed under MIT and GPL 2+ licenses
 * http://www.opensource.org/licenses
 *
 * Launch  : September 2009
 * Date: ${date}
 * Revision: ${revision} 
 */
(function($) {
	
	var t = $.tools.tabs; 
	t.plugins = t.plugins || {}; 
	t.plugins.slideshow = { 
		version: '1.0.0',
		
		conf: {
			next: '.forward',
			prev: '.backward',
			disabledClass: 'disabled',
			autoplay: true,
			autopause: true,
			interval: 3000, 
			clickable: false,
			api: false
		}
	};


	// jQuery plugin implementation
	$.prototype.slideshow = function(opts) {
	
		var conf = $.extend({}, t.plugins.slideshow.conf), len = this.length, ret; 
		$.extend(conf, opts);
		
		this.each(function() {
			
			var tabs = $(this), api = tabs.tabs(), ret = api; 

			function find(query) {
				return len == 1 ? $(query) : tabs.parent().find(query);	
			}	
			
			var nextButton = find(conf.next).click(function() {
				api.next();		
			});
			
			var prevButton = find(conf.prev).click(function() {
				api.prev();		
			});
			
			// interval stuff
			var timer, hoverTimer, stopped = false;
	
			api.play = function() {
	
				// do not start additional timer if already exists
				if (timer) { return; }
				
				stopped = false;
				
				// construct new timer
				timer = setInterval(api.next, conf.interval);
				
				api.next();
			};	

			api.pause = function() {
				timer = clearInterval(timer);	
			};
			
			// when stopped - mouseover won't restart 
			api.stop = function() {
				api.pause();
				stopped = true;	
			};
		
			/* when mouse enters, slideshow stops */
			if (conf.autopause) {
				var els = api.getTabs().add(nextButton).add(prevButton).add(api.getPanes());
				
				els.hover(function() {			
					api.pause();
					clearInterval(hoverTimer);
					
				}, function() {
					if (!stopped) {						
						hoverTimer = setTimeout(api.play, conf.interval);						
					}
				});
			} 
			
			if (conf.autoplay) {
				setTimeout(api.play, conf.interval);				
			} else {
				api.stop();	
			}
			
			if (conf.clickable) {
				api.getPanes().click(function()  {
					api.next();
				});
			} 
			
			// manage disabling of next/prev buttons
			if (!api.getConf().rotate) {
				
				var cls = conf.disabledClass;
				if (!api.getIndex()) {
					prevButton.addClass(cls);
				}
				api.onBeforeClick(function(i)  {
					if (!i) {
						prevButton.addClass(cls);
					} else {
						prevButton.removeClass(cls);	
					
						if (i == api.getTabs().length -1) {
							nextButton.addClass(cls);
						} else {
							nextButton.removeClass(cls);	
						}
					}
				});
			}
			
		});
		
		return conf.api ? ret : this;
	};
	
})(jQuery); 

