/* 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.1 (May 22, 2008)
 * Requires: jQuery 1.2+
 */
 
(function($j) {

	$j.fn.jFlow = function(options) {
		var opts = $j.extend({}, $j.fn.jFlow.defaults, options);
		var cur = 0;
		var maxi = $j(".jFlowControl").length;
		$j(this).find(".jFlowControl").each(function(i){
			$j(this).click(function(){
				$j(".jFlowControl").removeClass("jFlowSelected");
				$j(this).addClass("jFlowSelected");
				//alert(cur);
				//alert(i);
				var dur = Math.abs(cur-i);
				$j(opts.slides).animate({
					marginLeft: "-" + (i * $j(opts.slides).find(":first-child").width() + "px")
				}, opts.duration*(dur));
				cur = i;
			});
		});	
		
		$j(opts.slides).before('<div id="jFlowSlide"></div>').appendTo("#jFlowSlide");
		
		$j(opts.slides).find("div").each(function(){
			$j(this).before('<div class="jFlowSlideContainer"></div>').appendTo($j(this).prev());
		});
		
		//initialize the controller
		$j(".jFlowControl").eq(cur).addClass("jFlowSelected");
		
		var resize = function (x){
			$j("#jFlowSlide").css({
				position:"relative",
				width: opts.width,
				height: opts.height,
				overflow: "hidden"
			});
		
			$j(opts.slides).css({
				visibility:"visible",
				position:"relative",
				width: $j("#jFlowSlide").width()*$j(".jFlowControl").length+"px",
				height: $j("#jFlowSlide").height()+"px",
				overflow: "hidden"
			});
		
			$j(opts.slides).children().css({
				position:"relative",
				width: $j("#jFlowSlide").width()+"px",
				height: $j("#jFlowSlide").height()+"px",
				"float":"left"
			});
			
			$j(opts.slides).css({
				marginLeft: "-" + (cur * $j(opts.slides).find(":first-child").width() + "px")
			});
		}
		
		resize();
		
		$j(window).resize(function(){
			resize();						  
		});
		
		$j(".jFlowPrev").click(function(){
			if (cur > 0)
				cur--;
			else
				cur = maxi -1;
			
			$j(".jFlowControl").removeClass("jFlowSelected");
			$j(opts.slides).animate({
				marginLeft: "-" + (cur * $j(opts.slides).find(":first-child").width() + "px")
			}, opts.duration);
			$j(".jFlowControl").eq(cur).addClass("jFlowSelected");
		});
		
		$j(".jFlowNext").click(function(){
			if (cur < maxi - 1)
				cur++;
			else
				cur = 0;
				
			$j(".jFlowControl").removeClass("jFlowSelected");
			$j(opts.slides).animate({
				marginLeft: "-" + (cur * $j(opts.slides).find(":first-child").width() + "px")
			}, opts.duration);
			$j(".jFlowControl").eq(cur).addClass("jFlowSelected");
		});
	};
	
	$j.fn.jFlow.defaults = {
		easing: "swing",
		duration: 400,
		width: "100%"
	};
	
})(jQuery);

