// -------------------------------------------------------------------
// gAjax RSS Feeds Displayer- By Dynamic Drive, available at: http://www.dynamicdrive.com
// Created: July 17th, 2007
// Updated June 14th, 10': Fixed issue in IE where labels would sometimes be associated with the incorrect feed items
// -------------------------------------------------------------------

var gfeedfetcher_loading_image="/common/xsl/b2c/promoexpo/rss/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(divid, divClass, linktarget){
	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
	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="" //default element wrapping around each RSS entry item
}

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(typedata){
	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 + '" align="absmiddle" style="padding-left:10px;padding-bottom:5px;"/> Veuillez patienter...'
	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, typedata)
			}
		}(this.feedlabels[i])) //call Feed.load() to retrieve and output RSS feed.
	}
}


gfeedfetcher._formatdate = function(datestr, showoptions) {
    var itemdate = new Date(datestr)
    var day = (itemdate.getDate()).toString();
    if (day.length == 1) day = '0' + day;
    var month = (itemdate.getMonth() + 1).toString();
    if (month.length == 1) month = '0' + month;
    var year = itemdate.getFullYear();
    return "<span>" + day + "/" + month + "</span>" + year;
}
gfeedfetcher._formatdatefull = function(datestr, showoptions) {
var itemdatefull = new Date(datestr)
    return itemdatefull.toLocaleDateString();
}

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, typedata) {	
	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("Some blog posts could not be loaded: "+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(typedata) //signal the retrieval of this feed as complete (and move on to next one if defined)
}

gfeedfetcher.prototype._signaldownloadcomplete = function(typedata) {
	this.feedsfetched+=1
	if (this.feedsfetched==this.feedurls.length) //if all feeds fetched
	    this._displayresult(this.feeds, typedata) //display results
}

gfeedfetcher.prototype._displayresult = function(feeds, typedata) {
    var rssoutput = (this.itemcontainer == "<li>") ? "<ul>\n" : ""
    gfeedfetcher._sortarray(feeds, this.sortstring)
    for (var i = 0; i < feeds.length; i++) {
        var itemdate = gfeedfetcher._formatdate(feeds[i].publishedDate, this.showoptions)
        var itemdatefull = gfeedfetcher._formatdatefull(feeds[i].publishedDate, this.showoptions)
        var link = feeds[i].link;
        if (link.indexOf('.html') > -1) link = link.substring(0, link.indexOf('.html'));
        var idnews = link.substring(link.lastIndexOf('-') + 1);
        var newstitle = cleanurl(feeds[i].title);
        var urlDet = urlroot + "/" + newstitle + "-" + idnews;
        var urlTitle = (feeds[i].title).replace(/["]/gi, "&#34;");
        if (codenews != '') {
            var itemdescription = /description/i.test(this.showoptions) ? "<br />" + feeds[i].content : /snippet/i.test(this.showoptions) ? "<br />" + feeds[i].contentSnippet : ""
            if ((itemdescription.substring(itemdescription.indexOf('>') + 1)).indexOf('<') == 0) itemdescription = '<em>Prévisualisation de la news non disponible</em>';
            var item = itemdescription + "<br/><br/><a class=\"newsDetailsExterne\" target=\"_blank\" href=\"" + feeds[i].link + "\" title=\"" + urlTitle + "\">Lire la suite</a>"
            if (idnews == codenews) {
                if (typedata == 'titleOnly') rssoutput += feeds[i].title;
                else if (typedata == 'dateOnly') rssoutput += itemdatefull;
                else rssoutput += item;
            }
        }
        else {
            var item = "<p class=\"date\">" + itemdate + "</p><p class=\"article\"><a href=\"" + urlDet + "\" title=\"" + urlTitle + "\">" + feeds[i].title + "</a></p>"
            rssoutput += this.itemcontainer + item + this.itemcontainer.replace("<", "</") + "<div class=\"sep\">&#160;</div>";
        }
    }
    this.feedcontainer.innerHTML = rssoutput
}

function cleanurl(text) {
    temp = text.replace(/[àâä]/gi, "a")
    temp = temp.replace(/[éèêë]/gi, "e")
    temp = temp.replace(/[îï]/gi, "i")
    temp = temp.replace(/[ôö]/gi, "o")
    temp = temp.replace(/[ùûü]/gi, "u")
    temp = temp.replace(/[ '´’().,":??!–]/gi, "-")
    var xxx = "---";
    var xx = "--";
    temp = temp.replace(xxx, "-")
    temp = temp.replace(xx, "-")
    if (temp.indexOf('-') == 0) temp = temp.substring(1);
    if (temp.lastIndexOf('-') + 1 == temp.length) temp = temp.substring(0, temp.lastIndexOf('-'));
    return temp.toLowerCase();
}

