window.addEvent('domready',initializePage);

/* stop flipping news */
var no_flipping = false;
var newsTimer;
var lastId;

function initializePage() {
	/* create the navigatio menu */
	var myMenu = new MenuMatic();  
	
	/* if we are at the home page */
	if($('news')) {
		/* show the first news */
		showNews(1);
		
		/* not working yet */
		/*initializeNews();*/
		
		$('c_pause').addEvent('click', function(){
		clearTimeout(newsTimer);
		});
		
		$('c_play').addEvent('click', function(){
			showNews(lastId);
		});
		
		$('c_previous').addEvent('click', function(){
			clearTimeout(newsTimer);
			showNews(lastId-1);
		});
		
		$('c_next').addEvent('click', function(){
			clearTimeout(newsTimer);
			showNews(lastId+1);
		});

		
	}
	
}

function initializeNews() {
	var newsList;
	new Request.JSON({
		'url'		:'/news/',
		'onComplete':function(newsList){
			flipNews(newsList);
		}
	}).post({'id':'list'})
}

function flipNews(newsList) {
	/*
	if(!no_flipping) {
		newsList.each(function(id_news,count){
			if(count == (newsList.length -1)) {
				flipNews(newsList);
			}
		});
	}
	*/
}

function showNews(id) {
	var maxId = 19;
	
	if(id < 0) id = 0;
	id = id%maxId;
	lastId = id;

	$$('#news_navigator a').each(function(aLink){
		aLink.erase('class');
	});
	
	new Request.JSON({
		'url'		:'/news/',
		'onComplete':function(result){
			$('news_title').innerHTML 	= result['title'];
			$('news_content').innerHTML = result['extract'];
			$('news_link').set('href',result['page_url']);
			$('news').setStyle('background-image','url("/img/actualites/'+result['id']+'.jpg")');
			$('link_'+result['id']).addClass('active');
		}
	}).post({'id':id})
	
	var nextNews = function() { showNews(id + 1); };
	newsTimer = nextNews.delay(5000);
}
