/*
$Revision:                 $
$Date:                     $
*/




String.implement({
	trim: function(charlist){
		var str = this;
		str = str.rtrim(charlist);
		str = str.ltrim(charlist);
		return str;
	},
	rtrim: function(charlist){
		charlist = !charlist ? ' \s\xA0' : (charlist+'').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\$1');
		var re = new RegExp('[' + charlist + ']+$', 'g');
		return (this+'').replace(re, '');
	},
	ltrim: function(charlist){
	    charlist = !charlist ? ' \s\xA0' : (charlist+'').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\$1');
	    var re = new RegExp('^[' + charlist + ']+', 'g');
	    return (this+'').replace(re, '');
	}
});




/**
 * FeedReader
 *
 * lecteur RSS (et prochainement ATOM)
 * inspiré du "Rss Reader" inclus dans "Moodgets library" (www.moodgets.com)
 */

var FeedReader = new Class({
	Implements: [Events, Options],
	options: {
		url: null,
		data: null,
		method: 'post',
		scrollOffset: 1,
		scrollDelay: 60,
		stopScroll: false,
		showHeader: true,
		expandRowOnLoad: false,
		topBar: null,
		bottomBar: null
	},
	classes: {
		element: 'feedReader',
		headerContainer: 'feedReaderHeader',
		headerElement: 'feedReaderHeaderBox',
		bodyElement: 'feedReaderBody',
		bodyTreeElement: 'feedReaderBodyTree',
		rowHeader: 'feedReaderRowTitle',
		rowTool: 'feedReaderRowTool',
		rowDescription: 'feedReaderRowDescription'
	},
	
	element: null,
	headerElement: null,
	bodyElement: null,
	bodyTreeElement: null,
	
	headerHeight: 0,
	topBarHeight: 0,
	bottomBarHeight: 0,
	bodyHeight: 0,
	
	
	initialize: function(p_parent, p_options) {
		p_parent = $(p_parent);
		
    	this.element = new Element('div')
 		.addClass( this.classes.element )
		.setStyle('height', p_parent.getHeight())
		.setStyle('width', p_parent.getWidth());
   	
		if(p_parent)
			this.element.inject(p_parent);
		
		this.setOptions(p_options);
		
		this.createReader();
 	},
	
	createReader: function() {	
		this.fireEvent('beforeHeaderCreation');			
		
		//************************* Elements height initialization *****************		
		if ($chk(this.options.topBar))
			this.topBarHeight = 26; // toolbar height 25px + 1px bottom border
		
		if ($chk(this.options.bottomBar))
			this.bottomBarHeight = 26; // pagination toolbar height 25px + 1px bottom border
	
		// *********************** Header initialization **************************	
		var l_headerContainer = new Element('div')
		.addClass( this.classes.headerContainer )
		.inject(this.element);
		
		this.headerElement = new Element('div')
		.set('html', '&nbsp;')
		.addClass( this.classes.headerElement )
		.setStyle('width', '100%')
		.inject(l_headerContainer);
		
		if (!this.options.showHeader){
			this.headerHeight = 0;
			l_headerContainer.setStyle('display', 'none');
		}else{
			this.headerHeight = 24;
		}				
		
		// ************************* Body *****************************************	
		this.fireEvent('beforeBodyCreation', this);	
		this.bodyHeight = this.element.getHeight().toInt() - this.headerHeight-this.topBarHeight-this.bottomBarHeight;  	
		
		this.bodyElement = new Element('div')
		.addClass( this.classes.bodyElement )
		.setStyle('width', '100%')
		.setStyle('height', this.bodyHeight)
		.inject(this.element);
		
		this.fireEvent('bodyCreation', this.bodyElement);
		
		this.loadData();
	},
	
	loadData: function() {
		if ($chk(this.options.url)){
			this.bodyElement.addClass('loading');
			new Request({
				url: this.options.url,
				data: this.options.data,
				method: this.options.method,
				onFailure:  this.onFailure.bind(this),
				onSuccess: this.onSuccess.bind(this)
			}).send();
		}
	},
	
	renderData: function(p_rssTree) {
		this.fireEvent('beforeRenderData', this.bodyElement);
		
		var l_channels = p_rssTree.getElementsByTagName('channel');
		if ($chk(l_channels)&&(l_channels.length > 0))
		{ 
			var l_channel = l_channels[0];
			this.headerElement.set('text', l_channel.getElementsByTagName('title')[0].firstChild.nodeValue.trim() );
			
			var l_items = l_channel.getElementsByTagName('item');		
			this.bodyTreeElement = this.bodyElement.getElement('ul');			
			if ($chk(this.bodyTreeElement))
			{
				this.bodyTreeElement.empty();
			}
			else
			{
				this.bodyTreeElement = new Element('ul')
				.addClass( this.classes.bodyTreeElement )
				.setStyle('width', '100%')
				.setStyle('top', this.bodyHeight)
				.inject(this.bodyElement);
			}
			
			for (var j=0; j<l_items.length; j++)
			{ 			
				var l_row = new Element('li')
				.setStyles('width', '100%');
				
				var l_rowHeader = new Element('div')
				.addClass( this.classes.rowHeader )
				.setStyle('width', '100%');
				
				var l_toolImg = new Element('div')
				.addClass( this.classes.rowTool )
				.setStyle('float', 'left')
				.setStyle('background-position','-18px 3px')
//				.addEvent('click', this.onRowToolClick.bind(this))
				.inject(l_rowHeader);
				
				var l_rowTitle = new Element('a', {
					'text': l_items[j].getElementsByTagName('title')[0].firstChild.nodeValue.trim(),
					'href': l_items[j].getElementsByTagName('link')[0].firstChild.nodeValue.trim(),
					'target': '_blank'
				});				
				l_rowTitle.inject(l_rowHeader);
				l_rowHeader.inject(l_row);
				
				var l_rowDescription = new Element('div')
				.addClass( this.classes.rowDescription )
				.addClass('hidden')
				.set('html', l_items[j].getElementsByTagName('description')[0].firstChild.nodeValue.trim() )
				.inject(l_row);
				
				if(this.options.expandRowOnLoad){
					l_rowDescription.toggleClass('hidden');
					l_toolImg.setStyle('background-position','0px 3px');
				}
				
				l_row.inject(this.bodyTreeElement);
//				.addEvent('mouseover', this.onRowMouseOver.bind(this) )
//				.addEvent('mouseout',  this.onRowMouseOut.bind(this) );
				
				this.fireEvent('newRow', l_row);	
			}
			
			this.bodyTreeElementHeight = this.bodyTreeElement.getStyle('height').toInt();
			this.rows = this.bodyTreeElement.getElements('li');
			this.fireEvent('renderData', this.bodyElement);
			this.lastScrollValue = ( this.bodyHeight / 2 ).toInt();
			this.scroll.periodical(this.options.scrollDelay, this); 
			
			
			// On mutliple par 3 pour être sur de ne pas se retourver avec du vide
			this.bodyTreeElement.clone().cloneEvents( this.bodyTreeElement )
			.setStyle('top', 0)
			.inject( this.bodyTreeElement.getParent() );
			
			this.bodyTreeElement.clone().cloneEvents( this.bodyTreeElement )
			.setStyle('top', 0)
			.inject( this.bodyTreeElement.getParent() );
			
			
			// Ajout des évènements sur les éléments
			this.bodyElement.getElements( '.'+this.classes.rowTool )
			.addEvent('click', this.onRowToolClick.bind(this));
			
			this.bodyElement.getElements( 'li' )
			.addEvent('mouseover', this.onRowMouseOver.bind(this) )
			.addEvent('mouseout',  this.onRowMouseOut.bind(this) );
			
			
			// Classe 'erow' sur 1 li sur 2
			var i=0;
			this.bodyElement.getElements( 'li' ).each(function(li) {
				if(i%2==0)
					li.addClass('erow');
				i++;
			});
		}
		else
		{
			this.bodyTreeElementHeight = 0;
			this.rows = [];		
			if(!$chk(this.dialog)){
//				this.dialog = new DialogBox(this);
			}
//			this.dialog.error(g_language.RssReader.invalidRssResultMsg);
		}					
	},
	
	scroll: function() {
		if (!this.stopScroll){
			if (this.lastScrollValue > -this.bodyTreeElementHeight){
				this.lastScrollValue = this.lastScrollValue - this.options.scrollOffset;
			}else{
//				this.lastScrollValue = this.bodyHeight;
				this.lastScrollValue = 0;
			}
			
			this.bodyElement.getElements('ul').setStyle('top', this.lastScrollValue + 'px');
		}
	},
	
	onSuccess: function(p_response) {
		var l_xmlDoc = null;
		try {//Internet Explorer 
			l_xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
			if (l_xmlDoc){
				l_xmlDoc.async="false";
				l_xmlDoc.loadXML(p_response);
			}
		} catch(e) {
			l_xmlDoc=new DOMParser().parseFromString(p_response,"text/xml");
		}
		this.bodyElement.removeClass('loading');
		this.renderData(l_xmlDoc);
	},
	
	onFailure: function() {
		this.bodyElement.removeClass('loading');				
		if(!$chk(this.dialog)){
//			this.dialog = new DialogBox(this);
		}
//		this.dialog.error(g_language.RssReader.loadFailureMsg);
	},
	
	onRowMouseOver: function(p_evt) {
		this.stopScroll = true;
		p_evt.target.getParent('li').addClass('over');
	},
	
	onRowMouseOut: function(p_evt) {
		this.stopScroll = false;
		p_evt.target.getParent('li').removeClass('over');
	},
	
	onRowToolClick: function(p_evt) {
		var li = p_evt.target.getParent('li');
		var pos = 0;
		var lis = [];
		
		pos = li.getAllPrevious('li').length;
		//while( li = li.getPrevious('li') )
		//	pos++;
		
		this.bodyElement.getElements('ul').each(function(ul) {
			lis.push( ul.getElements('li')[pos] );
		});
		
		lis.each(function(li) {
			var l_description = li.getElement( '.'+this.classes.rowDescription );
			
			if ($chk(l_description)){
				l_description.toggleClass('hidden');
				this.bodyTreeElementHeight = this.bodyTreeElement.getStyle('height').toInt();
				
				var l_toolImg = li.getElement( '.'+this.classes.rowTool );
				if ($chk(l_toolImg)){
					if (l_description.hasClass('hidden'))
						l_toolImg.setStyle('background-position','-18px 3px');
					else
						l_toolImg.setStyle('background-position','0px 3px');	
				}
			}
		}, this);
	}
});


