/*
 * A simple JQuery plugin for an RSS-fed news box
 * @author Ben Davey
 * modified from code by Francesco Vivoli <f.vivoli@gmail.com> - http://atalayasec.org	
 */

/**
 * Configure the news box container with url, maximum number of posts
 * to be fetched and their text length.
 * @example jQuery('#newsbox').feedreader({
 *		targetUrl: 'http://blogs.atalayasec.org/atalaya/?feed=rss2',
 *		items: 3
 *	});
 * @desc fill the #newsbox element with at most 3 posts taken from the above url, and showig
 * a teaser of at most 15 words.
 *	
 */	

var global_options = {};

jQuery.fn.feedreader = function(options) {
	var defaults = {
			targetUrl: '',
			divId: '',
			items: 3,
			showUrl: true,
			showDate: true,
			showDescription: true,
			showPagination: true,
			showThumbnail: true,
			showLoadingIcon: true,
      showShare: false, 
      shareImage: '',
      shareMessage: '', 
      shareUrl: '',
			classTitle: '',
			classDescription: '',
			classDate: '',
			classThumbnail: '',
			classItem: '',
			metadataThesaurus: 'Categories',
			metadataThesaurusValue: '',
			
			isCarousel: false,
			buttonLeft: '',
			buttonRight: '',
			auto: null,
			speed: 200,
      vertical: false,
      circular: true,
      visible: 3,
      start: 0,
      scroll: 1,
      widthLi: 225,
      heightLi: 275,
      widthDiv: 675,
      heightDiv: 275
	}

	if(!options.targetUrl)	return false;

	var opts = jQuery.extend(defaults, options);

	if(!opts.currentpage)
		opts.currentpage = 0;

	opts.min = opts.currentpage * opts.items;
	opts.max = (opts.currentpage + 1) * opts.items;

	if (opts.showLoadingIcon) {
		displayLoadingIcon(opts.divId);
	}

	jQuery(this).each(function(){
		if(!opts.container)
			opts.container = this;
		// has the rss already been retrieved to memory?
		// if not, get the feed, else use the old one
		if(opts.min == 0)
			jQuery.get(opts.targetUrl,function(xml){
				processRSS(xml,opts);
			}
			);
		else{
			writeposts(opts,opts.posts.length);	
		}
		// store a reference of this divs options
		// such that we can access them later
		eval("global_options." + opts.divId + "= opts;");
	});	
};

function processRSS(xml,opts){
	var i=0;
	opts.posts = [];
	var proceed=true;

	jQuery("item", xml).each(function(){
		post={};
		
		if (typeof(jQuery(this).attr("id")) != "undefined") {
		  post.resourceId = jQuery(this).attr("id");
		}
		
		jQuery(this).find("link").each(function(){
			post.link=getNodeText(this);
		});
		
    jQuery(this).find("image").each(function(){
      post.image=getNodeText(this);
    });
    
		jQuery(this).find("title").each(function(){
			post.title=getNodeText(this);
		});
		
		jQuery(this).find("enclosure").each(function(){
			post.link= jQuery(this).attr("url");
		});
		
		jQuery(this).find("pubDate").each(function(){
			post.date=getNodeText(this);
		});
		
		jQuery(this).find("description").each(function(){
			post.desc=getNodeText(this);
		});
		
		jQuery(this).find("meta").each(function(){
			if (jQuery(this).attr("id") == opts.metadataThesaurus) {
				post.metadata=getNodeText(this);
				return;
			}
		});  

		post.opts = opts;

		proceed = true;

		if (opts.metadataThesaurusValue != '') {
			if (typeof(post.metadata) == "undefined") {
				proceed = false; 
			}
			else if (post.metadata == opts.metadataThesaurusValue) {
				proceed = true; 
			}
			else if (post.metadata.indexOf(opts.metadataThesaurusValue) >= 0) {
				proceed = true;
			}
			else {
				proceed = false; 
			}
		}
		
		if (proceed && ((!opts.isCarousel) || (opts.isCarousel && i < opts.max))) {
			opts.posts[i++]=post;
		}
	});

	writeposts(opts,i);
}

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(opts,i){
	var hasNextPage = true;
	var hasPrevPage = true;
	var curmax = 0;
	var html = '';
	
	if(opts.max <= i){
		curmax = opts.max;
	} else{
		curmax = i;
	}

	for(k=opts.min;k<curmax;k++){
		html+=format(opts.posts[k],opts.isCarousel);
	}

	if(opts.isCarousel) {
	  html = '  <div class="jCarouselLite">\n' +
           '    <ul>\n' +
           html +
           '    </ul>\n' +
           '  </div>\n';

	  if (opts.buttonLeft == '') {
	    html = '\n<button class="prev">&lt;&lt;</button>\n' + html;
	  } else {
	    html = '\n<img class="prev" alt="Previous" src="'+opts.buttonLeft+'" />\n' + html;
	  }
	  if (opts.buttonRight == '') {
	     html += '<button class="next">&gt;&gt;</button>\n';
	  } else {
	     html += '<img class="next" alt="Next" src="'+opts.buttonRight+'" />\n';
	  }
	} else {
  	if (html == '') {
  		html = 'No results found.';  
  	}
  	else {
  	  if(opts.min == 0)
  	    hasPrevPage = false;
  	  
  	  if(i <= (opts.currentpage + 1) * opts.items)
  	    hasNextPage = false;
  
  	  html += getPagination(opts, hasPrevPage, hasNextPage);	  
  	}
	}

	jQuery(opts.container).empty();
	jQuery(opts.container).html(html);
	
	if(opts.isCarousel) {
	  applyJCarouselLite(opts);
	}
}

