/*
 * News Highlighter v0.1b
 * By Zephia Digital Art
 */

var NewsHighlighter = new Class({
	Implements: Options,
	options: {
		content: 'nhl-content',
		btnNext: 'nhl-next',
		btnPrev: 'nhl-prev',
		jsonFileURL: 'news.json.php',
		moreURL: '/news-more.php',
		moreParamName: 'id',
		autoSlide: true,
		slideTime: 5
	},
	
	items: null,
	currentIndex: 0,
	
	initialize: function(options){
		this.setOptions(options);
		this.requestItems();
		
		$(this.options.btnNext).addEvent('click', this.next.bind(this));		
		$(this.options.btnPrev).addEvent('click', this.prev.bind(this));
	},
	
	requestItems: function(){
		var jsonItems = new Request.JSON({url: this.options.jsonFileURL, onSuccess: this.loadItems.bind(this)}).get();
	},
	
	loadItems: function(jsonObj){
		this.items = jsonObj.noticias;
		this.showNew(this.currentIndex);
		
		if(this.options.autoSlide){
			this.next.periodical(this.options.slideTime*1000, this);
		}
	},
	
	next: function(){
		if(this.currentIndex < this.items.length-1){
			this.currentIndex++;
		}
		else{
			this.currentIndex = 0;
		}
		this.showNew(this.currentIndex);
	},
	
	prev: function(){
		if(this.currentIndex > 0){
			this.currentIndex--;
		}
		else{
			this.currentIndex = this.items.length-1;
		}
		this.showNew(this.currentIndex);
	},
	
	showNew: function(index){		
		var currentItem = this.items[index];
		
		$(this.options.content).fade('hide');
		
		var item_a = new Element('a', {
		    'href': this.options.moreURL + '?' + this.options.moreParamName + '=' + currentItem.id,
		    'html': currentItem.titulo
		});
		
		$(this.options.content).set('html','');
		$(this.options.content).grab(item_a);
		
		$(this.options.content).fade('in');
	}
});
