/*
* jQuery.emoryFeed
* v0.01
* 
* last modified July 18, 2011
* by Andrew Roberts
*
* Description: uses Google Feeds API (jGFeed 1.0 plugin) to
* obtain RSS / Atom feed in JSON format, then places the
* contents of the feed into the designated container.
*
* Customizable using the following settings:
*	
*	feedURL*				the URL of an RSS or Atom feed (* REQUIRED)
*	maxItems				the total number of items in the feed to display;
*							default is 10.
*	feedTitle				the title to display in the heading at the top of
*							the container; if not provided, default behavior
*							is to use the title of the RSS feed.
*	rssIconURL				the RSS icon to show at the top corner of the
*							container. default is to use the Emory-hosted one.
*	viewAllText				the text that appears at the bottom of the feed;
*							default: "View all stories"
*	viewAllTextURL			the URL of all the stories. default behavior is
*							to use the RSS feed here.
*							you may specify an HTML-formatted link here, for
*							example, or a trumba calendar link.
*	useContentSnippet		if set to true, the first item will use the
*							"content snippet" text for the summary of the
*							first item.
*   contentSelector			(only if useContentSnippet is not "true") the
*   						jQuery selector for the element inside the
*   						"content" that contains the text you'd like to
*   						use for the summary of the fist item.
*	maxWords				(only if useContentSnippet is not "true") the
*							maximum number of words you'd like to appear in
*							the summary. The rest will be truncated
*							(with trailing ellipsis: "...")
*   thumbnailSelector		(only if useContentSnippet is not "true") the
*   						jQuery selector used to obtain the thumbnail
*   						image for the first item. by default, the
*   						selector is "img" and will therefore use the
*   						first image that occurs in the content.
*   thumbnailMaxWidth		(only if useContentSnippet is not "true") the
*   						maximum width of the thumbnail, in pixels.
*   						default is 120.
*/

