/* Effet rollover et preload d'image  */
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

var pause=false;

window.addEvent('domready', onDomReady);


function onDomReady()
{

	if(checkAddress())
	{
	
		new Asset.images(
			['images/css/next-over.gif',
			'images/css/previous-over.gif',
			'images/css/newsletter-over_fr.gif',
			'images/css/radio-piknic-over_fr.png',
			'images/css/alert-meteo-over_fr.png' ]
		);
		openBloc();
		refreshInfoComplementaire();
		refreshBanner('big-box');
		modifyAjaxLinks($('body'));
		evaluateJavascriptDiv();
		accordeon();
flickr.init();
		//SWFAddress.addEventListener(SWFAddressEvent.CHANGE, onSWFAddressEvent);
		
	}

}

function checkAddress()
{	
	// SOIT a la racine => ajoute #/news/{articleid}
	// SOIT acces direct a une partie => reload ver #/part
	// SOIT accés # a une partie => load content
	/*if( root_url+'/' == location.href )
	{
		SWFAddress.setValue("news/" + $('content-nouvelle').getProperty('articleid'));
	}else{ 
		var pattern = /[a-zA-Z0-9][a-zA-Z0-9\/]+$/g;
 		// On enleve root_url du location.href
		var str = location.href.replace(root_url+"/", "");
		var part = str.match(pattern);
		// soit part commence par # soit non

		if(str.charAt(0) =='#' )
		{
			if(str.charAt(11)=="="){
				searchwords = str.substr(12);
				part ="index.php?mact=Search%2Ccntnt01%2Cdosearch%2C0&cntnt01returnid=57&cntnt01searchinput="+searchwords+"&submit=Envoyer";
			};
			loadContent( part, receiveData );
		}else{
			location.assign(root_url + "/#/" + part);
			return false;
		}
	}*/
	return true;
}

function evaluateJavascriptDiv()
{
	$$('div.javascript').each(
		function(item, index)
		{
			eval(item.getText());
		}
	);
}
function receiveData(data)
{	
	
	var all=new Element( 'div' ).setHTML(data);
	modifyAjaxLinks(all);
	
	var title = all.getElement('div[id=title]');	
	var menu = all.getElement('div[id=menu-principal]'); 
	var content = all.getElement('div[id=sidebar-left]');
	var oldmenu = $('menu-principal');
	var oldsidebar = $('sidebar-left');
			
	oldsidebar.replaceWith(content);
	oldmenu.replaceWith(menu);	
	evaluateJavascriptDiv();
	document.title = title.getText();
		
	refreshInfoComplementaire();	
	openBloc();
}

function loadContent( part, callback )
{
	var myAjax = new Ajax(
		root_url + "/" + part,
		{
			method: 'post',
			onComplete: callback
		}
	);
	
	$('sidebar-left').empty();
	$('container-info-complementaire').empty();
	myAjax.request();
}

var rechercheForm;
function recherche(form)
{
	
	rechercheForm = "index.php?mact=Search%2Ccntnt01%2Cdosearch%2C0&cntnt01returnid=57&cntnt01searchinput="+form;	
	form = form.toString();
	form = form.replace(/é/,"e");
	form = form.replace(/è/,"e");
	form = form.replace(/ê/,"e");
	form = form.replace(/ë/,"e");
	form = form.replace(/ö/,"o");
	form = form.replace(/ô/,"o");
	form = form.replace(/ï/,"i");
	form = form.replace(/î/,"i");
	form = form.replace(/à/,"à");
	
	/*location.assign(root_url + "/#/recherche=" + form);*/
	
	loadContent( rechercheForm, receiveData );

	return false;
}




function onSWFAddressEvent(event)
{
	switch( event.type ){		
		case SWFAddressEvent.CHANGE:
			loadContent( event.value, receiveData );
		break;		
	}
	
}
function modifyAjaxLinks(el)
{
	/*var links = el.getElements('a.ajax');	
	links.each(
		function(item,index){
			item.setProperty(
				"href",
				item.getProperty('href').replace(root_url, root_url + "/#")
			);
		}
	);*/
}

function refreshBanner(id)
{
	var bloc = $(id);
	var a=bloc.getElement('a');
	var img=a.getElement('img');
	var newbloc = new Element('div');
	newbloc.setProperty('id', 'swfBanner');
	var params={ width:img.getProperty('width'), height:img.getProperty('height') };
	var attributes= {id:'swfBanner',name:'swfBanner'};	
	a.replaceWith(newbloc);
	swfobject.embedSWF(root_url + "/"+img.getProperty('src'), 'swfBanner', params.width, params.height, "9.0.0", root_url+"/swf/expressInstall.swf",	{}, params,	attributes);	
}

