/******** USAGE **********
HTML CODE
<ul id="unique_id">
	<li>news 1</li>
	<li>news 2</li>
	<li>....
</ul>

JAVASCRIPT CODE
$('#unique_id').newsTicker({options});

--OPTIONS--
speed: (int) moving speed
fps: (int) frame rate per second
margin: (int) margin between each news

*************************/
(function($) {
	$.fn.newsTicker = function(userArgs) {
		if(!this.length) return false;
		if(!this.is('ul')) return this;
		
		var args = {
			speed:2,
			fps:25,
			margin:100
		}
		$.extend(true, args, userArgs);
		
		var frame = this.css({'position':'relative','overflow':'hidden'});
		var total = frame.find('li').length;
		var counter = 0;
		var FPS = Math.ceil(1000/args.fps);
		var lis = new Array();
		var timer = null;
		var timerRun = false;
		
		frame.find('li').each( function() {
			$(this).css('white-space','nowrap');
			var thisWidth = 0;
			$(this).children().each( function() {
				thisWidth += $(this).outerWidth();
			});
			lis.push({obj:$(this), flag:false, width:thisWidth, position:frame.width()+10});
			
			$(this).css({'position':'absolute','top':0,'left':frame.width()+10+'px','float':'left'});
			thisWidth = null;
		});
		lis[0].flag = true;
		
		timer = setInterval(function() {
			moving();
		}, FPS);
		timerRun = true;
		
		function moving() {
		
			for(var i=0; i<total; i++) {
				if(lis[i].flag) {
					//var newPosi = lis[i].obj.position().left-args.speed; 
					/*position() function has a problem in IE 7*/
					var newPosi = lis[i].position-args.speed;
					lis[i].obj.css({'left':newPosi+'px'});
					if(newPosi < -1*(lis[i].width+10)) {
						lis[i].obj.css({'left':frame.width()+10+'px'});
						lis[i].flag = false;
						lis[i].position = frame.width()+10;
					}else{
						lis[i].position = newPosi;
					}
					newPosi = null;
				}
			}
			
			if(lis[counter].obj.position().left < frame.width()-(lis[counter].width+args.margin)){
				counter++;
				if(counter >= total)	counter = 0;
				lis[counter].flag = true;
			}
			return false;	
		}
		
		this.stopTimer = function() {
			window.clearInterval(timer);	
			timerRun = false;
		}
		
		this.startTimer = function() {
			if(!timerRun) {
				timer = window.setInterval(function() {
					moving();
				}, FPS);
				timerRun = true;
			}
		}
		
		return this;
	}
})(jQuery);
