(function($) {

	var op 			= new Array; //option
	var charac		= new Array; //text
	var charlength	= new Array; //character length
	var href		= new Array; //link
	var positions	= new Array;
	var textpos		= new Array;
	var playInterval = new Array;
	var appInterval	= new Array;
	
	$.fn.themesguyTicker= $.fn.themesguyTicker = function(options){
		
		init = function(tt){
			
			op[tt.id] = $.extend({}, $.fn.themesguyTicker.defaults, options);
			charlength[tt.id]	= new Array();
			charac[tt.id]		= new Array();
			href[tt.id]			= new Array();
			textpos[tt.id]		= new Array();
			positions[tt.id]	= 0;
				

					$.each($('#'+tt.id+' li'), function(i,item){
						charac[tt.id][i] 	= $(item).find('a').text();
						href[tt.id][i]		= $(item).find('a').attr('href');
						charlength[tt.id][i] = charac[tt.id][i].length;
						textpos[tt.id][i] = 0;
					});
					
					$('.' + op[tt.id].classPlace + '').html($('#'+tt.id+' li:eq(0)').html());//append the first data
					
					if($('#'+tt.id+' li').length > 1) //only do the animation if length more than 1.
						$.transition(tt);
					
		};
		
		// transitions
		$.transition = function(tt){
			clearInterval(playInterval[tt.id]);
			//calculate the total time , option delay + character length*option speed for each character. works in all browsers except IE :)
			if(positions[tt.id] == $('#'+tt.id+' li').length){
				next = 0;
			} else {
				next = positions[tt.id] + 1
			}
			leday = op[tt.id].delay + Math.ceil(charlength[tt.id][next]*op[tt.id].CharDelay);
			playInterval[tt.id] = setInterval(function() { $.gt(tt) }, leday);
			
		};
		
		$.gt = function(tt){
			$('.' + op[tt.id].classPlace + '').html(""); //remove current html
			textpos[tt.id][positions[tt.id]] = 0; //reset the textpos, set it into 0
			$('.' + op[tt.id].classPlace + '').append('<a href=""></a>');//append the tag a
			appInterval[tt.id] = setInterval(function() { $.np(tt)  },op[tt.id].CharDelay);
			
			positions[tt.id]++;
			if  (positions[tt.id] == $('#'+tt.id+' li').length) {
				positions[tt.id] = 0;
			}
			
		};
		
		$.np = function(tt){

				if( textpos[tt.id][positions[tt.id]] > charlength[tt.id][positions[tt.id]] )
				{
					clearInterval(appInterval[tt.id]);
					return;
				}
				$('.' + op[tt.id].classPlace + ' a').attr('href', href[tt.id][positions[tt.id]]);//insert the current href
				var toEnter = charac[tt.id][positions[tt.id]].substr(0, textpos[tt.id][positions[tt.id]]);
				$('.' + op[tt.id].classPlace + ' a').text(toEnter);//animate the character
				
				textpos[tt.id][positions[tt.id]]++;
		};

		this.each (
			function(){ init(this); }
		);


	};
	
	// default values
	$.fn.themesguyTicker.defaults = {	
		delay : 6000, // delay between news
		CharDelay : 50, //delay between character
		classPlace : 'anim_recent' //class name of div to display the news ticker,
	};	
	
})(jQuery);
