/**
 * Plugin: jquery.zRSSFeed
 * 
 * Version: 1.0.1
 * (c) Copyright 2010, Zazar Ltd
 * 
 * Description: jQuery plugin for display of RSS feeds via Google Feed API
 *              (Based on original plugin jGFeed by jQuery HowTo)
 * 
 * History:
 * 1.0.1 - Corrected issue with multiple instances
 *
 **/

(function($){

	var current = null; 
	
	$.fn.rssfeed = function(url, options) {	
	
		// Set pluign defaults
		var defaults = {
			limit: 10,
			start: 0,
			header: true,
			titletag: 'h4',
			date: false,
			content: {include:true,text_length:100,images:false},
			snippet: true,
			showerror: true,
			errormsg: '',
			key: null
		};  
		var options = $.extend(defaults, options); 
		
		// Functions
		return this.each(function(i, e) {
			var $e = $(e);
			
			// Add feed class to user div
			if (!$e.hasClass('rssFeed')) $e.addClass('rssFeed');
			
			// Check for valid url
			if(url == null) return false;

			// Create Google Feed API address
			var api = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=" + url;
			if (options.limit != null) api += "&num=" + (options.limit+options.start);
			if (options.key != null) api += "&key=" + options.key;

			// Send request
			$.getJSON(api, function(data){
				
				// Check for error
				if (data.responseStatus == 200) {
	
					// Process the feeds
					_callback(e, data.responseData.feed, options);
				} else {

					// Handle error if required
					if (options.showerror)
						if (options.errormsg != '') {
							var msg = options.errormsg;
						} else {
							var msg = data.responseDetails;
						};
						$(e).html('<div class="rssError"><p>'+ msg +'</p></div>');
				};
			});				
		});
	};
	
	// Callback function to create HTML result
	var _callback = function(e, feeds, options) {

		if (!feeds) {
			return false;
		}
		var html = '';	
		var row = 'odd';	
		
		// Add header if required
		if (options.header)
			html +=	'<div class="rssHeader">' +
				'<a href="'+feeds.link+'" title="'+ feeds.description +'">'+ feeds.title +'</a>' +
				'</div>';
			
		// Add body
		html += '<div class="rssBody">' +
			'<ul>';
		
		// Add feeds
		for (var i=options.start; i<feeds.entries.length; i++) {
			
			// Get individual feed
			var entry = feeds.entries[i];
			
			// Format published date
			var entryDate = new Date(entry.publishedDate);
			var pubDate = entryDate.toLocaleDateString() + ' ' + entryDate.toLocaleTimeString();
			
			if(entry.title != '')
			{
				// Add feed row
				html += '<li class="rssRow '+row+'">'; 
				if (options.date) html += '<div>'+ pubDate +'</div>';
				html += '<'+ options.titletag +'><a href="'+ entry.link +'" title="View this feed at '+ feeds.title +'">'+ entry.title +'</a></'+ options.titletag +'>';
				
				if (options.content.include) {
				
					// Use feed snippet if available and optioned
/*
					if (options.snippet && entry.contentSnippet != '') {
						var content = entry.contentSnippet;
					} else {
*/
						var content = entry.content;
/*
					}
*/
					content = content.replace(new RegExp("<br>", "gim"), "");
					content = content.replace(new RegExp("<br />", "gim"), "");
					
					html += '<p>'+ content +'</p>'
				}
				
				html += '</li>';
				
				// Alternate row classes
				if (row == 'odd') {
					row = 'even';
				} else {
					row = 'odd';
				}			
			}
		}
		
		html += '</ul>' +
			'</div>'
		
		$(e).html(html);
		
		var i = 0;	
		$(e).find('h4 a').each(function(){
			$(this).attr('href',window.URL_ROOT+'page/News&anchor='+(i+1));
			i++;
		});
		
		if(options.content.images == false)
		{
			$(e).find('img').remove();
			$(e).find('div').each(function(){
				if($(this).text() == ''){ $(this).remove(); }
			});
		}
		
		if(options.content.text_length != null && options.content.text_length != false)
		{
			var title = $(e).find('.rssRow h4').text();
			
			// replace <br /> with ^ so we can use text() without loosing the breaks
			$(e).find('br').replaceWith( function(){ return '±'; } );

			var str = '';
			$('.rssRow p, .rssRow div').each(
				function(i)
				{
					var str_temp = $(this).text();
					if(str_temp != '') { str += str_temp+'<br />'; }
				}
			);

			str = str.substr(0,options.content.text_length);
			str = str.substr(0,str.lastIndexOf(' '));
			
			function replaceAllInString(txt, replace, with_this){ return txt.replace(new RegExp(replace, 'g'),with_this); }

			str = replaceAllInString(str,'±±','±');
			str = replaceAllInString(str,'±','<br />');
			
			var html = '<h4><a href="'+window.URL_ROOT+'page/News">'+title+'</a></h4>';
			if(str != ''){ html += '<p>'+str+'...</p>'; }
			
			$(e).html(html);
		}
	};
})(jQuery);


