/**
 * Plugin: jquery.zRSSFeed
 * 
 * Version: 1.0.1
 * (c) Copyright 2010, Zazar Ltd
 * 
 * Description: jQuery plugin for display of RSS feeds via Google Feed API
 *              (Based on original plugin jGFeed by jQuery HowTo)
 * 
 * History:
 * 1.0.1 - Corrected issue with multiple instances
 *
 **/

(function($){

	var current = null; 
	
	$.fn.rssfeed = function(url, options) {	
	
		// Set pluign defaults
		var defaults = {
			limit: 10,
			header: false,
			banniere: false,
			titletag: 'h2',
			groupByYear: false,
			date: true,
			datevalue: false,
			content: true,
			snippet: true,
			showerror: true,
			errormsg: '',
			inblank: true,
			apisite: null,
			key: null
		};  
		var options = $.extend(defaults, options); 
		
		// Functions
		return this.each(function(i, e) {
			var $e = $(e);
			
			// Add feed class to user div
			if (!$e.hasClass('rssFeed')) $e.addClass('rssFeed');
			
			// Check for valid url
			if(url == null) return false;

			// Create Adomos Feed API address
			var api = "/cgi-bin/feedloader.cgi?v=1.0&callback=?&q=" + url;
			if (options.apisite != null) api = options.apisite + api;
			if (options.limit != null) api += "&num=" + options.limit;
			if (options.key != null) api += "&key=" + options.key;

			// Send request
			$.getJSON(api, function(data){
				
				// Check for error
				if (data.responseStatus == 200) {
	
					// Process the feeds
					_callback(e, data.responseData.feed, options);
				} else {

					// Handle error if required
					if (options.showerror)
						if (options.errormsg != '') {
							var msg = options.errormsg;
						} else {
							var msg = data.responseDetails;
						};
						$(e).html('<div class="rssError"><p>'+ msg +'</p></div>');
				};
			});				
		});
	};
	
	// Used for sorting the rss feed by year
	// The result will be a double array, containing the year
	// in the first dimension and the pertinent data in the second dimension
	function resort_data_by_year( entries ){
		// get the array size
		var nArrayLength = entries.length;
		
		// initialising the result as an empty Array
		var aResult = new Array();
	
		// go through the whole feed one by one
		for(var nIndex=0; nIndex < nArrayLength; nIndex++){
			// get one feed
			var entry = entries[ nIndex ];
			
			// retrieve the feed's year through its date
			var entryDate = new Date(entry.publishedDate);
			var nYear = entryDate.getFullYear();
			
			// if year key is not present in aResult then
			// create it and assing it a empty array
			if( !( nYear in aResult ) ){
				aResult[ nYear ] = new Array();
			}
			
			// push the current entry in its year queue
			aResult[ nYear ].push( entry );
			
		}

		
		return aResult;
	}
	
	function group_data( entries ){
		// get the array size
		var nArrayLength = entries.length;
		
		// initialising the result as an empty Array
		var aResult = new Array();
		var nYear = (new Date).getFullYear();
		aResult[ nYear ] = new Array();
	
		// go through the whole feed one by one
		for(var nIndex=0; nIndex < nArrayLength; nIndex++){
			// get one feed
			var entry = entries[ nIndex ];
									
			// push the current entry in its year queue
			aResult[ nYear ].push( entry );
		}
		return aResult;
	}
	
	// Callback function to create HTML result
	var _callback = function(e, feeds, options) {
		var weekday = new Array('Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi');
		var month_extensive = new Array('Janvier','Fevrier','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre');
	
		if (!feeds) {
			return false;
		}
		var html = '';	
		var row = 'odd';	
		
		// Add header if required
		if (options.header)
			html +=	'<div class="rssHeader">' +
				'<a href="'+feeds.link+'" title="'+ feeds.description +'">'+ feeds.title +'</a>' +
				'</div>';
			
		// Add body
		// html += '<div class="rssBody">' + '<ul class="ulBoursePresse">';
	//$('#infofi_com_presse').add($('#infofi_evenementiel_1'));
	//var old = $('#infofi_com_presse').html();
	//$('#infofi_com_presse').html('<div id="infofi_evenementiel_1" style=" background-image:url(/images/infofi_evenementiel_1.png); height:89px; width:610px;"></div>'+old);
	
		html += '<div class="rssBody">\n';
		if (options.banniere != false) {
			html += '<a href="http://adomos.com/infofi/pdf/Adomos_augmentation-de-capital-du-18-au-31-01-2012.pdf" target="_blank" id="infofi_evenementiel_1" style="background-image:url(/images/infofi_evenementiel_1.png); height:89px; width:610px; margin-bottom:15px; display:block;"></a>\n';
		}
		
		var aSortedFeed = new Array();
		if (options.groupByYear)
		{
			aSortedFeed = resort_data_by_year(feeds.entries);
		}
		else {
			aSortedFeed = group_data(feeds.entries);
		}		

		//var report = "";
		var anneeCourante = (new Date).getFullYear();
		//alert ("annee courante: " + anneeCourante);
		while (!(anneeCourante in aSortedFeed))
		{
			//report += "aucun element pour l'annee: " + anneeCourante + "\n";
			anneeCourante = anneeCourante - 1;
		}
		for( var nYear in aSortedFeed ){
				//report += "annee: " + nYear + " -- " + aSortedFeed[ nYear ].length + " articles\n";
				var szTab = "tab_" + nYear;
		
				var disStyle = "none"; 
				if (nYear == anneeCourante) {
						disStyle = "block";
				}
				
				html += '<ul id="' + szTab + '" class="ulBoursePresse" style="display:' + disStyle + ';">\n';
			
			
			var nYearLength = aSortedFeed[ nYear ].length;
			for( var nIndex=0; nIndex < nYearLength; nIndex++ ){
				var entry = aSortedFeed[ nYear ][ nIndex ]; 
				var entryDate = new Date(entry.publishedDate);
				
				// Add feed row
				html += '<li class="rssRow '+row+'">' + 
					'<'+ options.titletag +'><a href="'+ entry.link +'" title="Voir ce flux '+ feeds.title +'"' +
					(options.inblank ? ' target="_blank"' : '') + '>' + entry.title +'</a></'+ options.titletag +'>'
				
				if (options.content) {
				
					// Use feed snippet if available and optioned
					if (options.snippet && entry.contentSnippet != '') {
						var content = entry.contentSnippet;
					} else {
						var content = entry.content;
					}
					
					html += '<p>'+ content +'</p>'
				}
				
				if (options.date){
					html += '<div class="rssDate">'	+ 
							'Date de publication : ' +
							weekday[ entryDate.getDay() ] + " " +
							entryDate.getDate() + " " +
							month_extensive[ entryDate.getMonth() ] + " " +
							entryDate.getFullYear() +'</div>';
				}	
				if (options.datevalue){
					html += '<div class="rssDate">'	+ 
							weekday[ entryDate.getDay() ] + " " +
							entryDate.getDate() + " " +
							month_extensive[ entryDate.getMonth() ] + " " +
							entryDate.getFullYear() +'</div>';
				}	
				html += '</li>';
				
				// Alternate row classes
				if (row == 'odd') {
					row = 'even';
				} else {
					row = 'odd';
				}						
			
			
			}
			
			html += '</ul>\n';
		}
		//alert (report);
		

		
		$(e).html(html);
	};
})(jQuery);


