
var gfeedfetcher_loading_image="images/loading_w.gif" //Full URL to "loading" image. No need to config after this line!!

google.load("feeds", "1") //Load Google Ajax Feed API (version 1)


function gfeedfetcher(Command, divid, divClass, titleStyle, descStyle, linktarget, fname, vars, chid, picW){

this.descMode = Command || "" //(Command=='FullNews'?'description':'contentSnippet') //display mode for content
this.linktarget=linktarget || "" //link target of RSS entries
	this.titleStyle=titleStyle || "" //title style
	this.descStyle=descStyle || "" //desc style
	this.fname=fname || "" //Feed Name	
	this.vars=vars || "" //Additional variables
	this.chid=chid || "" //Channel ID
	this.picW=picW || "90" //picture width
	
	this.feedlabels=[] //array holding lables for each RSS feed
	this.feedurls=[]
	this.feeds=[] //array holding combined RSS feeds' entries from Feed API (result.feed.entries)
	this.feedsfetched=0 //number of feeds fetched
	this.feedlimit=5
	this.showoptions="" //Optional components of RSS entry to show (none by default)
	this.sortstring="date" //sort by "date" by default
	//document.write('<div id="'+divid+'" class="'+divClass+'"></div>') //output div to contain RSS entries
	this.feedcontainer=document.getElementById(divid)

	this.itemcontainer="<li>" //default element wrapping around each RSS entry item
}

function getImageFromContent(content,Mode,pw) {

var img = content.match(/<img[^>+]*>/i);
      if(img) {
        var source = img[0].match(/src="[^"+]*"/i),
        alt = img[0].match(/alt="[^"+]*"/i), titleTXT = img[0].match(/title="[^"+]*"/i);
// Filter
var altText = $(img[0]).attr('alt').toLowerCase();
var titleText = $(img[0]).attr('title').toLowerCase();
var imgSRC = $(img[0]).attr('src');
// Get Size

if(Mode=='FullNews') {
var w = 125;
var c = 'N';
} else {
var w = pw;
var c = 'Y';
}

return '<img src=".Thumbnailer.php?pic='+imgSRC+'&crop=Y&w=' + w + '&filterNews=Y" ' + alt + ' style="float: left;margin: 0 8px 8px 0;" >';
   
}
      return '<img src=".Thumbnailer.php?pic=images/0-bullet-gray.gif&crop=N&w=6" style="float: left;margin: 4px 8px 4px 0" >';
}

gfeedfetcher.prototype.addFeed=function(label, url){
	this.feedlabels[this.feedlabels.length]=label
	this.feedurls[this.feedurls.length]=url
}

gfeedfetcher.prototype.filterfeed=function(feedlimit, sortstr){
	this.feedlimit=feedlimit
	if (typeof sortstr!="undefined")
	this.sortstring=sortstr
}

gfeedfetcher.prototype.displayoptions=function(parts){
	this.showoptions=parts //set RSS entry options to show ("date, datetime, time, snippet, label, description")
}

gfeedfetcher.prototype.setentrycontainer=function(containerstr){  //set element that should wrap around each RSS entry item
this.itemcontainer="<"+containerstr.toLowerCase()+">"
}

gfeedfetcher.prototype.init=function(){
	this.feedsfetched=0 //reset number of feeds fetched to 0 (in case init() is called more than once)
	this.feeds=[] //reset feeds[] array to empty (in case init() is called more than once)
	this.feedcontainer.innerHTML='<br /><br /><br /><br /><center><span style="font-size:13px;font-weight:bold"><img src="'+gfeedfetcher_loading_image+'" align=\"absmiddle\" /> Loading...</span></center><br /><br /><br /><br />'
	var displayer=this
	for (var i=0; i<this.feedurls.length; i++){ //loop through the specified RSS feeds' URLs
		var feedpointer=new google.feeds.Feed(this.feedurls[i]) //create new instance of Google Ajax Feed API
		var items_to_show=(this.feedlimit<=this.feedurls.length)? 1 : Math.floor(this.feedlimit/this.feedurls.length) //Calculate # of entries to show for each RSS feed
		if (this.feedlimit%this.feedurls.length>0 && this.feedlimit>this.feedurls.length && i==this.feedurls.length-1) //If this is the last RSS feed, and feedlimit/feedurls.length yields a remainder
			items_to_show+=(this.feedlimit%this.feedurls.length) //Add that remainder to the number of entries to show for last RSS feed
		feedpointer.setNumEntries(items_to_show) //set number of items to display
		feedpointer.load(function(label){
			return function(r){
				displayer._fetch_data_as_array(r, label)
			}
		}(this.feedlabels[i])) //call Feed.load() to retrieve and output RSS feed.
	}
}


gfeedfetcher._formatdate=function(datestr, showoptions){
	var itemdate=new Date(datestr)
	var parseddate=(showoptions.indexOf("datetime")!=-1)? itemdate.toLocaleString() : (showoptions.indexOf("date")!=-1)? itemdate.toLocaleDateString() : (showoptions.indexOf("time")!=-1)? itemdate.toLocaleTimeString() : ""
	return "<span class='datefield'>"+(parseddate=='Invalid Date'?'':parseddate)+"</span>"
}

