/*
 * A simple JQuery plugin for an jquery_feedreader news box
 *
 * @author Michael Cole <jquery_feedreader@michaelcole.com> - http://www.michaelcole.com
 * Based on code from http://www.learningjquery.com/2006/10/scroll-up-headline-reader
 * Based on code by Francesco Vivoli <f.vivoli@gmail.com> - http://atalayasec.org	
 *  - Based on code found on the JQuery mailing list
 */
(function($) {

var scroll_pause=5000;	
var scroll_speed=1000;
var scroll_height=200;
/**
 * Configure the news box container with url, maximum number of posts
 * to be fetched and their text length.
 * @example $('#newsbox').feedreader({
 *		targeturl: 'http://localhost/frontpage/feed',
 *		destination: 'div.news-slide',
 *		items: 3,
 *		descLength: 15
 *	});
 * @desc fill the #newsbox element with at most 3 posts taken from the above url, and showig
 * a teaser of at most 15 words.
 *	
 */	
$.fn.feedreader = function(options) {
	var defaults = {
		feed: '/frontpage/feed',
		items: 3,
		length: 15,
		pause: scroll_pause,
		speed: scroll_speed,
		height: scroll_height
	}
	if(!options.feed)	return false;  //FIXME Fail gently:
	var opts = $.extend(defaults, options);
	scroll_pause=opts.pause;
	scroll_speed=opts.speed;
	scroll_height=opts.height;
	
	$(this).each(function(){
    var container = this;
    // AJAX feed request to server
    $.get(opts.feed,function(xml){
      var posts=[];
      var i=0;
      $("item", xml).each(function(){
              if(i>opts.items-1)	return;
              var post={};
              $(this).find("link").each(function(){
                post.link=getNodeText(this);
              });
              $(this).find("title").each(function(){
                post.title=getNodeText(this);
              });
              $(this).find("pubDate").each(function(){
                post.date=getNodeText(this);
              });
              $(this).find("description").each(function(){
                var t=getNodeText(this);
                post.desc=trimtext(t,opts.length);
              });
              posts[i++]=post;
      });
      // items retrieved.  Now do something with them.
      writeposts(container, posts);
      scrollposts($(this), "#jquery-feedreader-list li");	
      $('#jquery-feedreader').css("height",scroll_height+"px");
      $('#jquery-feedreader li').css("height",scroll_height+"px");
    })
    // FIXME: what if the AJAX feed request fails?
  });	
	
};

function trimtext(text,length){
	var t = text.replace(/\s/g,' ');
	var words = t.split(' ');
	if(words.length<=length)	return text;
	var ret='';
	for(var i=0;i<length;i++){
		ret+=words[i]+' ';
	}
	return ret;
}

//////////////////////////////////////////////////////////////////////////////////

function writeposts(container,posts){
	$(container).empty();
	var html = '<ul id="jquery-feedreader-list">';
	for(var k in posts){
		html+=format(posts[k])
	}
	html += '</ul>';
	$(container).append(html);
}

function format(post){
	var html='<li class="jquery-feedreader-item"> <a href="'+post.link+'">';
		html+='<span class="jquery-feedreader-title">'+post.title+'</span></a>';
		html+='<span class="jquery-feedreader-description">'+post.desc+'</span>';
		html+='</li>';
	return html;	
}

function getNodeText(node)
{
  var text = "";
  if(node.text) text = node.text;
  if(node.firstChild) text = node.firstChild.nodeValue;
  return text;
}


//////////////////////////////////////////////////////////////////////////////////


var headline_count;
var headline_interval;
var old_headline = 0;
var current_headline=0;
var headlines = new Array(); // an array of jQuery objects

function scrollposts(destination, container){
  headline_count = $(container).size();

  for (var i = 0; i < headline_count; i++) {
    headlines[i] = $(container+":eq("+i+")");
  }

  headlines[current_headline].top('5px');

  headline_interval = setInterval(headline_rotate,scroll_pause);  // Repeat scrolling
  
  $(destination).hover(function() {   // FIXME mouse hover isn't working to pause.
    clearInterval(headline_interval);
  }, function() {
    headline_interval = setInterval(headline_rotate,scroll_pause);
    headline_rotate();
  });
}

function headline_rotate() {
  var h_animate = -(scroll_height+5);
  var h_top = ""+scroll_height+'px'
  
  current_headline = (old_headline + 1) % headline_count;
  headlines[old_headline].animate({top: h_animate},scroll_speed, function() {
    $(this).top(h_top).hide();
    });
  headlines[current_headline].show().animate({top: 5},scroll_speed);
  old_headline = current_headline;
}

})(jQuery);