function getPagination(p_opts, p_prev, p_next){
  var l_html = '';
  
	if(p_opts.showPagination){
	  l_html = '<br />';

		if(p_prev)
		  l_html += '<a onclick="prevPage(\'' + p_opts.container.id + '\');" style="cursor:pointer">< prev</a>&nbsp;&nbsp;';
		
		if(p_next) 
		  l_html += '<a onclick="nextPage(\'' + p_opts.container.id + '\')" style="cursor:pointer">next ></a>';
	}
	
	return(l_html);
}

function nextPage(p_divId){
	// retrieve stored options
	eval("var storedopts = global_options." + p_divId + ";");
	storedopts.currentpage++;
	jQuery("#" + p_divId).feedreader(storedopts);
}

function prevPage(p_divId){
	eval("var storedopts = global_options." + p_divId + ";");
	storedopts.currentpage--;
	jQuery("#" + p_divId).feedreader(storedopts);
}

function format(post,isCarousel){
	var html = '';
 
	if (isCarousel) {	  
	  html = '<li class="carousel">\n';
	}
	    
	//content    
	html += '<div class="' + post.opts.classItem + '">';

  if(post.opts.showThumbnail) {
    var l_thumbnail = '';
  
    if (typeof(post.image) != "undefined") {
      l_thumbnail = post.image;
    } 

    if (l_thumbnail == '' && typeof(post.link) != "undefined") {
      if (post.link.indexOf('.jpg') > 0 || post.link.indexOf('.JPG') > 0 ||
          post.link.indexOf('.png') > 0 || post.link.indexOf('.PNG') > 0 ||
          post.link.indexOf('.gif') > 0 || post.link.indexOf('.GIF') > 0) {
        l_thumbnail = post.link; 
      }
    }
    
    if (l_thumbnail != '') {
  		html += '<div class="' + post.opts.classThumbnail + '"><img src="' + l_thumbnail + '" /></div>';
  	}
  }
  
  html += '<div class="' + post.opts.classTitle + '">';
  
  if(post.opts.showUrl && typeof(post.link) != "undefined")
  	html += '<a href="' + post.link + '" class="' + post.opts.classTitle + '" target="_blank\">';
  
  html += post.title;
  
  if(post.opts.showUrl)
  	html += '</a>';	
  	
  html += '</div>';
  
  if(post.opts.showDate && typeof(post.date) != "undefined")
  	html += '<div class="' + post.opts.classDate + '">' + post.date + '</div>'; 
  
  if(post.opts.showDescription && typeof(post.desc) != "undefined")
  	html += '<div class="' + post.opts.classDescription + '">' + post.desc + '</div>'; 
  
  if(typeof(post.metadata) != "undefined")
  	html += '<div class="' + post.opts.classDescription + '">' + post.opts.metadataThesaurus + ': ' + post.metadata + '</div>'; 
  
  if(post.opts.showShare && (typeof(post.resourceId) != "undefined")) {
     html += '<div class=""><a onclick="ajaxShareAdd(\'' + post.opts.shareUrl + '\', \'' + post.resourceId + '\', \'\', \'' + post.opts.shareMessage + '\', \'\');" style="cursor:pointer"><img src="' + post.opts.shareImage + '" /></a></div>';
  }	
  	
  html += '</div>';
	
  if (isCarousel) {    
     html += '</li>\n';
  }

	return html;
}

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

function updateFeed(p_divId, p_thes) {
  eval("var storedopts = global_options." + p_divId + ";");
  if (storedopts.showLoadingIcon) {
    displayLoadingIcon(p_divId);
  }  
  storedopts.metadataThesaurusValue = p_thes;
  storedopts.currentpage = 0;
  jQuery.get(storedopts.targetUrl,function(xml){
	  jQuery("#" + p_divId).feedreader(storedopts);
  });  
}

function applyJCarouselLite (opts) {

  jQuery(".centricFeed .jCarouselLite").jCarouselLite({
    btnNext: ".centricFeed .next",
    btnPrev: ".centricFeed .prev",
    auto: opts.auto,
    speed: opts.speed,
    vertical: opts.vertical,
    circular: opts.circular,
    visible: opts.visible,
    items: opts.posts.length,
    start: opts.start,
    scroll: opts.scroll,
    widthLi: opts.widthLi,
    heightLi: opts.heightLi,
    widthDiv: opts.widthDiv,
    heightDiv: opts.heightDiv       
  });
}

