//
// THIS PLUGIN HAS BEEN MODIFIED BY SCOTT HORLBECK <shorlbeck@salud.unm.edu> OF HSC WEB TEAM TO SUIT OUR PURPOSES
//

/**
 * 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,
			header: true,
			titletag: 'h4',
			date: true,
			content: true,
			snippet: true,
			showerror: true,
			errormsg: '',
			key: null,
			getTodaysEntriesOnly : false, // Added by Scott Horlbeck
			customAPI : '',         // Added by Scott Horlbeck
			useTestFeed : false,    // Added by Scott Horlbeck
			callback : function(){} // Added by Scott Horlbeck
		};  
		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 && options.customAPI.length == 0) return false;

			
			if (options.customAPI.length == 0) {
				// 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;
				if (options.key != null) api += "&key=" + options.key;

			} else {
				var api = options.customAPI + '?';
				if (options.limit != null) api += "num=" + options.limit;
				if (options.useTestFeed) api += "&useTestFeed=true";
			}
	
			// Send request
			$.ajax({
				"url" : api,
				"dataType" : "json",
				"cache" : false,
				"success" : function(data, textStatus, XMLHttpRequest){
					// 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>');
					}
				},
				"error" : function(XMLHttpRequest,textStatus,errorThrown) {
					if (console)
						console.log(textStatus + ': ' + errorThrown);
				}
			});
		});
	};
	
	// 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=0; i<$(feeds.entries).length; i++) {
		$(feeds.entries).each(function(i) {
			
			// Get individual feed
//			var entry = feeds.entries[i];
			var entry = $(this);
			
			// Format published date
			var entryDate = new Date(entry.attr('publishedDate'));
			var todaysDate = new Date();

		  if (options.getTodaysEntriesOnly && todaysDate.toLocaleDateString() != entryDate.toLocaleDateString() ) {
				return true; // equivalent to "continue" in a for loop
			}

			
			var pubDate = entryDate.toLocaleDateString() + ' ' + entryDate.toLocaleTimeString();
			
			// Add feed row
			if (i == 0)
				row = 'firstRssRow';

			html += '<li class="rssRow '+row+'">';
			var titleHtml = '(<'+ options.titletag +'><a href="'+ entry.attr('link') +'" title="View this feed at '+ $(feeds).attr('title') +'">'+ entry.attr('title') +'</a></'+ options.titletag +'>)';
			if (options.date) html += '<div class="rssDate">'+ pubDate +'</div>';
			if (options.content) {

				// Use feed snippet if available and optioned
				if (options.snippet && entry.attr('contentSnippet') != '') {
					var content = entry.attr('contentSnippet');
				} else {
					var content = entry.attr('content');
				}

				html += '<p>'+ content +'</p>'
			}

			html += ' ' + titleHtml + '</li>';

			// Alternate row classes
			if (row == 'odd') {
				row = 'even';
			} else {
				row = 'odd';
			}
		});
		
		html += '</ul>' +
			'</div>';

		$(e).html(html);


		// statement below added by Scott Horlbeck <shorlbeck@salud.unm.edu> of HSC Web and Applications Team
		if (typeof(options.callback) == 'function')
			options.callback();

	};
})(jQuery);

