/*
* JQuery feed fetcher from Google Feed
*
* Makes easier feed fetch from any RSS or XML feed, with Google Feed API on the fly
*
* Adds the following methods to jQuery:
* 
* $('.blog_content').feedfetcher(); - append a feed list in the applied DOM element with link to the source of feed result.
*
* Parameters
*	feed_source: '[feed_source]' - the source of the feed
*	head_class: '[class]' - append a feed source link and name to the given DOM element
*
*
* Result
* 	- A list of paragraphs contain a feed title with a link to a feed soure
*
* WARNING
* You need to load the JS API from google to use this plug-in
*
*	<script type="text/javascript" src="http://www.google.com/jsapi"></script>
*	<script type="text/javascript">
*    google.load("feeds", "1");
*	</script>
*
* Copyright (c) 2009 Istvan Ferenc Toth
*
* Plugin homepage:
* http://adminlight.com/static/files/feedfetch.html
*
* Example:
* http://adminlight.com/static/files/feedfetch.html
*
* Version 0.1.0.0
*
* Tested with:
* - Linux: Firefox 2
* - Windows: Firefox 2, Internet Explorer 6+
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Credits:
*   - http://code.google.com/: 
*   - http://adminlight.com: 
*	- http://www.learningjquery.com/2007/10/a-plugin-development-pattern
*/
 
  (function($) {
	//
	// plugin definition
	//
	$.fn.feedfetcher = function(options) {
	  // build main options before element iteration
	  var opts = $.extend({}, $.fn.feedfetcher.defaults, options);
	  // iterate and reformat each matched element
	  return this.each(function() {

		$this = $(this);
		// build element specific options
		var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
		// display feed
		

		var feed = new google.feeds.Feed(o.feed_source);
		feed.setNumEntries(o.feed_items)
		var target = this;
		
		feed.load( function(results){ $.fn.feedfetcher.processResults(results, target, o) } );
		
	  });
	};
	
	//
	$.fn.feedfetcher.processResults = function(result, target, o){
		
			$this = $(target);
		
			debug('feed contact ok');
			
			if (!result.error) {
				debug('feed content loaded');
				//$this.hide();
				//if (o.head_class!='') $('.'+o.head_class).append('<a href="'+result.feed.link+'" target="_blank">'+result.feed.title+'</a>');
				
				//var dl = document.createElement("dl");
				var container = $(o.container).appendTo($this);
				
				for (var i=0; i<result.feed.entries.length && i < o.feed_items; i++){
					var entry = result.feed.entries[i];
	
					var minute = 1000*60;
					var hour = minute*60;
					var day = hour * 24;
					
					var timestamp = new Date(entry.publishedDate);
					var now = new Date();
					
					var offset = ( now - timestamp);
			
					var when; //published when e.g. 1hour ago, 35 minutes ago
					
					
					if(offset < hour){
						var c = Math.floor(offset / minute);
						when =  c + " minute" + ( c != 1 ? "s" : "" ) + " ago";
					}else if(offset < day){
						var c = Math.floor(offset / hour);					
						when =  c + " hour" + ( c != 1 ? "s" : "" ) + " ago";
					}else{
						var c = Math.floor(offset / day);					
						when =  c != 1 ? c + " days ago" : "yesterday";
					}
					
					var author = entry.author.replace( /\(.*\)/ig, "");
					
					
					// 	$link$ 		= entry.link
					//	$author$ 	= entry.author
					//	$when$		= formatted date, e.g. 5 minutes ago, or 2 days ago.
					//	$content$	= entry.content
					var _item = o.itemtemplate;
					
					var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"];
					
					var day = timestamp.getDate();
					var month = months[timestamp.getMonth()];
					
					_item = _item.replace(/\$when\$/ig, when); 
					_item = _item.replace(/\$author\$/ig, author);
					_item = _item.replace(/\$title\$/ig, entry.title);
					_item = _item.replace(/\$link\$/ig, entry.link);
					_item = _item.replace(/\$day\$/ig, day);
					_item = _item.replace(/\$month\$/ig, month);
					
					
					//Content - currently hardcoded truncate
					var content = $.fn.feedfetcher.truncateString(entry.content, {wordcount: o.contentWordCount} );
					if(o.parselinks)content = content.replace(/(http:\/\/([^\s]*))/, "<a href='$1' target='_blank'>$1</a>")
					
					if(o.contentparsefunction){
						//content = o.contentparsefunction(content);
						content = o.contentparsefunction(content);
					}
					
					_item = _item.replace(/\$content\$/ig,  content);
					
					
						
					
					container.append(_item);
					
					/*
					$(dl)
						.append('<dt><a href="' + entry.link + '" target="_blank" onclick="pageTracker._trackPageview(\'/rss-feed-external/' + entry.link.replace("http://", "") +'\');return fbs_click();">' + byline + '</a></dt><dd>' + entry.content.replace(/(http:\/\/([^\s]*))/, "<a href='$1' target='_blank' onclick=\"pageTracker._trackPageview(\'/rss-feed-external/$2');return fbs_click();\">$1</a>") + '</dd>');
					*/

				}
			} else {
				debug('feed error');
				$this.append('<p>'+result.error.message+'</p>');
			}
			//$this.fadeIn("fast");
		
	}
	
	
	//
	// Truncate
	//
	$.fn.feedfetcher.truncateString = function( s,o ){


		this.options		  	= o || {};
		this.wordcount			= this.options.wordcount || 100;
		
		//split the string into word array
		var sa = s.split(" ");
		
		//Return original string
		if(sa.length <= this.wordcount) return s;
		//return the truncated string
		var tsa = sa.slice(0, this.wordcount)
		tsa.push("...")
		return tsa.join(" ");

	}
	
	//
	// private function for debugging
	//
	function debug($obj) {
	  if (window.console && window.console.log)
		window.console.log('feedfetcher: ' + $obj);
	};
	//
	// plugin defaults
	//
	$.fn.feedfetcher.defaults = {
	  feed_source: 'http://adminlight.blogspot.com/feeds/posts/default',
	  container:	"<ul id='blog-posts'>",
	  itemtemplate:	"<li> <div class='title'><a href='$link$' target='blank'>$title$</a></div> <div class='summary'>$content$</div> <div class='data'><span class='date'>Posted $when$</span></div></li>",
	  contentWordCount:	50,
	  parselinks: false,
	  contentparsefunction: null
	};
//
// end of closure
//
})(jQuery);


