/* Copyright (c) 2008 Kean Loong Tan http://www.gimiti.com/kltan
 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * jFlow
 * Version: 1.2 (July 7, 2008)
 * Requires: jQuery 1.2+ ... Vini hack!
 */
 
(function($) {

	$.fn.jFlow = function(options) {
		var opts = $.extend({}, $.fn.jFlow.defaults, options);
		var jFC = opts.controller;
		var jFS =  opts.slideWrapper;
		var jSel = opts.selectedWrapper;

		var cur = 0;
		var maxi = $(jFC).length;
		var t;
		// sliding function
		var h = false;
		var slide = function (dur, i) {
			if (!h) {
				h = true;
				$(opts.slides).find("> div").eq(cur).fadeOut(opts.duration,function(){$(jFC).removeClass(jSel).eq(i).addClass(jSel);$(opts.slides).find("> div").eq(i).fadeIn(opts.duration,function(){h=false;cur=i;});});
			}
		}
		$(this).find(jFC).each(function(i){
			$(this).click(function(){
				if (t) {window.clearInterval(t);t=null;}
				var dur = Math.abs(cur-i);
				slide(dur,i);
			});
		});	
		
		$(opts.slides).find("> div").addClass("jFlowSlideContainer");
		
		//initialize the controller
		$(jFC).eq(cur).addClass(jSel);
		$(opts.slides).find("> div").eq(cur).show();

		$(opts.prev).click(function(){
			if (t) {window.clearInterval(t);t=null;}
			var dur = 1;
			var i;
			if (cur > 0)
				i = cur - 1;
			else {
				i = maxi -1;
				dur = cur;
			}
			slide(dur,i);
		});
		var next = function(){
			var dur = 1;
			var i;
			if (cur < maxi - 1)
				i = cur + 1;
			else {
				i = 0;
				dur = maxi -1;
			}
			slide(dur, i);
		};
		$(opts.next).click(function(){
			if (t) {window.clearInterval(t);t=null;}
			next();
		});

		t = window.setInterval(function() {next();}, opts.autoSlideInterval);

	};
	
	$.fn.jFlow.defaults = {
		controller: ".jFlowControl", // must be class, use . sign
		slideWrapper : "#jFlowSlide", // must be id, use # sign
		selectedWrapper: "jFlowSelected",  // just pure text, no sign
		easing: "swing",
		duration: 3000,
		width: "100%",
		autoSlideInterval: 5000,
		prev: ".jFlowPrev", // must be class, use . sign
		next: ".jFlowNext" // must be class, use . sign
	};
	
})(jQuery);

