/**
 * 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
 *
 **/
 
var associativeArray = [];
associativeArray["Cisco Canada"] = "ciscocanada";
associativeArray["Brantz Myers"] = "brantzmyers";
associativeArray["Rick Huijbregts"] = "rickhuijbregts";
associativeArray["Nitin Kawale"] = "nitinkawale";
associativeArray["Ayelet Baron"] = "ayeletbaron";
associativeArray["Jeff Seifert"] = "jeffseifert";
associativeArray["rondekker"] = "rondekker";
associativeArray["Mike Ansley"] = "mansley";
associativeArray["Willa Black"] = "willablack";
associativeArray["Mark Kummer"] = "makummer";
associativeArray["Bill Kastelic"] = "billkastelic";
associativeArray["Ian Gallagher"] = "iagallagher";

(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: '',
			showusername: false,
			author:false,
			key: null,
			showoptions: false
		};  
		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;
			if (options.key != null) api += "&key=" + options.key;

			// Send request
			$.getJSON(api, function(data){
				
				// Check for error
				if (data.responseStatus == 200) {
	
					// Process the feeds
					if(url.indexOf("http://search.twitter.com/search.atom?q=") != -1)
						_callbackTwitter(e, data.responseData.feed, options);
					else
						_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 _callbackTwitter = 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>';
		if(feeds.entries.length == 0 && (feeds.title.indexOf("18york")!=-1))
		{
			html += '<li class="rssRow odd"><h4>No current tweets have been found with the hashtag #18york or #smart18york. Meanwhile please use the Follow Us dropdown to follow one of our channels.</h4></li>';
		}
		else if(feeds.entries.length == 0)
		{
			html += '<li class="rssRow odd"><h4>No current tweets available for now.</h4></li>';
		}

		// Add feeds
		for (var i=0; i<feeds.entries.length; i++) {
			
			// Get individual feed
			var entry = feeds.entries[i];

			// Format published datealert(entry.tweet_id);
			var entryDate = new Date(entry.publishedDate);
			//var pubDate = entryDate.toLocaleDateString() + ' ' + entryDate.toLocaleTimeString();
			
			// Add feed row
			var temp = entry.title.split(" ");
			var textString = "";
			if(options.showusername)
			{
					var tempUserName = entry.author.split(" ");
					textString += '<a href="http://www.twitter.com/' + tempUserName[0] + '" target="_blank" class="twitter-channel-name"><strong>' + tempUserName[0] + '</strong></a> ';
			}
			
			for (j=0;j<temp.length;j++)
			{
				// Convert usernames (@) into links
				if(temp[j].charAt(0) == "@")
				{
					var patt = new RegExp("[a-zA-Z0-9\_]+");
					temp[j] = '<a href="http://www.twitter.com/' + patt.exec(temp[j].substr(1)) + '" target="_blank">@' + temp[j].substr(1) + '</a>';
				}
				else if(temp[j].charAt(0) == "#")
				{
					temp[j] = '<a href="http://search.twitter.com/search?q=%23' + temp[j].substr(1) + '" target="_blank">#' + temp[j].substr(1) + '</a>';
				}
				else if(temp[j].length > 7)
				{
					if(temp[j].slice(0,7) == "http://")
						temp[j] = '<a href="' + temp[j] + '" target="_blank">' + temp[j] + '</a>';
				}
				if(j==(temp.length-1))
					textString += temp[j];
				else
					textString += temp[j] + ' ';
			}
			html += '<li class="rssRow '+row+'">' + 
				'<'+ options.titletag +'>' + textString +'</'+ options.titletag +'>'
			if (options.content) {
			
				// Use feed snippet if available and optioned
				if (options.snippet && entry.contentSnippet != '') {
					var content = entry.contentSnippet;
				} else {
					var content = entry.content;
				}
				
				html += '<p>'+ content +'</p>'
			}
	
			if (options.showoptions && options.date)
			{
				html += '<div style="border-bottom:none;"><a href="' + entry.link + '" title="' + feeds.description + '" target="_blank">'+ jQuery.timeago(entryDate) +'</a></div>';
				var tempURL = entry.link.split("/");
				var tweetID = tempURL[tempURL.length - 1];
				html += '<div style="margin-top: 5px; font-size:11px;"><img src="/web/CA/assets/images/reply.png" alt="" /> <a id="windowwindow" href="http://twitter.com/intent/tweet?in_reply_to=' + tweetID + '" title="Reply" target="_blank" onclick="window.open(\'http://twitter.com/intent/tweet?in_reply_to=' + tweetID + '\',\'\',\'location=yes,status=yes,scrollbars=no,resizable=yes,width=550,height=450,top=175,left=375\');return false;">Reply</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="/web/CA/assets/images/retweet.png" alt="" /> <a id="windowwindow" href="http://twitter.com/intent/retweet?tweet_id=' + tweetID + '" title="Retweet" target="_blank" onclick="window.open(\'http://twitter.com/intent/retweet?tweet_id=' + tweetID + '\',\'\',\'location=yes,status=yes,scrollbars=no,resizable=yes,width=550,height=450,top=175,left=375\');return false;">Retweet</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="/web/CA/assets/images/fav.png" alt="" /> <a id="windowwindow" href="http://twitter.com/intent/favorite?tweet_id=' + tweetID + '" title="Favorite" target="_blank" onclick="window.open(\'http://twitter.com/intent/favorite?tweet_id=' + tweetID + '\',\'\',\'location=yes,status=yes,scrollbars=no,resizable=yes,width=550,height=450,top=175,left=375\');return false;">Favorite</a></div>';
			}
			else if (options.date) html += '<div><a href="' + entry.link + '" title="' + feeds.description + '" target="_blank">'+ jQuery.timeago(entryDate) +'</a></div>';
			
			html += '</li>';
			
			// Alternate row classes
			if (row == 'odd') {
				row = 'even';
			} else {
				row = 'odd';
			}			
		}
		
		html += '</ul>' +
			'</div>'

		$(e).html(html);
	};
	
	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++) {
			
			// Get individual feed
			var entry = feeds.entries[i];
			// Format published date
			var entryDate = new Date(entry.publishedDate);
			var pubDate = entryDate.toLocaleDateString() + ' ' + entryDate.toLocaleTimeString();
			
			// Add feed row
			html += '<li class="rssRow '+row+'">' + 
				'<'+ options.titletag +'><a href="'+ entry.link +'" target="_blank" title="View this feed at '+ feeds.title +'">'+ entry.title +'</a></'+ options.titletag +'>'
			if (options.content) {
			
				// Use feed snippet if available and optioned
				if (options.snippet && entry.contentSnippet != '') {
					var content = entry.contentSnippet;
				} else {
					var content = entry.content;
				}
				
				html += '<p>'+ content +'</p>'
			}
			if (options.author)
			{
				//if (options.date) html += '<div style="margin-top:5px;">Posted by <a href="'+ entry.link +'" target="_blank" title="View this feed at '+ feeds.title +'"><strong>'+ entry.author + '</strong></a> on ' + pubDate +'</div>'
				if (options.date) html += '<div style="margin-top:5px;">Posted by <a href="http://ciscocanada.wordpress.com/author/'+ associativeArray[entry.author] +'/" target="_blank" title="View all posts by '+ entry.author +'"><strong>'+ entry.author + '</strong></a> on ' + pubDate +'</div>'
				else html += '<div></div>'
			}
			else
			{
				if (options.date) html += '<div>'+ pubDate +'</div>'
				else html += '<div></div>'
			}
			html += '</li>';
			
			// Alternate row classes
			if (row == 'odd') {
				row = 'even';
			} else {
				row = 'odd';
			}			
		}
		
		html += '</ul>' +
			'</div>'
		
		$(e).html(html);
	};
})(jQuery);

