/*
 * Js loader, looks for html components with the right class
 * and then runs the js object associated with it.
 */

(function(){
       
      var newsTicker = function(opts, c){

         var that = {};
         var opts = opts || {};
		 var $container = opts.$container || $('.news-container');
		 var tickTime = opts.tickTime || 14;
		 var currentPos = 0;
		 var maxChars = 100;
		 var $newsList = $($container.find('.news-items')[0]);
		 var $newsItems = $newsList.find('.news-item');
		 var numberOfNewsItems = $newsItems.length;
		 var news = [];
		 var $unravel, $ticker, position;
		 var timer;
		 
		 // Stop sliding on hover
         $container.hover(
  			function () {
    			clearTimeout(timer);
  			}, 
  			function () {
    			clearTimeout(timer);
    			timer = setTimeout(tick,tickTime*1000);
  			}
  		);
		 
		 // Read through the html news and extact relevant data
		 var newsListToData = function(){
		 	$newsItems.each(function(){
		 		var truncatedText = truncate($(this).text(),maxChars);
		 		$(this).find('a').text(truncatedText);
		 		var curNewsItem = {
		 			html: $(this).html(),
		 			width: $(this).width()
		 		}
		 		news.push(curNewsItem);
		 	});
		 };
		 
		 var tick = function(){
		 	//console.log('tick');
		 	clearTimeout(timer);
		 	$unravel.css({'left':position.left+'px', 'top':'7px'});
		 	$unravel.show();
		 	$ticker.html(news[currentPos].html);
		 	$unravel.animate({'left':(news[currentPos].width+position.left)+'px'},2500,function(){
		 		$(this).hide();
         		timer = setTimeout(tick,tickTime*1000);
		 	});
		    currentPos++;
		 	if(currentPos>=numberOfNewsItems) currentPos = 0; //Reset
		 };
		 
		 var truncate = function(text, maxChars){
		 	if(maxChars<text.length){
		 		var truncatedText = text.substring(0, maxChars);
		 		return jQuery.trim(truncatedText) + '...';
		 	}else{
		 		return text;
		 	}
		 }
		 
		 var appendTickerElements = function(){
		 	$container.append('<div class="unravel"></div>');
		 	$unravel = $container.find('.unravel');
		 
		 	// Insert a new blank li to display ticker content
		 	$container.append('<div class="ticker"></div>');
		 	$ticker = $container.find('.ticker');
		 }
		  
		 // Exit if no news items.
		 if(numberOfNewsItems === 0) return that;
		 newsListToData();
		 $newsList.remove();
		 appendTickerElements();
		 $ticker.show();
		 // Position Unravel
		 position = $ticker.position();
		 tick();

         return that;
         
      };
      
      window[namespace].newsTicker = newsTicker;
      
})();