function scrollToElement( id )
{
	var scroll = new Fx.Scroll(window);
	scroll.toElement( $(id) );
}

function refreshInfoComplementaire()
{
	var info = $('info-complementaire');
	if(info!=null)
	{
		var container = $('container-info-complementaire');
		if(container!=null)
		{
			container.empty();
			container.adopt(info);
		}
	}
}

function loadPage(page, time)
{		
	var url = root_url+"/news/"+page+"/"+time+"/";

	var myAjax = new Ajax(
		url,
		{
			method: 'post',
			onComplete: function(data)
				{
					var obj = Json.evaluate(data);
					receiveNews( new Element('div').setHTML(obj.news) );
				}
		}
	);
	myAjax.request();
}

function receiveNews( news )
{	
	modifyAjaxLinks(news);
	if(news.getFirst() != null)
	{	
		var bloc = $('bloc-news');
		var first = bloc.getFirst();
		var nb = news.childNodes.length;
		var slide;
		if( first.getProperty('time').toInt() > news.getFirst().getProperty('time').toInt() )
		{			
			bloc.setStyle('left', - nb * 143 );
			news.getChildren().injectBefore( bloc.getFirst() );
			openBloc();
			slide = new Fx.Style(
				'bloc-news',
				'left',
				{
					duration:500,
					transition: Fx.Transitions.Quad.easeInOut,
						onComplete: function( el )
						{
							while( el.childNodes.length > 6 )
								el.getLast().remove();
							onSlideComplete();
						}
				}
			);
			slide.start(0);
		}else{
			bloc.setStyle('left', 0)
			while( news.getFirst() != null )
				news.getFirst().injectAfter( bloc.getLast() );
			openBloc();
			slide = new Fx.Style(
				'bloc-news',
				'left',
				{
					duration:500,
					transition: Fx.Transitions.Quad.easeInOut,
						onComplete: function( el )
						{			
							while( el.childNodes.length > 6 )
								el.getFirst().remove();
							el.setStyle('left', 0);			
							onSlideComplete();			
						}
				}
			);			
			slide.start( -nb * 143 );
		}
	}else
		pause = false;	
}

function onSlideComplete()
{
	Cookie.set('time', $('bloc-news').getFirst().getProperty('time'), {duration: 0, path:"/"});	
	pause = false;		
}

function clickPrev()
{
	if(!pause)
	{
		pause = true;
		loadPage(-1, $('bloc-news').getFirst().getProperty('time'));
	}
}

function clickNext()
{
	if(!pause)
	{
		pause = true;	
		loadPage(1,$('bloc-news').getLast().getProperty('time'));
	}	
}

function getBloc(blocId)
{
	return $$('div.bloc-sommaire[sommaireid='+blocId+']');
}

function openBloc()
{
	var content = $('content-nouvelle');
	if(content!=null)
	{
		var id = content.getProperty('articleid');
		select(id);
	}else{
		select(-1);
	}
}

var marginOver = 0;
var marginOut = 37;
var marginSelected = 20;

function select(blocId)
{
	var bloc = $$('.selected-bloc')[0];
	if(bloc != null)
		effectRoll(
			bloc,
			marginOut,
			function(el){
				var bloc = getBloc(el.getProperty('sommaireid'));
				bloc.addClass( 'unselected-bloc' );
				bloc.removeClass( 'selected-bloc' );
			}
		);	
	
	blocs = getBloc(blocId);
	blocs.each(
		function(bloc, index)
		{
			bloc.addClass( 'selected-bloc' );
			bloc.removeClass( 'unselected-bloc' );
			effectRoll(
				bloc,
				marginSelected,
				function(){}
			);
		}
	);
}

function click(blocId)
{
	select(blocId);	
}

function rollout(blocId)
{
	var blocs = getBloc(blocId);
	blocs.each(
		function (bloc, index)
		{
			if(bloc.hasClass('unselected-bloc'))
			{
				effectRoll(bloc, 37,function(el){});	
			}
		}		
	)
}
function rollover(blocId)
{
	var blocs = getBloc(blocId);
	blocs.each(
		function (bloc, index)
		{
			if(bloc.hasClass('unselected-bloc'))
			{
				effectRoll(bloc, 0,function(el){});		
			}
		}
	);
}