gfeedfetcher._sortarray=function(arr, sortstr){
	var sortstr=(sortstr=="label")? "ddlabel" : sortstr //change "label" string (if entered) to "ddlabel" instead, for internal use
	if (sortstr=="title" || sortstr=="ddlabel"){ //sort array by "title" or "ddlabel" property of RSS feed entries[]
		arr.sort(function(a,b){
		var fielda=a[sortstr].toLowerCase()
		var fieldb=b[sortstr].toLowerCase()
		return (fielda<fieldb)? -1 : (fielda>fieldb)? 1 : 0
		})
	}
	else{ //else, sort by "publishedDate" property (using error handling, as "publishedDate" may not be a valid date str if an error has occured while getting feed
		try{
			arr.sort(function(a,b){return new Date(b.publishedDate)-new Date(a.publishedDate)})
		}
		catch(err){}
	}
}

gfeedfetcher.prototype._fetch_data_as_array=function(result, ddlabel){	
	var thisfeed=(!result.error)? result.feed.entries : "" //get all feed entries as a JSON array or "" if failed
	if (thisfeed==""){ //if error has occured fetching feed
		alert("Error loading resource! Please try another. Error No.: "+result.error.message)
	}
	for (var i=0; i<thisfeed.length; i++){ //For each entry within feed
		result.feed.entries[i].ddlabel=ddlabel //extend it with a "ddlabel" property
	}
	this.feeds=this.feeds.concat(thisfeed) //add entry to array holding all feed entries
	this._signaldownloadcomplete() //signal the retrieval of this feed as complete (and move on to next one if defined)
}

gfeedfetcher.prototype._signaldownloadcomplete=function(){
	this.feedsfetched+=1
	if (this.feedsfetched==this.feedurls.length) //if all feeds fetched
		this._displayresult(this.feeds) //display results
}



gfeedfetcher.prototype._displayresult=function(feeds){




	var rssoutput=(this.itemcontainer=="<li>")? "<ul>\n" : "<div style=\"display:block;width:100%\">"
	gfeedfetcher._sortarray(feeds, this.sortstring)
	for (var i=0; i<feeds.length; i++){
		//var itemtitle="<a href=\"" + feeds[i].link + "\" target=\"" + this.linktarget + "\" class=\"titlefield\" rel=\"shadowbox\">" + feeds[i].title + "</a>"
		var itemtitle="<a href=\"" + feeds[i].link + "\" "+(this.linktarget?"target=\""+this.linktarget+"\"":"rel=\"shadowbox\"")+"  title=\"" + feeds[i].title.replace('"',"&quot;") + "\" style=\""+this.titleStyle+"\">" + feeds[i].title + "</a>"
		
		var itemlabel=/label/i.test(this.showoptions)? '<span class="labelfield">['+this.feeds[i].ddlabel+']</span>' : " "
		var itemdate=gfeedfetcher._formatdate(feeds[i].publishedDate, this.showoptions)
		var CSnippet = "<br />"+feeds[i].contentSnippet
		var itemdescription=/description/i.test(this.showoptions)? "<br />"+feeds[i].content : /snippet/i.test(this.showoptions)? "<br />"+feeds[i].contentSnippet  : ""
		var Desc = (this.descMode=='FullNews' ? itemdescription : CSnippet)
		rssoutput+="<table width=\"100%\" border=0 cellspacing=2 cellpadding=2 style=\"width:100%;border-bottom:1px solid #D2E1FF\"><tr><td><div style=\"clear:both;display:block;height:auto;width:100%;padding:14px 0px 14px 0px;margin: 0px;\">" + getImageFromContent(feeds[i].content,this.descMode,this.picW) +  itemtitle +"&nbsp;&nbsp;<span style=\"color: #999;font-size:11px\" >" + itemdate + "</span>" + (feeds[i].contentSnippet.replace(/^\s+|\s+$/g, '')!=""?"\n <br />":"") + "<span style=\""+this.descStyle+"\">" +Desc.replace(/(<([^>]+)>)/ig,"") +"</span></div></td></tr></table>" }

	rssoutput+=(this.itemcontainer=="<li>")? "</ul>" : "</div>"
	rssoutput+='<div style="clear:both;width:100%;display:block;height:auto;padding:6px 0px"><table width="100%" border=0 cellspacing=2 cellpadding=2>'
	if(this.vars!="") {
	rssoutput+='<tr><td width="100%" nowrap><a '+decodeURIComponent((this.vars + '').replace(/\+/g, '%20'))+' class="main" style="background:transparent url(images/0-circle-dot.png) no-repeat center left; padding-left:30px;font-size:13px;height:24px; display:block; font-weight:bold;text-decoration: none;color: #006699;padding-top:8px; cursor: pointer; width:auto;">More from '+this.fname+'</a></td><td rowspan="2" align="right" nowrap valign="top" style="padding-top:8px"><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.livepage.info%2F'+this.chid+'&amp;layout=button_count&amp;show_faces=false&amp;width=120&amp;action=recommend&amp;font=arial&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:120px; height:21px;" allowTransparency="true"></iframe></td></tr>'
	}
	rssoutput+='<tr><td width="100%" nowrap style="font-size:11px;color:#999999;padding-top:8px">&copy; Copyright '+this.fname+'</td></tr></table></div>'
	this.feedcontainer.innerHTML=rssoutput



//Shadowbox.setup();


			
}


