// -------------------------------------------------------------------
// gAjax RSS Feeds Displayer- By Dynamic Drive, available at: http://www.dynamicdrive.com
// Created: July 17th, 2007 Updated: n/a
// -------------------------------------------------------------------

function myBrowser()
{
	this.name = navigator.appName;
	this.version = parseFloat(navigator.appVersion);
	this.isIE = (this.name == 'Microsoft Internet Explorer');
}

function rssfeed(label, url, img)
{
	this.label = label;
	this.url = url;
	this.img = img;
}

//Full URL to "loading" image. No need to config after this line!!
var gfeedfetcher_loading_image="modules/mod_camp26_special_ajaxrss/ajaxrss_inc/indicator.gif" 

google.load("feeds", "1") //Load Google Ajax Feed API (version 1)

function gfeedfetcher(divid, divClass, delay, linktarget)
{
	//link target of RSS entries
	this.linktarget = linktarget || ""; 
	
	//array holding lables for each RSS feed
	this.feedstructure = []; 

	//array holding combined RSS feeds' entries from Feed API (result.feed.entries)
	this.feeds = []; 
	
	//Default delay between msg change, in miliseconds.
	this.delay = parseInt( delay );

	this.aIndex = [];
	this.indexFeedToDiplay = -1;
	
	//number of feeds fetched
	this.feedsfetched = 0; 
	this.feedlimit = 5;
	this.nbentriesperpage = 3;
	this.lastindex = -1;
	this.nbmax = 0;

	//Optional components of RSS entry to show (none by default)
	this.showoptions = ""; 

	//sort by "date" by default
	this.sortstring = "date"; 

	//output div to contain RSS entries
	if (!this.submenuonly)
	{
		this.feedcontainer = document.getElementById( divid + '_content' );
	}
	//default element wrapping around each RSS entry item
	this.itemcontainer = "<li>";
	
	this.rssoutput = "";
	this.buffer = "";
	this.divid = divid;
	this.mouseoverBol = 0;
	this.submenuonly = false;
}

gfeedfetcher.prototype.addFeed = function(label, url, img)
{
	this.feedstructure[this.feedstructure.length] = new rssfeed(label, url, img);
}

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.setSubMenuOnly = function()
{
	this.submenuonly = true;
}

gfeedfetcher.prototype.setentrycontainer = function( containerstr )
{  //set element that should wrap around each RSS entry item
	this.itemcontainer = "<" + containerstr.toLowerCase() + ">";
}

gfeedfetcher.prototype.entries_per_page = function( nbentriesperpage )
{
	this.nbentriesperpage = nbentriesperpage;
}

gfeedfetcher.prototype.init = function()
{
	this.indexFeedToDiplay = 0;
	this.rssoutput = "";
	
	if (!this.submenuonly)
	{
		this.feedcontainer.innerHTML = '<div class="centerdiv">' + 
										'<img src="' + gfeedfetcher_loading_image + '" align="absmiddle"/>' +
										'Loading RSS feed(s)' +
										'</div>';
	}

	this._loadFeeds();
}

gfeedfetcher.prototype._reload = function()
{
	var feedfetcherinstance = this;

	if (this.nbmax != 1)
	{
		if (this.indexFeedToDiplay > this.feedlimit)
		{
			this.indexFeedToDiplay = 0;
		}
		else
		{

			this.indexFeedToDiplay += 1;
		}
	}
	
	this.rssoutput = "";
	
	this._loadFeeds();
}


gfeedfetcher.prototype._loadFeeds = function()
{
	this.feedsfetched = 0; //reset number of feeds fetched to 0 (in case init() is called more than once)
	this.feeds = [];
	var displayer = this;
	
	// determines the three indexes into the feeds	
	this.aIndex = [];
	
	this.nbmax = ( this.feedstructure.length < this.nbentriesperpage + 1 ) ? this.feedstructure.length : this.nbentriesperpage;
	
	var newindex = this.lastindex;

	while (this.aIndex.length < this.nbmax) 
	{
		newindex += 1;
		if (newindex >= this.feedstructure.length) newindex = 0;
		this.aIndex[this.aIndex.length] = newindex;
	}

	this.lastindex = newindex;
	
	for(counter = 0; counter < this.aIndex.length; counter++)
	{
		var feedpointer = new google.feeds.Feed(this.feedstructure[this.aIndex[counter]].url);
		feedpointer.setNumEntries( this.feedlimit ); 
		
		//call Feed.load() to retrieve and output RSS feed
		feedpointer.load( function(r)
						  { 
						  	displayer._fetch_data_as_array(r)
						   }
						  ); 
	}
	feedfetcherinstance = this;
	
	setTimeout(function(){feedfetcherinstance._reload();},this.delay);
}


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 + "</span>"
}

