// -------------------------------------------------------------------
// gAjax RSS Feeds Displayer- By Dynamic Drive, available at: http://www.dynamicdrive.com
// Created: July 17th, 2007 Updated: n/a
// -------------------------------------------------------------------
// Adapted from http://blogshaman.awardspace.com/webs/feeds/gfeedfetcher.js
// Changes (DY, 2010-03-28):
// FIXED: display of first feed when have only 1 feed per page
// ADDED: separated page links into new paragraph class
// ADDED: objname parameter to constructor to identify the object for loding
// CHANGED: changes pages through arrow buttons rather than specific page numbers
// ADDED: automatic page rotator based on gajaxticker.js

var gfeedfetcher_loading_image="indicator.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(objname, divid, divClass, linktarget, pagshow, delay){
	this.objname = objname; // added object name for reference from javascript command
	this.linktarget=linktarget || "" //link target of RSS entries
	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 // total number of feeds
	this.pagshow=pagshow-1 // number of feeds per page
	this.totpages = 0;
	this.currpage = 0;
	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
	this.delay=parseInt(delay) //Default delay between msg change, in miliseconds.
	this.mouseovercontainer = 0;
}

// DEPRECATED
function mostrardiv(num,tot) {
for (var i=1; i<tot; i++){
var midiv = document.getElementById("feed"+i);
if (i!=num){midiv.style.display = 'none';}else{midiv.style.display = 'block';}
}
}

// added function to change page in the given direction
gfeedfetcher.prototype.changepage=function(dir) {
	//console.log(this.currpage, this.totpages, this.currpage + dir);
	if (!(this.currpage + dir < 0 || this.currpage + dir >= this.totpages)) {
		this.currpage += dir;
		for (var i = 0; i < this.totpages; i++){
			var midiv = document.getElementById("feed"+i);
			if (i == this.currpage) {
				midiv.style.display = 'block';
			} else {
				midiv.style.display = 'none';
			}
		}
	}
}

gfeedfetcher.prototype.rotatepage=function() {
	var fetcher = this;
	if (this.mouseovercontainer == 1) {
		setTimeout(function() {fetcher.rotatepage()}, 100);
	} else {
		var jump = (this.currpage + 1 >= this.totpages) ? jump = -1 * this.currpage : 1;
		this.changepage(jump);
		setTimeout(function() {fetcher.rotatepage()}, this.delay);
	}
}

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='<img src="'+gfeedfetcher_loading_image+'" /> Retrieving RSS feed(s)'
	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(r){displayer._fetch_data_as_array(r)}) //call Feed.load() to retrieve and output RSS feed
	}
	this.feedcontainer.onmouseover = function() { displayer.mouseovercontainer = 1 };
	this.feedcontainer.onmouseout = function() { displayer.mouseovercontainer = 0 };
	if (window.attachEvent) //Clean up loose references in IE
		window.attachEvent(
			"onunload", 
			function(){
				displayer.feedcontainer.onmouseover = displayer.feedcontainer.onmouseout = null;
			}
		);
	setTimeout(function() { displayer.rotatepage() }, 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){
	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){
	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("Google Feed API Error: "+result.error.message)
	for (var i=0; i<thisfeed.length; i++) //For each entry within feed
		result.feed.entries[i].ddlabel=this.feedlabels[this.feedsfetched] //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 ic=0; //Lleva la cuenta individual de los feeds
	var ic2=0; // changed to 0-based indexing
	var rssoutput=(this.itemcontainer=="<li>")? "<ul>\n" : ""
	gfeedfetcher._sortarray(feeds, this.sortstring)
	for (var i=0; i<feeds.length; i++){
		// now displays the first page when only one feed per page is given
		var itempagshow = "";
		if (ic==this.pagshow){
			itempagshow = (i == 0) 
				? "</div><div id='feed"+ic2+"' style='display:block;'>" 
				: "</div><div id='feed"+ic2+"' style='display:none;'>"; 
			ic=0; 
			ic2++;
		} else {
			ic++;
		}
//	if (i==0){itempagshow = "<div id='feed"+ic2+"' style='display:block;'>"; ic=0; ic2++;}
		var itemtitle="<a href=\"" + feeds[i].link + "\" target=\"" + this.linktarget + "\" class=\"titlefield\">" + 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 itemdescription=/description/i.test(this.showoptions)? "<br />"+feeds[i].content : /snippet/i.test(this.showoptions)? "<br />"+feeds[i].contentSnippet  : ""
		rssoutput+=itempagshow + this.itemcontainer + itemtitle + " " + itemlabel + " " + itemdate + "\n" + itemdescription + this.itemcontainer.replace("<", "</") + "\n\n"
		if (i+1==feeds.length){rssoutput+="</div>";}
	}
	this.totpages = ic2;
	rssoutput+=(this.itemcontainer=="<li>")? "</ul>" : "";
	// added separate paragraph and paragraph class
	var htmloutput="<p class='feedpages'>";
	// changed page number display to up and down button
	htmloutput+='<a href="javascript:' + this.objname + '.changepage(-1);" class="feedpag">&lt;</a>&nbsp;&nbsp;';
	htmloutput+='<a href="javascript:' + this.objname + '.changepage(1);" class="feedpag">&gt;</a>';
	/*
	for (var i=1; i<ic2; i++){	
	htmloutput+='<a href="javascript:mostrardiv('+i+','+ic2+');" class="feedpag">'+i+'</a>';
	}
	*/
	rssoutput+=htmloutput+"</p>";
	this.feedcontainer.innerHTML=rssoutput;
}
