/*!

 * Meztura Stock Scroller v1.0
 * Based on liScroll 1.0 by Gian Carlo Mingati
 * jQuery v1.2.x or later
 * 
 */


jQuery.fn.mezRssTicker = function(settings) {
		settings = jQuery.extend({
		travelocity: 0.07,
		dataSource: "get_rss.php?xml_source=http://www.nytimes.com/services/xml/rss/nyt/GlobalHome.xml"
		}, settings);		
		return this.each(function(){
			
			newsContainer = $(this);
				
			loadData();
						
			function loadData()
			{	
				//The jQuery ajax object:
				$.ajax({
					type: "POST",
					url: settings.dataSource,
					dataType: "xml",
					success: function(data) {
						generate_list(data);
					  }
				});	
			}
			
			
			function generate_list(data){
			
				//This function will generate a UL list with all data and then will start the scroller
				$(newsContainer).append("<ul id='mez_news'>");
				jData = $(data);
				
				jData.find('ITEM').each(function(i){
					
					var jItem = (this);
										
					$("#mez_news").append("<li>"
									+"<span class='dot'>•</span>"
									+"<span class='item'>"+jItem.childNodes[0].firstChild.nodeValue+"</span>"
									+"</li>");
									
				});
				
				//Prepare scroller for first use
				$strip = jQuery("#mez_news");
				$strip.addClass("newsticker")
				$mask = $strip.wrap("<div class='mask'></div>");
				$tickercontainer = $strip.parent().wrap("<div class='tickercontainer'></div>");								
	
				//Call Scroller
				scrollnews();
	
			}
	
			
			
			
			function scrollnews(){
			//This function transform a UL list into a sliding scroller
				
				var stripWidth = 1;
				$strip.find("li").each(function(i){
				stripWidth += jQuery(this, i).outerWidth(true); // thanks to Michael Haszprunar and Fabien Volpi
				});
				
				var containerWidth = $strip.parent().parent().width();	//a.k.a. 'mask' width 	
				$strip.width(stripWidth);
				var totalTravel = stripWidth+containerWidth;
				var defTiming = totalTravel/settings.travelocity;	// thanks to Scott Waye		
				
				//When the scroller finishes we call refreshData()
				$strip.animate({left: '-='+ totalTravel}, defTiming, "linear", function(){$strip.css("left", containerWidth); refreshData();});
			
			}

			
			function refreshData()
			{	
				//The jQuery ajax object:
				$.ajax({
					type: "POST",
					url: settings.dataSource,
					dataType: "xml",
					success: function(data) {
						update_list(data);
					  }
				});	
				
			}
			
			
			function update_list(data){
				
				//This function will update the UL list	
				var jData = $(data);
				
				$("#mez_news").find('li').each(function(i) {
				
					$(this).replaceWith(function() {						 
						 
						 var output ="<li>"
						 				+"<span class='dot'>•</span>"
										+"<span class='item'>"+data.documentElement.childNodes[i].childNodes[0].firstChild.nodeValue+"</span>"
										+"</li>";		 
						 return output;		
					});
				});
				
				//once updated we call the scroller again 
				scrollnews();
			}			
				
				
		});	
};