gfeedfetcher._sortarray = function(arr, sortstr)
{
	//change "label" string (if entered) to "ddlabel" instead, for internal use
	var sortstr = (sortstr == "label") ? "ddlabel" : sortstr; 

	//sort array by "title" or "ddlabel" property of RSS feed entries[]
	if ( sortstr == "title" || sortstr == "ddlabel" ) 
	{ 
		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 )
{
	//get all feed entries as a JSON array or "" if failed
	var thisfeed = (!result.error) ? result.feed.entries : "";
	
	//if error has occured fetching feed
	if (thisfeed == "") 
		alert("Google Feed API Error: " + result.error.message)

	//For each entry within feed
	for (var i = 0 ; i < thisfeed.length; i++) 
	{
		//extend it with a "ddlabel" property
		result.feed.entries[i].ddlabel = this.feedstructure[this.aIndex[this.feedsfetched]].label;
		
		
		
		result.feed.entries[i].ddimg = this.feedstructure[this.aIndex[this.feedsfetched]].img;
	}

	this.feeds = thisfeed; 

	//signal the retrieval of this feed as complete (and move on to next one if defined)
	this._signaldownloadcomplete() 
}

gfeedfetcher.prototype._signaldownloadcomplete = function() 
{
	this.feedsfetched += 1;
	
	// builds the result into the buffer
	this._buildresult( this.feeds );

	//if all feeds fetched
	limit = (this.nbentriesperpage > this.nbmax) ? this.nbmax : this.nbentriesperpage;

	if (this.feedsfetched == limit) 
	{
		//displays results
		this._displayresult(); 
	}
}


gfeedfetcher.prototype._buildresult = function(feeds)
{
	gfeedfetcher._sortarray(feeds, this.sortstring);
	
	if (this.nbmax != 1)
	{
		var indexFeed = parseInt(this.indexFeedToDiplay);
		
		if (indexFeed > feeds.length -1)
			indexFeed = 0;
		
		this._buildcoreresult(indexFeed, feeds);
	}
	else
	{

		var indexFeed = parseInt(this.indexFeedToDiplay);
		var flag = false;
		
		for (counteritem = 0; counteritem < this.nbentriesperpage; counteritem++)
		{
			if (indexFeed > feeds.length - 1)
			{
				this.indexFeedToDiplay = 0;
				indexFeed = 0;
			}
			this._buildcoreresult(indexFeed, feeds);
	
			if ( !flag )
				indexFeed++;
			else
				flag = false;
		}
		
		this.indexFeedToDiplay  = indexFeed;
	}
}
	
gfeedfetcher.prototype._buildcoreresult	= function(indexFeed, feeds)
{
	var nbmaxchartitle = 50;
	var clientBrowser = new myBrowser();
	
	var itemtitle =	"<a href=\"" + feeds[indexFeed].link + 
						"\" target=\"" + this.linktarget + 
						"\" class=\"echangez\" title=\"" + feeds[indexFeed].title + "\">";

	if (feeds[indexFeed].title.length > nbmaxchartitle)
	{
		itemtitle += feeds[indexFeed].title.substring(0,50) + "...</a>";
	}
	else
	{
		itemtitle += feeds[indexFeed].title + "</a>";
	}
	
	var itemlabel = "";
	if (this.showoptions.indexOf("label") > -1)
	{
		itemlabel = '<span class="labelfield">[' + feeds[indexFeed].ddlabel + ']</span>';
	}
	
	var itemdescription = "";
	if (this.showoptions.indexOf("description") > -1)
	{
		itemdescription = feeds[indexFeed].content;
	}
	else
	{
		if 	(this.showoptions.indexOf("snippet") > -1) 
		{
			itemdescription = feeds[indexFeed].contentSnippet;
		}
	}
	
	var styleoverride = "";
	if (feeds[indexFeed].ddimg != "" && feeds[indexFeed].ddimg != "undefined" )
	{
		if (clientBrowser.isIE && clientBrowser.version <= 6 && feeds[indexFeed].ddimg.indexOf(".png") > -1) 
		{
			styleoverride = " style=\"background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + feeds[indexFeed].ddimg + "', sizingMethod='crop');\"";
		}
		else
		{
			styleoverride = " style=\"background: url('" + feeds[indexFeed].ddimg + "') left center no-repeat;\"";
		}
	}

	this.rssoutput +=  "<li" +
						styleoverride +
						"><div class=\"contentechangezwrapper\"><div class=\"contentechangezitem\">" + 
						itemtitle + " " + 
						itemlabel + " " + 
						"<p>" + 
						itemdescription + 
						"</p></div></div></li>";
}

gfeedfetcher.prototype._displayresult = function()
{
	if (!this.submenuonly)
	{
		this.feedcontainer.innerHTML = "<ul>" + this.rssoutput + "</ul>";
	}
	
	submenucontent = document.getElementById('feedsrecipient');
	if (submenucontent != null)
	{
		submenucontent.innerHTML = "<ul>" + this.rssoutput + "</ul>";
	}
}

