/**
 * Easy to use RSS feed viewer. 
 * NewsWidget can even combine multiple RSS feeds and show the latest news items of these feeds.
 * 
 * @package News Widget
 * @author Sitebase (http://www.sitebase.be)
 * @version 1.6.1
 * @license http://codecanyon.net/wiki/support/legal-terms/licensing-terms/
 * @copyright Copyright (c) 2008-2011 Sitebase (http://www.sitebase.be)
 */
(function($){
	$.fn.newswidget = function(options) {

		/**
		 * The dollar sign could be overwritten globally,
		 * but jQuery should always stay accesible
		 */
		var $ = jQuery;
	
		var defaults = {
		  	source: ['http://feeds.feedburner.com/computerfaq/rss', 'http://feeds.feedburner.com/FlexExamples', 'http://community.invisionpower.com/rss/downloads/'],
			proxyUrl: 'proxy.php',
			limitDescription: 100,
			limitDescriptionSuffix: "...",
			limitItems: 10,
			stripHtml: true,
			prettyDate: true,
 			format: '<li><h4>{title}</h4><div class="description">{description}</div><span class="date"">{prettyDate}</span><span class="link"><a href="{link}">read more</a></span><span class="websiteTitle">{websiteTitle}</span></li>',
			animationSpeed: 500,
			random: true,
			refresh: 0,
			dateFormat: 'd-m-Y',
			showFilter: function(){}
		  },
		settings = $.extend({}, defaults, options);
		
		// Variables
		var newsHolder 		= this;
		var templateVars	= ['title', 'link', 'description', 'date', 'prettyDate', 'image', 'websiteTitle', 'websiteLink']
		var items			= [];
		var timer;
		var previous 		= ''; // Used to check if the content is changed 
			
		// Start script
		init();
			
		/**
		 * Init
		 */
		function init(){
		
			// Kill timer
			if(settings.refresh > 0){
				clearTimeout(timer);
			}
			
			// Reset items array
			items = [];
		
			// Reload items
			load( settings.source );
		}
		
		
		// Show items in news holder
		function show( items ){
			
			var rendered_items = '';
			for(var idx in items){
				var template = settings.format;
				var item = items[idx];
				
				settings.showFilter.call(item);
				
				// Replace template variables
				for(var var_idx in templateVars) {
					var_name = templateVars[var_idx];
					if(var_name == 'description') {
						template = template.replace('{' + var_name + '}', limitText(stripHtml(item[var_name]), settings.limitDescription, settings.limitDescriptionSuffix));
					} else {
						template = template.replace('{' + var_name + '}', item[var_name]);
					}
				}	
				
				rendered_items += template;
			}
			
			// Show items is they are changed
			var new_items = $(rendered_items).hide();
			if(rendered_items != previous) {
				previous = rendered_items;
				newsHolder.html(new_items.fadeIn(settings.animationSpeed));
			}
			
			// Start timer (again)
			if(settings.refresh > 0){
				timer = setTimeout(init, settings.refresh);
			}

		}
		
		/**
		 * Check if an object is of type array
		 */
		function isArray(object) {
			if (object.constructor.toString().indexOf("Array") == -1) {
			  return false;
		   	} else {
			  return true;
			}
		}
		
		/**
		 * Load RSS
		 */
		function load( source ){
			
			var data = '';
			if(isArray(source)) {
				data = source.join('|');
			} else {
				data = source;
			}
			
			$.ajax({
				type: 'POST',
				data: 'source=' + data + '&limit=' + settings.limitItems + '&date_format=' + settings.dateFormat + '&random=' + settings.random + '&rnd=' + Number(new Date()),
				url: settings.proxyUrl + '?url=' + source,
				dataType: 'json',
				success: parse
			});
		}
		
		/**
		 * Parse json
		 */
		function parse(json) {
			if(json.error) {
				newsHolder.html('<strong>ERROR:</strong> ' + json.error);
				return;
			}
			show(json);
		}
		
		/**
		 * Limit text
		 */
		function limitText( text, limit, suffix ){
			if(text.length > limit){
				text = text.substr(0, limit) + suffix;
			}
			return text;
		}
		
		/**
		 * Strip HTML
		 */
		function stripHtml( text ){
			if(settings.stripHtml) {
				var matchTag = /<(?:.|\s)*?>/g;
				return text.replace(matchTag, "");
			}
			return text;
		}

		
		// returns the jQuery object to allow for chainability.
		return this;
	}
})(jQuery);