var effects = new Hash();
function removeEffect(id)
{ 
	if( effects.hasKey( id ) )
	{
		var effect = effects.get(id);		
		effect.stop();
		effects.remove(id);
	}
}
function effectRoll( bloc, value, callback )
{
	var hashid = bloc.getProperty('hashid');
	if(hashid==null)
	{
		hashid = $time();
		bloc.setProperty( 'hashid', hashid );
	}
	removeEffect(hashid);
	var effect = new Fx.Style(
		bloc.getElement('div[name=infos]'),
		'margin-top',
		{
			duration:250,
			transition: Fx.Transitions.Quad.easeOut,
			fps:50,
			onComplete:callback
		}
	);
	effect.start( value );
	effects.set( hashid, effect );	
}

function embedPictoBrowser( divId, flashvars, params )
{	
	url = root_url+"/swf/pictobrowser.swf";
	embedSwf( divId, url , flashvars, {id:divId,name:divId}, params );
}

function embedYouTubePlayer( divId, swfUrl, flashvars, params)
{
	embedSwf( divId, swfUrl, flashvars, {id:divId,name:divId}, params )	
}

function embedSwf( divId, url, flashvars, attributes, params)
{
	swfobject.embedSWF(url, divId, params.width, params.height, "9.0.0", root_url+"/swf/expressInstall.swf",	flashvars, params,	attributes);	
}

function addCssClass(id, cssClass)
{
	$(id).addClass(cssClass);	
}

function removeCssClass(id, cssClass)
{
	$(id).removeClass(cssClass);	
}

function toggleCssClass( id, cssClass )
{
	$(id).toggleClass( cssClass );	
}

function changeColor(id, property, color)
{
	$(id).setStyle(property,color);
}

var commentForm;
function submitComment(form)
{
	commentForm = form;
	$(form).toggleClass('display-none');
	$('wait-validation').toggleClass('display-none');
	$(form).send(
		{
			onComplete: function(data)
			{
				var obj = Json.evaluate(data);
				validateComment(obj);
			}
		}
	);
	
	return false;
}

function validateComment(response)
{
	var tab = $$('.error','.no-error');
	$('wait-validation').toggleClass('display-none');
	$(commentForm).toggleClass('display-none');
	if(response.errors)
	{
		$('formulaire-commentaire').removeClass('display-none');
		tab.each(
			function(item, index)
			{
				var name = item.getProperty('name');
				if( response.errors.contains( name ) )
				{
					item.removeClass('no-error');
					item.addClass('error');
				}else{
					item.removeClass('error');
					item.addClass('no-error');					
				}
			}
		);
		var captcha = $$('*[name$=captcha_phrase]')[0];
		captcha.removeClass('no-error');
		captcha.addClass('error');
		captcha.setProperty('value', '');
		
	}else{
		commentForm.reset();
		
		var sel = $$('.error');
		sel.removeClass('error');
		sel.addClass('no-error');
		$('formulaire-commentaire').addClass('display-none');
		response.newComment.number = $('commentaire-nouvelle').getChildren().length + 1;
		$$('span[name=comment-lenght]').setHTML(response.newComment.number);
		processNewComment( response.newComment );
	}
	var new_captcha = new Element('div').setHTML(response.captcha);
	new_captcha.setProperty('id', 'captcha');
	$('captcha').replaceWith(new_captcha);
}

function processNewComment( newComment )
{
	var template = $('comment-template').innerHTML;
	var result = new Element('div').setHTML(template.process( newComment )).getFirst();
	
	result.injectTop($('commentaire-nouvelle'));
	var fx = new Fx.Style(result, 'background-color', {duration:1500});
	fx.start( $('header-nouvelle').getStyle('background-color'),'#FFFFFF' );
}

function clickAlerteMeteo()
{
	var flash=$('alert-meteo-flash');
	if(flash.hasClass('display-none'))
	{
		var div = new Element('div');
		div.setProperty('id', 'fido');
		flash.adopt(div);
		var flashvars={};
		var params={
			wmode:"transparent"
		};
		var attributes={};
		swfobject.embedSWF(root_url+"/swf/fido_meteo.swf", 'fido', '100%','100%' , "9.0.0", root_url+"/swf/expressInstall.swf",	flashvars, params,	attributes);	
		
	}else{
		$('fido').remove();
	}
	
	toggleCssClass('alert-meteo-flash','display-none');	
}
function deleteComment(url, id)
{
	$(id).remove();
	$$('span[name=comment-lenght]').setHTML($('commentaire-nouvelle').getChildren().length );
	var myAjax = new Ajax(
		url, {method: 'post'}
	);
	myAjax.request();
}








function accordeon() {
	//create our Accordion instance
	var myAccordion = new Accordion($('accordion'), 'h3.toggler', 'div.element', {
		opacity: false,
		display:-1,
		onActive: function(toggler, element){
			toggler.setStyle('color', '#000');
		},
		onBackground: function(toggler, element){
			toggler.setStyle('color', '#000');
		}
	});
};
