/*
 * 
 * ImageScroller - a Image Horizental Scroll Viewer 
 * Version 0.1
 * @requires jQuery v1.2.1
 * 
 * Copyright (c) 2007 Luan
 * Email verycss-ok@yahoo.com.cn 
 * 
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * 
*/

jQuery.fn.imageScroller = function(params){
	var p = params || {
		next:"buttonNext",
		prev:"buttonPrev",
		frame:"viewerFrame",
		width:100,
		child:"a",
		auto:true
	}; 
	var _btnNext = $("#"+ p.next);
	var _btnPrev = $("#"+ p.prev);
	var _imgFrame = $("#"+ p.frame);
	var _width = p.width;
	var _child = p.child;
	var _auto = p.auto;
	var _itv;
	
	var turnLeft = function(){
		_btnPrev.unbind("click",turnLeft);
		if(_auto) autoStop();
		var playFired = false;

		_imgFrame.find('div').each(function(){
			var _row = $(this);
			_row.animate( {marginLeft:-_width}, 'fast', '', function(){
				_row.find(_child+":first").appendTo( _row );
				_row.css("marginLeft",0);
				if (!playFired) {
					_btnPrev.bind("click",turnLeft);
					if(_auto) autoPlay();
					playFired = true;
				}
			});
		});
	};
	
	var turnRight = function(){
		var playFired = false;

		_btnNext.unbind("click",turnRight);
		if(_auto) autoStop();
		_imgFrame.find('div').each(function(){
			var _row = $(this);
			_row.find(_child+":last").clone().show().prependTo(_row);
			_row.css("left",-_width);
			_row.animate( {left:0}, 'fast' ,'', function(){
				_row.find(_child+":last").remove();
				if (!playFired) {
					_btnNext.bind("click",turnRight);
					if(_auto) autoPlay(); 
					playFired = true;
				}
			});
		});
	};
	
	_btnNext.css("cursor","hand").click( turnRight );
	_btnPrev.css("cursor","hand").click( turnLeft );
	
	var autoPlay = function(){
	  _itv = window.setInterval(turnRight, 3000);
	};
	var autoStop = function(){
		window.clearInterval(_itv);
	};
	if(_auto)	autoPlay();

	// prevent autoplay when hovering over the ticker container
	$(this).hover(autoStop, autoPlay);

};
