(function($) {

	/*
		source: http://www.ooeygui.net/articles/43
		date:   January 5, 2010
		modified by clever.tv
	*/
	
	$.extend(jQuery.fn,{
	
		feed : function(params){
		
			var $this = $(this);

			var $ajaxMgr = $.manageAjax({
				manageType: 'abortOld', 
				maxReq: 5, 
				blockSameRequest: true
			});
			
			// Set the variables to be used within the class
			var $url = params.url;
			var $count = params.count || 1;
			var $vars = params.vars || ["title","description","link","pubDate"];
			var $template = params.template || $this.html();
			
			$.replaceAll = function(needle, value, subject){
				var $subject = subject;
			
				while($subject.indexOf("@"+needle) != -1){
					$subject = $subject.replace("@"+needle, value);
				}
				
				return $subject;
			}
			
			// What to do after a request has been completed
			$this.complete = params.complete || function(html){
				$this.html(html);
			}
			
			// What to do while a request is in progress
			$this.loading = params.loading || function(){
				$this.html("<span class=\"loading\">Loading...</span>");
			}
		
			// Make a request
			$this.request = function(url){
				
				$this.loading();
				
				$ajaxMgr.add({
					success : function(html){
					
						var $v = [];
						var $t = [];
						var $tmp = "";
						
						// Grab values from the feed
						for(var i in $vars){
							$v[i] = $.xmlDOM(html).find("rss > channel > item > "+$vars[i]);	
						}
						
						var numItems = 0;
						if (($v.length > 0) && ($v[0].length > 0))
							numItems = $v[0].length;
						if ($count < numItems) 
							numItems = $count;
						
						// Build the html
						for(i = 0; i < numItems; i++){
							$t[i] = $template;
							
							for(var n in $v){
								$t[i] = $.replaceAll($vars[n], $($($v[n])[i]).text(), $t[i])
							}
							
							$tmp += $t[i];
							
						}
					
						$this.complete($tmp);
						
					},
					url : url
				});
								
			}
			
			$this.request($url);
			
		}		
		
	});

})(jQuery);