(function ( $ ) 
		{

		    jQuery.fn.emoryFeed = function ( options ) {

		    	if (jQuery.jGFeed == null)
			           jQuery.error("The jGFeed jQuery plugin is missing. This plugin is required by jQuery.emoryFeed. Please import it.");

			        var settings =
			        {
			           feedURL : null,
			           maxItems : 10,
					   feedTitle: null,
					   rssIconURL : "http://www.emory.edu/home/img/rss.gif",
					   viewAllText : "View all stories",
					   viewAllTextURL : null,
					   useContentSnippet : false,
					   contentSelector : "*",
					   maxWords : 50,
					   thumbnailSelector: "img",
					   thumbnailMaxWidth: 120
			        };

			        if ( options )
			            $.extend( settings, options );

			        if (settings.feedURL == null)
			            jQuery.error("Parameter for 'feedURL' is missing; this parameter is required by jQuery.emoryFeed.");


			        // functions used by clRssScroller
			        
			        var formatDate = function(dateString)
			            {
			                var m_names = new Array("January", "February", "March", 
			                                        "April", "May", "June", "July", "August", "September", 
			                                        "October", "November", "December");

			                var date = new Date(dateString);

			                var monthName = m_names[date.getMonth()];

			                var day = date.getDate();

			                var fullYear = date.getFullYear();

			                var out = monthName+" "+day+", "+fullYear;

			                return out;
			            };
			            

				        return this.each(function()
						        {
						            
						            var context = $(this);
						            
						            context.data('currentItem', 1);
						                        			            
						            var rssLoaded;
						            
						            $.jGFeed(
						                settings.feedURL,
						                function(rss) { rssLoaded(rss); },
						                settings.maxItems
						            );
						                
						            
						            var rssLoaded = function(rss)
						            {						               
						               var $headingWrapDiv = $("<div></div>").addClass("heading_wrap");
						               
						               var $titleSpan = $("<span>"+((settings.feedTitle != null) ? settings.feedTitle : rss.title)+"</span>").addClass("h2rss");
						               
						               var $h2 = $("<h2></h2>").append($titleSpan);
						               
						               
						               var $spanRssAudience = $("<span></span>").addClass("rss_audience");
						               
						               var $feedSourceA = $("<a></a>").attr("title", "RSS").attr("href", rss.feedUrl);
						               
						               var $rssIcon = $("<img />").attr("alt", "RSS").attr("src", settings.rssIconURL);
						               
						               $feedSourceA.append($rssIcon);
						               
						               $spanRssAudience.append($feedSourceA);
						               
						               $headingWrapDiv.append($h2);
						               
						               $headingWrapDiv.append($spanRssAudience);
						               
						               context.append($headingWrapDiv);
						               
						               // ----
						               // Feature Story .
						               
						               var $featureStoryH3 = $("<h3></h3>");
						               
						               var $featureStoryA = $("<a>"+rss.entries[0].title+"</a>").attr("href", rss.entries[0].link);
						               
						               context.append($featureStoryH3);
						               
						               var $featureStoryP = $("<p></p>");
						               
						               if (settings.useContentSnippet)
						               {					               
						               		$featureStoryP.append(rss.entries[0].contentSnippet);
						               		
						               }
						               else
						               {
						            		var $content = $("<div>"+rss.entries[0].content+"</div>");
						            		
						            		var $thumbnail = $(settings.thumbnailSelector, $content);
						            		
						            		$thumbnail.attr("align", "left");
						            		
						            		var contentSnippet = "";
						            		
						            		$(settings.contentSelector, $content).each(function(i)
						            		{
						            			contentSnippet = contentSnippet+" "+$(this).text();
						            		});
						            								            		
						            		var contentSnippetArray = contentSnippet.split(" ");
						            		
						            		var truncatedText = "";
						            		
						            		for (var i = 0; i < settings.maxWords && i < contentSnippetArray.length; i++)
						            		{
						            			truncatedText = truncatedText+" "+contentSnippetArray[i];
						            		}
						            		
						            		if (truncatedText.charAt(truncatedText.length - 1) != ".")
						            			truncatedText = truncatedText+"...";
						            									            		
						            		$featureStoryP.append($thumbnail).append(truncatedText);
						            		
						               }
						               
						               context.append($featureStoryP);
						               
						               $("img", $featureStoryP).each(function()
						            		   {
						            	   			var proportions = $(this).width() / $(this).height();
						            	   			
						            	   			var w = settings.thumbnailMaxWidth;
						            	   			
						            	   			var h = Math.floor(settings.thumbnailMaxWidth / proportions);
						            	   			
						            	   			$(this).css({"width" : w, "height" : h, "margin" : "auto"});
						            	   			
						            		   });
						               

						               var $featureStoryContinueP = $("<p></p>");
						               
						               var $featureStoryContinueA = $("<a>Continue reading</a>").attr("href", rss.entries[0].link);
						               
						               $featureStoryContinueP.append($featureStoryContinueA);
						               
						               $featureStoryH3.append($featureStoryA);
						               
						               context.append($featureStoryContinueP);
						               
						               // ----
						               // Rest of stories
						               
						               var $newsFeedDiv = $("<div></div>").attr("id", "newsfeed");
						               
						               var $newsFeedAlsoInNews = $("<h5>Also in the News</h5>");
						               
						               var $ulMoreList = $("<ul></ul>").addClass("moreList");
						               						               
						               for (var i = 1; i < rss.entries.length; i++)
						               {
						            	   var currentEntry = rss.entries[i];
						            	   
						            	   var $entryLi = $("<li></li>");
						            	   
						            	   var $entryA = $("<a>"+currentEntry.title+"</a>").attr("href", currentEntry.link);
						            	   
						            	   $entryLi.append($entryA);
						            	   
						            	   $ulMoreList.append($entryLi);
						               }
						               
						               $newsFeedDiv.append($newsFeedAlsoInNews).append($ulMoreList);
						               
						               context.append($newsFeedDiv);
						               
						               var $viewAllA = $("<a>"+settings.viewAllText+"</a>").addClass("viewAll")
						               					.attr("href", ((settings.viewAllTextURL != null) ? settings.viewAllTextURL : settings.feedURL));
						               var $viewAllP = $("<p></p>").append($viewAllA);
						               
						               context.append($viewAllA);
						               
						            };
						        });      
		            
		    }
		})( jQuery );
