/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var	urlServices	= 'http://www.rondedespains.com/services/';
//var	urlServices	= 'http://projets.intothereal.com/dev/nutrixo/rdp/services/';
// var	urlServices	= 'http://rdp.local/services/';


window.RDP	= (function(){

	var	statLoading	= 5;


	var	currentURL	= null;
	var	currentItem	= null;

	var	currentEditElement	= null;

	var	scrollActu	= null;
	var	listActus	= null;

	var	listContent	= {accueil: null, reseau: null, campaillette: null, campaillou : null, contact: null, jeu: null};
	var	listCSS		= {accueil: 'contenu-home', reseau: 'contenu-reseau', campaillette: 'campaillette', campaillou : 'campaillou', contact: null, jeu: null};
	var	listInit	= {accueil: null, reseau: null, campaillette: null, campaillou : null, contact: null, jeu: null};

	var	listMenu	= [];

	var	zoom		= 1;
	var	idImage		= null;
	var	idTexte		= null;
	var	idListe		= null;
	var	idRubrique	= null;


	var	editor		= null;

	//	Exécute une fonction quand il n'y a plus de requette ajax en cours
	var	executeNoRequest	= function(fn) {

			if(Ajax.activeRequestCount == 0) {
				fn();
			} else {
				setTimeout(function(){executeNoRequest(fn);}, 500);
			}

		};

	/**
	 * Création du layer article
	 */
	var	createLayerArticle	= function () {
			var	elLayer	= new Element('div', {id: 'layerArticle', style: 'display: none;'});
			elLayer.addClassName('col-texte');
//			$('page').insert(elLayer);
			$('content').insert(elLayer);
		};

	/**
	 * Initialise le contenu du layer article
	 */
	var	initLayerArticle	= function () {

			var	btnClose		= $$('#layerArticle div.fermer a');

			if(!btnClose[0]) {
				setTimeout(initLayerArticle, 100);
			}else {
				btnClose			= btnClose[0];
				btnClose.onclick	= function() {return false;};

				btnClose.observe('click', closeLayerArticle);
				
				var scrollLayer = new Control.ScrollBar('contentScroll', 'scrollbar_track');
				setTimeout(function(){scrollLayer.recalculateLayout();}, 1000);

				openLayerArticle();
			}
		};

	/**
	 * affiche le layer d'article
	 */
	var	openLayerArticle	= function () {
			$('layerArticle').appear();
			$('layerArticle').morph({left: '0px'});
		};

	/**
	 * affiche le layer d'article
	 */
	var	closeLayerArticle	= function () {
			$('layerArticle').fade();
			$('layerArticle').morph({left: '-364px'});
		};

	//	charge un contenu et l'affiche dans le layer Article
	var	ajaxLayerArticle	= function (url) {

			if(!$('layerArticle')) {
				createLayerArticle();
			}

			new Ajax.Updater('layerArticle', url,
				{
					onComplete	: initLayerArticle,
					evalScripts	: true
				}
			);

		};

	//	initialise la carte googleMap
	var	initGoogleMap	= function () {

			$('address').observe('click', function(){$('address').value='';});
			$('address').observe('blur', function(){if($('address').value==''){$('address').value='Entrez votre adresse ici';}});

			$('valideGMAP').observe('click', openGMAP);
			$('valideGMAP').onclick	= function(){return false;};

			$('closeMap').onclick	= function(){return false;};
			$('closeMap').observe('click', closeGMAP);
		};

	/**
	 * ouvre le layer Google map
	 */
	var	openGMAP	= function () {
			address	= $('address').getValue() + ' FRANCE';

			$('localiser').appear({queue: 'end'});
			$('localiser').morph({height: '409px', top: '270px'});
			$('map1').morph({height: '409px'}, {afterFinish: load1});

			var scrollBoulanger = new Control.ScrollBar('listLocation', 'scrollbar_track_list');
			setTimeout(function(){scrollBoulanger.recalculateLayout();}, 2000);

		};

	/**
	 * ferme le layer Google map
	 */
	var	closeGMAP	= function () {
			$('localiser').fade({queue: 'end'});
			$('localiser').morph({height: '0px', top: '671px'});
			$('map1').morph({height: '0px'});
		};

	//	fait défiler les actus sur la home
	var	nextActu	= function () {

			if(currentItem == 'accueil') {

				if(listActus.size() > 1) {

					var first	= listActus[0];

					first.remove();
					$('scrollActu').insert(first);

					first	= listActus.shift();

					listActus.push(first);

					if(scrollActu != null) {
						scrollActu.cancel();
					}

					scrollActu	= new Effect.ScrollHorizontal('divActu',
						{
							duration: 10,
							queue: {scope: 'filActu'},
							from: (listActus[0].positionedOffset().left),
							to: (listActus[1].positionedOffset().left),
							afterFinish: nextActu,
							transition: Effect.Transitions.linear
						}
					);
				}
			}
		};

	//	initialise un menu latérale @TODO A remplacer par MORPH
	var	initSideMenu	= function (button, el, width, close) {

//			alert(close);

			close			= close || false;

			button.onclick	= function(){return false;};

			button.observe( 'click',

				function(event) {
					if(el.getWidth() == 0) {
						el.morph('width: ' + width + 'px;');
					} else {
						el.morph('width: 0px;');
					}
				}.bind(button, el, width)

			);

			if(close == true) {
//				alert('ok');
				el.morph('width: 0px;');
//				el.setStyle({width: '0px'});
			}
		};

	//	initialisation commune des pages
	var	initCommon	= function() {
			$('layerLoader').setStyle({opacity: 0.5, zIndex: 200});
			$('ficheBoulanger').hide();

			Ajax.Responders.register({
				onCreate: displayLoader,
				onSuccess: hideLoader,
				onComplete: hideLoader
			});

			listMenu	= $$('#nav li a');

			var	content		= ['accueil', 'reseau', 'campaillette', 'campaillou', 'jeu'];

			content.each(
				function(el, index) {

					if(listMenu[index]) {

						listMenu[index].onclick	= function(){return false;};

							new Ajax.Request(listMenu[index].href + '&ajax=oui', {

								onSuccess: function(transport) {

									$('contenu').insert(transport.responseText);
									listContent[el]	= $($$('#contenu div.pageMenu').pop());
									listContent[el].hide();

									statLoading--;

									if(el == currentItem) {
										listContent[el].show();
										$($$('#contenu div.pageMenu').shift()).remove();
									}
								}

//								onFailure	: function() { alert('ok');statLoading--; }
							});


						listMenu[index].observe('click', changePage.bind(this, el));

					}

				}
			);
				
			executeNoRequest( function(){changePage(currentItem);} );
			initGoogleMap();

		};

	//	change de page. Uniquement pour les pages chargé en Ajax
	var	changePage	= function(el, event) {
			if(statLoading == 0) {
				
				if(event) {
					listMenu.each(function(el){el.removeClassName('on')});
					Event.element(event).addClassName('on');
				}

				listContent[el].show();
				$('contenu').addClassName(listCSS[el]);

				if(currentItem != el) {
					$('contenu').removeClassName(listCSS[currentItem]);
					listContent[currentItem].hide();
				}

				if(RDP['stop_' + currentItem]) {
					RDP['stop_' + currentItem]();
				}else {
					alert('Pas de stop : ' + currentItem);
				}

				currentItem	= el;

				if(RDP['start_' + currentItem]) {
					RDP['start_' + currentItem].defer();
				}else {
					alert('Pas de start : ' + currentItem);
				}
			}

		};

	//	Affiche le loader Ajax
	var	displayLoader	= function () {
		var	layerLoader	= $('layerLoader');
		layerLoader.appear({to: 0.5, duration: 0.2});
	}

	/**
	 * cache le layer de loader ajax
	 */
	var	hideLoader	= function () {
		if(Ajax.activeRequestCount == 0) {
			$('layerLoader').fade({to: 0, duration: 0.2});
		}
	}

	//	initialise la liste de pains pour les campaillette et les campaillou
	var	initListePain	= function(context) {
			$$('.page' + context + ' #contentListe ul li a').each(

				function(el) {
					el.onclick	= function(){return false;};
					el.observe('click',
						function() {
							new Ajax.Updater($$('.content' + context + '')[0], el.href + '&ajax=oui&only=campaillette',
								{
									onComplete	: function(){initPictos('.page' + context + '', false);}
								}
							);
						}.bind(el)
					);
				}

			);

		};

	//	initialise les pictos pour les campaillettes et les campaillou
	var	initPictos	= function(context, open) {
			$$(context + ' .pictos li a').each(
					function(el) {
						new	morphTMP(el, el.select('.picto-text')[0]);
						el.onclick	= function(){return false;};
						el.observe('click',
							function() {
								ajaxLayerArticle(el.href + '&ajax=oui');
							}.bind(el)
						);
					}
			);

			new morphTMP($$(context + ' #btn-suivant')[0], $$(context + ' #suivantContent')[0], {eventOpen: 'click', eventClose: 'click', transitionOpen: Effect.Transitions.linear, fixedSize: 134, durationOpen: 0.5, startClose: open});
		};


	//	initialise la partie admin des fiches perso
	var	initEspaceFiche	= function() {
//			spDebug.profile('Initialisation');

			idRubrique	= $$('.espace-reseau')[0].title;

//			spDebug.info('menu image');
			$$('#contenu-pro .images').each(
				function(el) {
					createMenuImage(el);
				}
			);

//			spDebug.info('menu texte');
			$$('#contenu-pro .texte').each(
				function(el) {
					createMenuTexte(el);
				}
			);

//			spDebug.info('menu infos');
			$$('#contenu-pro .infos').each(
				function(el) {
					createMenuInfos(el);
				}
			);

//			spDebug.info('menu liste');
			$$('#contenu-pro .liste').each(
				function(el) {
					createMenuListe(el);
				}
			);

//			spDebug.info('init layer');
			$('layerFiche').observe('click', function(){$('formAdmin').fade({duration: 0.5});closeEditElement();});
			$('layerFiche').appear({to: 0.4});

//			spDebug.info('init scroll');
			initScrollFiche();
//			spDebug.info('init slide show');
			initSlideShowFiche();
//			spDebug.info('init liste');
			initListes();

//			spDebug.info('charge le menu');
			new Ajax.Updater('entete', 'fiche/menu.php',
					{
						insertion	: 'bottom',
						onComplete	: function(){initMenuEdition();}
					}
			);

//			spDebug.profile('Initialisation');

		};

/**
 *
 *	Administration des fiches boulanger
 *
 *
 *
 *
 */

	var	initMenuEdition	= function() {

			$('submit').observe('click', function() {alert('Les modifications sont soumises à validation.');});

			//	initialise le menu couleur
			$('colorList').hide();
			
			$('chooseColor').observe('mouseenter', function(){$('colorList').show();});
			$('chooseColor').observe('mouseleave', function(){$('colorList').hide();});

			$$('#colorList li').each(
				function(el) {
					el.observe('click', changeColor);
				}
			);

			//	initialise le menu ajouter un bloc
			$('blocList').hide();

			$('addBloc').observe('mouseenter', function(){$('blocList').show();});
			$('addBloc').observe('mouseleave', function(){$('blocList').hide();});

			$$('#blocList li').each(
				function(el) {
					el.observe('click', addBlock);
				}
			);

			//	initialise le menu changer de fiche
			if($('changeUser')) {
				$('userList').hide();

				$('changeUser').observe('mouseenter', function(){$('userList').show();});
				$('changeUser').observe('mouseleave', function(){$('userList').hide();});

//				$$('#userList li').each(
//					function(el) {
//						el.observe('click', addBlock);
//					}
//				);
			}
		};

	var	changeColor	= function(event) {

			var	el		= Event.element(event);
			var	fiche	= $$('.espace-reseau')[0];

			fiche.removeClassName('bgIvoir');
			fiche.removeClassName('bgJaune');
			fiche.removeClassName('bgVert');
			fiche.removeClassName('bgBleu');
			fiche.removeClassName('bgParme');
			fiche.addClassName('bg' + el.id);
			
			new Ajax.Request('fiche/updateColor.php?color=' + el.id);
		};

	var	addBlock	= function(event) {
		
			var	el		= Event.element(event);
			var	fiche	= $$('.espace-reseau')[0];

			//	calcul si il reste de la place pour ajouter un bloc
			new Ajax.Request('fiche/addBloc.php?type=' + el.id + '&color=' + el.className,
					{
						onComplete: reloadPage
					}
				);
			
			spDebug.info(fiche + ' -> ' + el.id);
		};

	var	listEspace			= null;
	var	mapEspace			= null;
	var	currentMoveIndex	= null;
	var	currentMoveId		= null;
	var	nbBloc				= null;
	var	nbBlocMax			= null;
	var	sizeBloc			= null;
	var	positionBloc		= null;

	var	sizeBlocOrigine		= null;
	var	positionBlocOrigine	= null;

	var	changeListEspace			= function(value) {listEspace		= value;};
	var	changeMapEspace				= function(value) {mapEspace		= value;};
	var	changeCurrentMoveIndex		= function(value) {currentMoveIndex	= value;};
	var	changeCurrentMoveId			= function(value) {currentMoveId	= value;};
	var	changeNbBloc				= function(value) {nbBloc			= value;};
	var	changeCurrentMovePosition	= function(value) {positionBloc		= value.split('x');positionBloc[0] = parseInt(positionBloc[0]);positionBloc[1] = parseInt(positionBloc[1]);};
	var	changeCurrentMoveTaille		= function(value) {sizeBloc			= value.split('x');sizeBloc[0] = parseInt(sizeBloc[0]);sizeBloc[1] = parseInt(sizeBloc[1]);};

	var	imgMoins				= 'images/fiche/btn-moins.jpg';
	var	imgPlus					= 'images/fiche/btn-plus.jpg';


	var	reloadPage	= function(transport) {


			if(transport.responseText != '') {
				alert(transport.responseText);
			} else {
				var tmp = window.location;
				window.location		= tmpURL + '&rnd=' + Math.random();

			}

		};

	var	markCurrentElement	= function (el) {	
			closeEditElement();
			currentEditElement	= $(el);
			currentEditElement.setStyle({border: '5px dashed red', marginLeft: '15px', marginTop: '-5px'});
		};

		//
		//	Déplacer un BLOC
		//
	var	loadMove	= function(type, el, event) {

			markCurrentElement(el);

			new Ajax.Updater('formAdmin', 'fiche/move.php?type=' + type + '&id=' + currentEditElement.title,
					{
						evalScripts	: true,
						method		: 'get',
						onComplete	: initMove.bind(this, type),
						insertion	: 'top'
					}
			);
		};

	var	initMove	= function(type) {
			$('formAdmin').appear({duration: 0.5, afterFinish: initMoveAction.bind(this, type)});
		};

	var	initMoveAction	= function(type) {

			markBloc(sizeBloc, positionBloc);

			$('closeForm').onclick	= function() {return false;};

			$('closeForm').observe('click', function(){

					$('blocForm').request({
						parameters:	'type=' + type + '&x=' + positionBloc[0] + '&y=' + positionBloc[1] + '&w=' + sizeBloc[0] + '&h=' + sizeBloc[1] + '&id=' + currentMoveId,
						onComplete: reloadPage
					});


				}
			);


		};

		//	Marquer les blocs pris
	var	markBloc	= function(size, position) {

			var	index		=	0;
			var	listBloc	= $$('#editImage .listBlocs div');

			var	totalSize	= size[0] * size[1];


			listBloc.each(
				function(el, index) {
					el.removeClassName('selected');
					el.stopObserving('click');
					
					//	si il y a les plus c'est une action de redimensionnement
					if(el.firstDescendant()) {
						el.observe('click', changeSizeBloc.bindAsEventListener(this, index));
					} else {
					//	si non c'est du déplacement
						el.observe('click', moveBlocMap.bindAsEventListener(this, index));
					}
				}
			);
			
			for(var width=0; width<size[0]; width++) {
				for(var height=0; height<size[1]; height++) {
					index	= (((height*1 + position[1]*1)-1)*3) + ((width*1 + position[0]*1)-1);

					if(listBloc[index]) {
						listBloc[index].addClassName('selected');

						if(width == 0 && height == 0 && listBloc[index].firstDescendant()) {
							listBloc[index].firstDescendant().hide();
						}
					} else {
					}
				}
			}
		};

		//	déplace les blocs
	var	moveBlocMap	= function(event, index) {
			var	y	= 1;
			var	x	= index+1;

			if(index>2) {
				y	= 2;
				x	= index-2;
			}

			if( ((x + sizeBloc[0]) -1) < 4 && ((y + sizeBloc[1]) -1) < 3) {
				positionBloc[0]	= x;
				positionBloc[1]	= y;
				markBloc(sizeBloc, positionBloc);
			}

		};

		//
		//	Redimensionner les blocs
		//
	var	loadSizeBloc	= function(type, el) {
			markCurrentElement(el);

			new Ajax.Updater('formAdmin', 'fiche/size.php?type=' + type + '&id=' + currentEditElement.title,
					{
						evalScripts	: true,
						method		: 'get',
						onComplete	: initMoveSize.bind(this, type),
						insertion	: 'top'
					}
			);

		};

//	var	initChangeSize	= function(test) {
//			$('formAdmin').appear({duration: 0.5, afterFinish: initSizeAction.bind(this, type)});
//		};

	var	initSizeAction	= function(type) {

			markBloc(sizeBloc, positionBloc);

			$('closeForm').onclick	= function() {return false;};

			$('closeForm').observe('click', function(){

					$('blocForm').request({
						parameters:	'type=' + type + '&x=' + positionBloc[0] + '&y=' + positionBloc[1] + '&w=' + sizeBloc[0] + '&h=' + sizeBloc[1] + '&id=' + currentMoveId,
						onComplete: reloadPage
					});


				}
			);


		};

	var	changeSizeBloc	= function(event, index) {

			alert(index);

		};

/***************************************************************************************************************/
/***************************************************************************************************************/
/***************************************************************************************************************/


	var	initMoveSize	= function(type) {
			$('formAdmin').appear({duration: 0.5, afterFinish: initMoveActionSize.bind(this, type)});
		};

	var	initMoveActionSize	= function(type) {

			positionBlocOrigine	= [positionBloc[0], positionBloc[1]];

			markBlocSize(sizeBloc, positionBloc);
			nbBlocMax	= 4;

			//	initialise le formulaire Ajax.
			$('closeForm').onclick	= function() {return false;};

			$('closeForm').observe('click', function(){

					$('blocForm').request({
						parameters:	'type=' + type + '&x=' + positionBloc[0] + '&y=' + positionBloc[1] + '&w=' + sizeBloc[0] + '&h=' + sizeBloc[1] + '&id=' + currentMoveId,
						onComplete: reloadPage
					});


				}
			);

		};

	var	markBlocSize	= function(size, position) {


			spDebug.info('x : ' + positionBlocOrigine[0])

			var	index		=	0;
			var	listBloc	= $$('#editImage .listBlocs div');

			var	totalSize	= size[0] * size[1];

			listBloc.each(
				function(el, index) {
					el.removeClassName('selected');
					el.firstDescendant().src	= imgPlus;
					el.firstDescendant().show();
					el.firstDescendant().stopObserving('click');
					el.firstDescendant().observe('click', addBlocMapSize.bindAsEventListener(this, index));
				}
			);

			for(var width=0; width<size[0]; width++) {
				for(var height=0; height<size[1]; height++) {
					index	= (((height*1 + position[1]*1)-1)*3) + ((width*1 + position[0]*1)-1);


					if(listBloc[index]) {
						listBloc[index].addClassName('selected');
						listBloc[index].firstDescendant().stopObserving('click');

						if( positionBlocOrigine[0] == ((width*1 + position[0]*1)) && positionBlocOrigine[1] == (height+1) ) {
							listBloc[index].firstDescendant().hide();
						}

						if(totalSize > 1) {
							listBloc[index].firstDescendant().src	= imgMoins;
							listBloc[index].firstDescendant().observe('click', removeBlocMapSize.bindAsEventListener(this, index));
						} else {
							listBloc[index].firstDescendant().hide();
						}
					} else {
					}
				}
			}
		};

//	var	getCurrentSize	= function() {
//			var	infos		= listEspace[currentMoveIndex];
//			var	size		= infos.size.split('x');
//
//			size[0]	= parseInt(size[0]);
//			size[1]	= parseInt(size[1]);
//
//			return	size;
//		};
//
//	var	getCurrentPosition	= function() {
//			var	infos		= listEspace[currentMoveIndex];
//			var	position	= infos.position.split('x');
//
//			position[0]	= parseInt(position[0]);
//			position[1]	= parseInt(position[1]);
//
//			return	position;
//		};

	var	addBlocMapSize	= function(event, index) {

			var	size		= sizeBloc;
			var	position	= positionBloc;

			var	y	= 1;
			var	x	= index+1;

			var	height	= size[1];
			var	width	= size[0];

			if(index>2) {
				y	= 2;
				x	= index-2;
			}

			if(y == position[1] && size[1] == 1) {
				height = 1;
			} else {
				height = 2;
			}

			if( (size[0] * size[1]) < nbBlocMax && nbBlocMax != 1) {

				if(x != position[0]) {
					width	= Math.abs(x - position[0]) + 1;
				}

				if(x > position[0]) {
					x	= position[0];
				}

				if(y > position[1]) {
					y	= position[1];
				}

				if( (y > 0 && y < 3) && (x > 0 && x < 4) && (width > 0 && width < 4) && (height > 0 && height < 3) && (width*height <= nbBlocMax)) {
					positionBloc[0]	= x;
					positionBloc[1]	= y;
					sizeBloc[0]		= width;
					sizeBloc[1]		= height;
					$('error').update('');
				} else {
					$('error').update('Déplacement impossible.');
				}

			} else {
				$('error').update('Déplacement impossible.');
			}

			markBlocSize(sizeBloc, positionBloc);

		};

	var	removeBlocMapSize	= function(event, index) {
			var	size		= sizeBloc;
			var	position	= positionBloc;

			var	y	= 1;
			var	x	= index+1;

			var	height	= size[1];
			var	width	= size[0];

			spDebug.info('Hauteur base : ' + height);
			if(index>2) {
				y	= 2;
				x	= index-2;
			}

			if(y == position[1] && size[1] == 1) {
				width = width -1;
			} else {
				height = 1;
			}

			if(x == position[0] && size[0] == 1) {
				height = height -1;
			} else {
				width = 1;
			}

			if(positionBlocOrigine[0] > x) {
				x	= (positionBlocOrigine[0] - width) + 1;
			} else {
				x	= positionBlocOrigine[0];
			}

			if(positionBlocOrigine[1] > y) {
				y	= (positionBlocOrigine[1] - height) + 1;
			} else {
				y	= positionBlocOrigine[1];
			}

			if(height == 0) {
				height = 1;
			}

			if(width == 0) {
				width = 1;
			}

			if( (size[0] * size[1]) && nbBlocMax != 1) {



				if( (y > 0 && y < 3) && (x > 0 && x < 4) && (width > 0 && width < 4) && (height > 0 && height < 3) && (width*height > 0)) {
					positionBloc[0]	= x;
					positionBloc[1]	= y;
					sizeBloc[0]		= width;
					sizeBloc[1]		= height;
					$('error').update('');
				} else {
					$('error').update('Déplacement impossible.');
				}

			} else if(nbBlocMax == 1) {
				$('error').update('Déplacement impossible.');
			} else {
				$('error').update('Déplacement impossible.');
			}

			markBlocSize(sizeBloc, positionBloc);

		};

//	var	getBlocIndexByPosition	= function(x, y) {
//			return	mapEspace[y][x];
//		};
//
//	var	getBlocByIndex	= function(index) {
//
//			var	y	= 1;
//			var	x	= index+1;
//
//			if(index>2) {
//				y	= 2;
//				x	= index-2;
//			}
//
//			return	listEspace[mapEspace[y][x]];
//
//		};

//	var	getSizeBlocByPosition	= function(x, y) {
//
//			var	numBloc	= getBlocIndexByPosition(x,y);
//			var	newX	= 0;
//			var	newY	= 0;
//
//			var	width	= 1;
//			var	height	= 1;
//
//			var	tmpY	= 0;
//
//			spDebug.info('numBloc: ' + numBloc);
//
//			for(width = 1; width<4; width++) {
//
//
//				if(getBlocIndexByPosition(width,height) == numBloc) {
//					spDebug.info('plus X');
//					newX = newX+1;
//				}
//
//				tmpY	= 0;
//
//				for(height = 1; height<3; height++) {
//					if(getBlocIndexByPosition(width,height) == numBloc) {
//						tmpY++;
//					}
//				}
//
//				if(tmpY > newY) {
//					newY	= tmpY;
//				}
//
//				height	= 2;
//
//			}
//			spDebug.info(newX + 'x' + newY);
//			return	newX + 'x' + newY;
//
//		};

//	var	updateBlocPosition	= function() {
//
//		};


/***************************************************************************************************************/
/***************************************************************************************************************/
/***************************************************************************************************************/




		//
		//	BLOC INFO
		//
	var	createMenuInfos	= function(el) {
			new menuBloc(el,
				{
					items	: [
						{title: 'Modifier', fn: editInfos},
						{title: 'Déplacer', fn: loadMove.bind(this, 'infos')}
					]
				}
			);
		};

	var	editInfos	= function(el, event) {
			markCurrentElement(el);
			new Ajax.Updater('formAdmin', 'fiche/infos.php?id=' + currentEditElement.title,
					{
						method		: 'get',
						onComplete	: initEditInfos,
						insertion	: 'top'
					}
			);

		};

	var	initEditInfos	= function() {
			$('formAdmin').appear({duration: 0.5, afterFinish: initEditInfosAction});
		};

	var	initEditInfosAction	= function() {
			$('closeForm').onclick	= function() {return false;};

			$('closeForm').observe('click', function(){

					$('blocForm').request({
						parameters:	'idInfos=' + currentEditElement.title,
						onComplete: reloadPage
					});


				}
			);

		};

		//
		//	BLOC TEXTE
		//
	var	createMenuTexte	= function(el) {
			new menuBloc(el,
				{
					items	: [
						{title: 'Modifier', fn: editTexte},
						{title: 'Déplacer', fn: loadMove.bind(this, 'texte')},
						{title: 'Taille', fn: loadSizeBloc.bind(this, 'texte')},
						{title: 'Supprimer', fn: deleteBlocTexte}
					]
				}
			);
		};

	var	deleteBlocTexte	= function(el, event) {

			currentEditElement	= $(el);
			currentEditElement.setStyle({border: '5px dashed red', marginLeft: '15px', marginTop: '-5px'});

			if(confirm('Supprimer ce bloc texte ?')) {
				new Ajax.Request('fiche/deleteBlocTexte.php?id=' + currentEditElement.title,
						{
							parameters:	'idTexte=' + currentEditElement.title,
							onComplete: reloadPage
					});
			} else {
				currentEditElement.setStyle({border: 'none', marginLeft: '20px', marginTop: '0'});
				currentEditElement	= null;
			}

		};

	var	editTexte	= function(el, event) {
			markCurrentElement(el);

			new Ajax.Updater('formAdmin', 'fiche/text.php?id=' + currentEditElement.title,
					{
						method		: 'get',
						onComplete	: initEditTexte,
						insertion	: 'top'
					}
			);

		};	


	var	initEditTexte	= function() {
			$('formAdmin').appear({duration: 0.5, afterFinish: initEditTexteAction});
		};

	var	initEditTexteAction	= function() {
			
			editor	= CKEDITOR.replace( 'editor', {toolbar: 'MyToolbar'});
			
			$('closeForm').onclick	= function() {return false;};
			
			$('closeForm').observe('click', function(){

					$('editor').setValue(editor.getData());
					
					$('blocForm').request({
						parameters:	'idTexte=' + currentEditElement.title,
						onComplete: reloadPage
					});

					
				}
			);
		};

		//
		//	BLOC LISTE
		//
	var	createMenuListe	= function(el) {
			new menuBloc(el,
				{
					items	: [
						{title: 'Modifier le titre', fn: editListeTitre},
						{title: 'Modifier les entrées', fn: editListe},
						{title: 'Déplacer', fn: loadMove.bind(this, 'liste')},
						{title: 'Taille', fn: loadSizeBloc.bind(this, 'liste')},
						{title: 'Supprimer', fn: deleteBlocListe}
					]
				}
			);
		};

	var	editListeTitre	= function(el) {
			markCurrentElement(el);

			new Ajax.Updater('formAdmin', 'fiche/listeTitre.php?id=' + currentEditElement.title,
					{
						method		: 'get',
						onComplete	: initEditListeTitre,
						insertion	: 'top'
					}
			);

		};

	var	editListe	= function(el) {
			markCurrentElement(el);

			new Ajax.Updater('formAdmin', 'fiche/liste.php?id=' + currentEditElement.title,
					{
						method		: 'get',
						onComplete	: initEditListe,
						insertion	: 'top'
					}
			);

		};

	var	initEditListeTitre	= function() {
			$('formAdmin').appear({duration: 0.5, afterFinish: initEditListeTitreAction});
		};

	var	initEditListe	= function() {
			$('formAdmin').appear({duration: 0.5, afterFinish: initEditListeAction});
		};

	var	initEditListeTitreAction	= function() {

			$('closeForm').onclick	= function() {return false;};

			$('closeForm').observe('click', function(){

					$('blocForm').request({
						parameters:	'idListe=' + currentEditElement.title,
						onComplete: reloadPage
					});

				}
			);

		};

	var	initEditListeAction	= function() {
			editor	= CKEDITOR.replace( 'editor', {toolbar: 'MyToolbar'});

			$('closeForm').onclick	= function() {return false;};

			$('closeForm').observe('click', reloadPage.bind(this, {responseText: ''}));


			$$('.listListe .item').each(

				function(el, index) {
					el.select('.action .edit')[0].observe('click', selectListe.bind(this, el, index));
					//if(index != 0) {
						el.select('.action .delete')[0].observe('click', deleteListe.bind(el));
					//}
				}

			);

			$('btnListeForm').onclick	= function() {return false;};
			$('btnListeForm').observe('click', addItemListe);

		};

	var	selectListe	= function(el, index, event) {

			$('btnListeForm').setValue('Valider');

			$('btnListeForm').stopObserving('click');
			$('btnListeForm').observe('click', updateItemListe.bind(this,el, index));

			new Ajax.Request('fiche/editListeTexte.php?id=' + el.title,
					{
						onComplete: function(transport) {
								editor.setData(transport.responseText);
								$('cke_editor').show();
						}

				});

			new Ajax.Request('fiche/editListeTitre.php?id=' + el.title,
					{
						onComplete: function(transport) {$('titreListe').setValue(transport.responseText);}

				});

		};

	var	addItemListe	= function(el, index, event) {

			$('editor').setValue(editor.getData());

			$('blocForm').request({
				parameters:	'idListe=' + currentEditElement.title + '&ordre=-1',
				onComplete: function(transport){
					if(transport.responseText != '') {
						alert(transport.responseText);
					} else {
						editListe(currentEditElement);
					}
				}
			});
		};

	var	updateItemListe	= function(el, index, event) {

			$('editor').setValue(editor.getData());

			$('blocForm').request({
				parameters:	'idListe=' + el.title + '&ordre=' + index,
				onComplete: function(transport){
					editListe(currentEditElement);
				}
			});
			

		};
		
	var	deleteBlocListe	= function(el) {
			currentEditElement	= $(el);
			currentEditElement.setStyle({border: '5px dashed red', marginLeft: '15px', marginTop: '-5px'});

			if(confirm('Supprimer ce bloc liste ?')) {
				new Ajax.Request('fiche/deleteBlocListe.php?id=' + currentEditElement.title,
						{
							parameters:	'idImage=' + currentEditElement.title,
							onComplete: reloadPage

					});
			} else {
				currentEditElement.setStyle({border: 'none', marginLeft: '20px', marginTop: '0'});
				currentEditElement	= null;
			}

		};

	var	deleteListe	= function(event) {

			if(confirm('Voulez vous supprimer ce texte ?')) {
				idListe	= Event.element(event).title;
				if(idListe !== null) {
					new Ajax.Request('fiche/deleteListe.php?idListe=' + idListe, {onComplete: function(){editListe(currentEditElement);}});

				}
			}
	};

		//
		//	BLOC IMAGE
		//
	var	createMenuImage	= function(el) {
			new menuBloc(el,
				{
					items	: [
						{title: 'Modifier', fn: editImage},
						{title: 'Déplacer', fn: loadMove.bind(this, 'image')},
						{title: 'Supprimer', fn: deleteBlocImage}
					]
				}
			);
		};


	var	deleteImage	= function(event) {

			if(confirm('Voulez vous supprimer cette image ?')) {
				idImage	= Event.element(event).title;
				if(idImage !== null) {

					new Ajax.Request('fiche/deleteImage.php?idImage=' + idImage, {onComplete: function(){editImage(currentEditElement);}});

				}
			}
	};

	var	deleteBlocImage	= function(el, event) {
		
			currentEditElement	= $(el);
			currentEditElement.setStyle({border: '5px dashed red', marginLeft: '15px', marginTop: '-5px'});

			if(confirm('Supprimer ce bloc image ?')) {
				new Ajax.Request('fiche/deleteBlocImage.php?id=' + currentEditElement.title,
						{
							parameters:	'idImage=' + currentEditElement.title,
							onComplete: reloadPage
					});
			} else {
				currentEditElement.setStyle({border: 'none', marginLeft: '20px', marginTop: '0'});
				currentEditElement	= null;
			}		
		};

	var	editImage	= function(el, event) {
			markCurrentElement(el);
			
			idImage	= null;

			new Ajax.Updater('formAdmin', 'fiche/img.php?id=' + currentEditElement.title,
					{
						method		: 'get',
						onComplete	: initEditImage,
						insertion	: 'top'
					}
			);
			
		};

	var	closeEditElement	= function() {

		if(editor !== null) {
			editor.destroy();
			editor	= null;
		}

		var	child	= $('formAdmin').firstDescendant();

		if(child.id != 'layerFiche') {
			$(child).remove();
		}

		if(currentEditElement != null) {
			currentEditElement.setStyle({border: 'none', marginLeft: '20px', marginTop: '0'});
			currentEditElement	= null;
		}
	}

	var	initEditImage	= function() {
			$('formAdmin').appear({duration: 0.5, afterFinish: initEditImageAction});
		};

	var	initEditImageAction	= function() {

			new Draggable('editImg', {onEnd: updateEditImage, change: checkEditImage});

			zoom	=	1;
			changeSizeEditImage(zoom);

			$('imgPlus').observe('click', zoomPlus);
			$('imgMoins').observe('click', zoomMoins);

			$$('.listImg .item').each(

				function(el, index) {

					el.select('.action .edit')[0].observe('click', selectImage.bind(el));
					el.select('.action .delete')[0].observe('click', deleteImage.bind(el));
					if(index == 0) {
						var	param	= el.select('div.action')[0];
						selectImageEdit(el, param.title);
					}
				}
				
			);

			new AjaxUpload('addImage', {
				action: 'fiche/upload-handler.php',
				name: 'myfile',
				onSubmit : function(file , ext){
					// Allow only images. You should add security check on the server-side.
					if (ext && /^(jpg|jpeg|JPG|JPEG)$/.test(ext)){
						/* Setting data */
						
						this.setData({
							'id_article': currentEditElement.title
						});
					} else {
						alert('Seul les fichiers JPG ou JPEG sont autorisés.');
						return false;
					}
				},
				onComplete : function(file){
					editImage(currentEditElement);
				}
			});

			$('closeForm').onclick	= function() {return false;};

			$('closeForm').observe('click', reloadPage.bind(this, {responseText: ''}));

		};

	var	zoomPlus	= function() {

			zoom	= zoom + 0.1;
			changeSizeEditImage(zoom);
			checkEditImage();
			updateEditImage();
		};

	var	zoomMoins	= function() {

			if(zoom > 0.2) {
				zoom	= zoom - 0.1;
				changeSizeEditImage(zoom);
				checkEditImage();
				updateEditImage();
			}
		};

	var	changeSizeEditImage	= function(zoom) {
			$('editImg').setStyle({width: (zoom*126) + 'px'});
		};

	var	checkEditImage	= function() {
			if($('editImg').getStyle('left').replace('px', '') > 0) {
				$('editImg').setStyle({left: '0px'});
			}

			if($('editImg').getStyle('top').replace('px', '') > 0) {
				$('editImg').setStyle({top: '0px'});
			}

			if($('editImg').getStyle('top').replace('px', '') < ((126) - $('editImg').getHeight())) {
				$('editImg').setStyle({top: ((126) - $('editImg').getHeight()) + 'px'});
			}

			if($('editImg').getStyle('left').replace('px', '') < ((126) - $('editImg').getWidth())) {
				$('editImg').setStyle({left: ((126) - $('editImg').getWidth()) + 'px'});
			}
		};

	var	updateEditImage	= function() {

			if(idImage !== null) {

				var	el	= $('editImg');
				new Ajax.Request('fiche/updateImage.php?left=' + el.getStyle('left') + '&top=' + el.getStyle('top') + '&zoom=' + zoom + '&idImage=' + idImage);
				
			}
			
		};

	var	selectImage	= function(event) {
			selectImageEdit(this, Event.element(event).parentNode.title);
		};

	var	selectImageEdit	= function(el, param) {

			var	src	= el.firstDescendant().innerHTML;
			
			$('editImg').setStyle({left: 0, top: 0});
			$('editImg').src	= 'images/fiche/' + idRubrique + '/' + src;
			$('editImg').show();
			$$('.listImg .item label').each(
				function(el) {
					el.removeClassName('selected');
				}
			);
				
			el.firstDescendant().addClassName('selected');

			param	= param.split('#');
			zoom	= parseFloat(param[0]);

			changeSizeEditImage(zoom);
			$('editImg').setStyle({left: param[1], top: param[2]});

		};
		

		/*
		 *	FIN DE L'ADMINISTRATION DES FICHES
		 */

	return	{
		//	points d'entré du site
		accueil			: function() {
			currentItem			= 'accueil';
			listContent.accueil	= $$('#contenu .pageMenu')[0].innerHTML;
			initCommon();
		},

		stop_accueil	: function() {
			if(scrollActu != null) {
				scrollActu.cancel();
			}
		},

		start_accueil	: function() {

			currentItem	= 'accueil';

			if(listActus == null) {
				listActus	= $$('#contenuActu div.actuItem');

				if(listActus.size() > 1) {
					var	tmp	= listActus.pop();
					listActus.unshift(tmp);
				}
			}

			listActus.each(function(el){el.remove();$('scrollActu').insert(el);});

			nextActu();
		},

		reseau			: function() {
			currentItem			= 'reseau';
			listContent.reseau	= $$('#contenu .pageMenu')[0].innerHTML;
			initCommon();
		},

		stop_reseau	: function() {

		},

		start_reseau	: function() {
			

			if(listInit.reseau == null) {
//				alert($$('#ssmenu-reseau #plus')[0]);
				initSideMenu($$('#ssmenu-reseau #plus')[0], $$('#ssmenu-reseau ul')[0], 282, false);
				$$('#ssmenu-reseau ul li a').each(
					function(el){
						el.onclick	= function(){return false;};
						el.observe('click',
							function() {
								ajaxLayerArticle(el.href + '&ajax=oui');
							}.bind(el)
						);
					}
				);

				listInit.reseau	= true;
			}

		},

		campaillette	: function() {
			currentItem			= 'campaillette';
			listContent.campaillette	= $$('#contenu .pageMenu')[0].innerHTML;
			initCommon();
		},

		stop_campaillette	: function() {

		},

		start_campaillette	: function() {

			if(listInit.campaillette == null) {
				//	initialise la liste des campaillettes
				new morphTMP($$('.pageCampaillette #plus')[0], $$('.pageCampaillette #contentListe')[0], {eventOpen: 'click', eventClose: 'click', transitionOpen: Effect.Transitions.linear, durationOpen: 0.5, startClose: false});

				initPictos('.pageCampaillette', true);
				//	initialise la liste des campaillettes
				initListePain('Campaillette');

				listInit.campaillette	= true;

			}
		},

		campaillou		: function() {
			currentItem			= 'campaillou';
			listContent.campaillou	= $$('#contenu .pageMenu')[0].innerHTML;
			initCommon();
		},

		stop_campaillou	: function() {

		},

		start_campaillou	: function() {
			if(listInit.campaillou == null) {
				new morphTMP($$('.pageCampaillou #plus')[0], $$('.pageCampaillou #contentListe')[0], {eventOpen: 'click', eventClose: 'click', transitionOpen: Effect.Transitions.linear, durationOpen: 0.5, fixedSize: 480, startClose: false});

				initPictos('.pageCampaillou', true);

				//	initialise la liste des campaillou
				initListePain('Campaillou');

				listInit.campaillou	= true;

			}
		},

		jeu			: function() {
			currentItem			= 'jeu';
			listContent.jeu	= $$('#contenu .pageMenu')[0].innerHTML;
			initCommon();
		},

		stop_jeu	: function() {

		},

		start_jeu	: function() {

			if(listInit.jeu == null) {
				RDP.initLinkJeu();
				listInit.jeu	= true;
			}

		},

		initLinkJeu	: function() {

				initSideMenu($('plusJeu'), $$('#ssmenu-jeu ul')[0], 282, false);

				var	linkJeu	= $$('#ssmenu-jeu ul li a')[0];
				linkJeu.onclick	= function(){return false;};
				linkJeu.observe('click',

					function() {

							new Ajax.Updater('flash', linkJeu.href + '&ajax=oui', {
									onSuccess: function(transport) {
										
										initLinkGame.defer();
									}

							});
					}
				);

				initLinkGame.defer();

				var	linkCompte	= $$('#ssmenu-jeu ul li a')[1];
				linkCompte.onclick	= function(){return false;};
				linkCompte.observe('click', processIdentification);

				var	linkResultat	= $$('#ssmenu-jeu ul li a')[2];
				linkResultat.onclick	= function(){return false;};
				linkResultat.observe('click',

					function() {

							new Ajax.Updater('flash', linkResultat.href + '&ajax=oui', {
									onSuccess: function(transport) {

										initFormResult.defer();

//										alert('ok');



//										jQuery("#loadResult").submit(function() {
//											alert('ok');
//											jQuery.ajax({
//												type: "GET",
//												data: s,
//												url: '/spip.php?page=resultats&id_rubrique=' + $('resultTheme').getValue() ,
//												success: function(retour){
//													$('resultatUpdate').update(retour);
//												}
//											});
//											return false;
//										});

									}

							});
					}
				);

				
		},

		contact			: function() {

		},

		espaceFiche		: function() {

			//	@TODO	faire la vérification de l'authentification
			initEspaceFiche();
		},

		espace			: function() {

		},

		mentions		: function() {

		},

		setListEspace			: changeListEspace,
		setMapEspace			: changeMapEspace,
		setCurrentMoveIndex		: changeCurrentMoveIndex,
		setCurrentMoveId		: changeCurrentMoveId,
		setCurrentMovePosition	: changeCurrentMovePosition,
		setCurrentMoveTaille	: changeCurrentMoveTaille,
		setNbBloc				: changeNbBloc,
		fiche					: function() {initFicheBoulanger();}

	};

})();
	
	
	jQuery.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;
	  while(x<c.length){var m=r.exec(c.substr(x));
		if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length;
		}else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);
		o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},
	URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;
	  while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);
	  t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}
	});
	
	var	elButton	= null;
	var	configJeu	= {name: 'aucun'};
	var	siteJeu	= 2;

	jQuery(document).ready(		
		function(e) {		
			jQuery(".button_jouez").each(
				function(i) {
					if(this.name == 'memory') {
						jQuery(this).onclick	= function(){return false;};
						jQuery(this).click(processIdentification);
					} else {
						jQuery(this).onclick	= function(){return false;};
						jQuery(this).click(goGame);
					}	
				}
			);

		}
	);
	
	function goGame() {
		elButton	= this;
		configJeu	= jQuery('.' + elButton.id)[0];
		playGame();
	}
	
	

	function initFormResult() {

		if($("loadResult")) {
			$("loadResult").onclick	= function(){return false;};

			$("loadResult").observe('click', function() {

					jQuery.ajax({
						type: "GET",
						url: 'spip.php?page=resultats&id_rubrique=' + $('resultTheme').getValue() ,
						success: function(retour){
							$('resultatUpdate').update(retour);
						}
					});


					return	false;
				}
			);
		}
	}

	function initLinkGame() {
		
		$$('input.button_jouez').each(
			function(el) {
//				alert('ok');
				el.onclick	= function(){return false;};
				el.observe('click', processIdentification.bindAsEventListener(this, el));
			}
		);
	}

	function processIdentification(event, el) {

		if(el) {
			configJeu	= $$('.' + el.id)[0];
		}
		
		jQuery.ajax({
			url: urlServices + 'checkLogin.php',
			success: function(data) {
				if(data == 'OK') {
					if(el) {
						checkReglement(el);
					} else {
						displayCompte();
					}
				} else {
					displayIdentification(el);
				}
			}
		});

		// alert('ok');
		
	}

	function checkReglement(el) {
		jQuery.ajax({
			url: urlServices + 'checkReglement.php?code_jeu=' + configJeu.name + '&site=' + siteJeu,
			success: function(data) {
				if(data == 'OK') {
					playGame(el);
				} else {
					displayReglement(el);
				}
			}
		});


		return	false;
	}

	function displayIForgotPassword(el) {
		jQuery.ajax({
			url: urlServices + 'forgotPasswordForm.php?site=' + siteJeu,
			success: function(data) {
				updateDisplayLayer(data);

				jQuery('.forgotPassword').each(
					function(i) {
						jQuery(this).click(displayIdentification.bind(this, el));
					}
				);
				jQuery('#inscription').click(displayInscription.bind(this, el));

				jQuery("#formLogin").submit(function() {
					s = jQuery(this).serialize();
					jQuery.ajax({
						type: "POST",
						data: s,
						url: jQuery(this).attr("action"),
						success: function(retour){
							alert(retour);
						}
					});
					return false;
				});
			}
		});


		return	false;
	}

	function displayIdentification(el) {
		jQuery.ajax({
			url: urlServices + 'loginForm.php?site=' + siteJeu,
			success: function(data) {
				updateDisplayLayer(data);

				jQuery('.forgotPassword').each(
					function(i) {
						jQuery(this).click(displayIForgotPassword.bind(this, el));
					}
				);

				jQuery('#inscription').click(displayInscription.bind(this, el));
//					alert('init');

				jQuery("#formLogin").submit(function() {
//					alert(jQuery(this).attr("action"));
					s = jQuery(this).serialize();
					jQuery.ajax({
						type: "POST",
						data: s,
						url: jQuery(this).attr("action"),
						success: function(retour){

							if(retour == '') {
								if(el) {
									checkReglement(el);
								} else {
									displayCompte();
								}
							} else {
								alert(retour);
							}
							
						}
					});
					return false;
				});
			}
		});


		return	false;
	}

	function displayInscription(el) {
		
		$$('#ssmenu-jeu ul')[0].morph('width: 0px;');
		
		jQuery.ajax({
			url: urlServices + 'signinForm.php?site=' + siteJeu + '&code_jeu=' + configJeu.name,
			type: "GET",
			success: function(data) {
				updateDisplayLayer(data);
				jQuery('#campaillette-inscription-form-error').hide();

				jQuery("#campaillette-inscription-formul").submit(function() {
					jQuery('#submitInscription').hide();
					s = jQuery(this).serialize();
					jQuery.ajax({
						type: "POST",
						data: s,
						url: jQuery(this).attr("action"),
						success: function(retour){
							if(retour == '') {
								console.log('call confirmation');
								displayConfirmInscription();
							} else {
								console.log('error');
								jQuery('#campaillette-inscription-form-error').html(retour);
								jQuery('#campaillette-inscription-form-error').show();
								jQuery('#submitInscription').show();
							}
						}
					});
					return false;
				});
			}
		});

		return	false;
	}

	function displayCompte() {

		jQuery.ajax({
			url: urlServices + 'compteForm.php?site=' + siteJeu,
			type: "GET",
			success: function(data) {
				updateDisplayLayer(data);
				jQuery('#campaillette-inscription-form-error').hide();

				jQuery("#campaillette-inscription-formul").submit(function() {
					jQuery('#submitInscription').hide();
					s = jQuery(this).serialize();
					jQuery.ajax({
						type: "POST",
						data: s,
						url: jQuery(this).attr("action"),
						success: function(retour){
							jQuery('#campaillette-inscription-form-error').html(retour);
							jQuery('#campaillette-inscription-form-error').show();
							jQuery('#submitInscription').show();
						}
					});
					return false;
				});
			}
		});

		return	false;
	}
	
	function closeLayer(){
		jQuery('#flashLayer').hide();
		jQuery('#flash').hide();
	}

	function closeJeuFlash() {
		$('#flash').hide();
		$('#flashLayer').hide();
		jQuery('#flash').html('');
	}
	
	function updateDisplayLayer(data) {
		if(data != 'KO') {
			$('flash').innerHTML=data;
		} else {
			alert('Une erreur technique est survenue.');
		}
	}

	function displayConfirmInscription() {
	
		console.log(urlServices + 'confirmSigninForm.php?site=' + siteJeu);
		jQuery.ajax({
			url: urlServices + 'confirmSigninForm.php?site=' + siteJeu,
			success: function(data) {
				updateDisplayLayer(data);
				jQuery('#closeInscription').click(closeLayer);
				jQuery('#campaillette-inscription-form').css('background-color', '#533931');
			}
		});
	}

	function displayReglement(el) {
		if(el) {
			jQuery.ajax({
				url: urlServices + 'reglementForm.php?code_jeu=' + configJeu.name + '&site=' + siteJeu,
				success: function(data) {
					updateDisplayLayer(data);

					jQuery("#formLogin").submit(function() {
						s = jQuery(this).serialize();
						jQuery.ajax({
							type: "POST",
							data: s,
							url: jQuery(this).attr("action"),
							success: function(retour){
								if(retour == '') {
									playGame(el);

								} else {
									alert(retour);
								}
							}
						});
						return false;
					});
				}
			});

		}
		
		return	false;
	}
	
	function playGame(el) {

		if(el.name == 'memory') {
			playMemory();
		} else if(el.name == 'question-reponse') {
			
			jQuery.ajax({
				url: configJeu.value + '&ajax=oui',
				success: function(data) {
					jQuery('#flash').html(data);
					setTimeout(function(){initQuestionReponse();}, 500);
//					initQuestionReponse();
				}
			});

		} else {
			window.location	= configJeu.value;
		}
	}

	function	initQuestionReponse() {
		var scrollReponse;

		jQuery('#jeuQuestion .question').hide().find('button').click(
			function() {

				if(jQuery(this).parent('div.question').find('textarea').length == 1 && jQuery.trim(jQuery(this).parent('div.question').find('textarea').val()) == '') {
					alert('La réponse est obligatoire');
					return	false;
				}

				if(jQuery(this).parent('div.question').hide().next().show().length == 0) {
					s = jQuery('#jeuxQuestionnaire').serialize();
					jQuery.ajax({
						type: "POST",
						data: s,
						url: urlServices + 'questionnaire.php?site=' + siteJeu,
						success: function(retour){
							jQuery('#jeuQuestion').html(retour);
						}
					});

				}

				jQuery('#jeuReponse .reponse').hide();
				jQuery('#jeuReponse .' + this.name).show();
				setTimeout(function(){scrollReponse.recalculateLayout();}, 100);

//				alert(this.name);

				return	false;
			}
		).each(

			function(index,el) {
//				index++;
//				console.log('contentScrollReponse_numero' + index, 'scrollbar_track_numero' + index);
//				var scrollReponse = new Control.ScrollBar('contentScrollReponse_numero' + index, 'scrollbar_track_numero' + index);
//				setTimeout(function(){scrollReponse.recalculateLayout();}, 500);
			}

		).end()[0].show();

		jQuery('#jeuReponse .reponse').hide()[0].show();
		
		scrollReponse = new Control.ScrollBar('contentScrollReponse_numero', 'scrollbar_track_numero');
		setTimeout(function(){scrollReponse.recalculateLayout();}, 500);
	}

	function playMemory() {
			var	urlConfig	= "spip.php?page=configMemory&id_rubrique=" + configJeu.className;

			var	flashGame	= new Element('div', {id: 'flashGame'});
			$('flash').update(flashGame);


			var flashvars = {
				urlConfig: jQuery.URLEncode(urlConfig),
				siteId: "site2",
				code_jeu: configJeu.name
			};
			var params = {
				menu: "false",
				scale: "noScale",
				bgColor: "#4c241c",
				allowScriptAccess: 'always',
				align: "middle",
				showMenu: "false",
				wmode:"transparent"
			};

			var attributes = {id: 'website', name:'website', style:'margin: 80px;'};

			swfobject.embedSWF( 'jeu/loader.swf', 'flashGame', '100%', '100%', '9.0.0', 'js/expressinstall.swf', flashvars, params, attributes );
	}

	

var	menuBloc	= Class.create({

	menu	: null,
	layer	: null,
	id		: null,
	el		: null,

	initialize	: function(el, options) {

		this.el		= $(el);
		this.id		= el.title;
		this.menu	= new Element('div');
		this.layer	= new Element('div');

		this.menu.addClassName('menu');
		this.layer.addClassName('layer');

		el.insert(this.menu);
		el.insert(this.layer);
		this.menu.hide();
		this.layer.hide();
		this.layer.setOpacity(0.5);

		el.observe('mouseover', this.show.bind(this));
		el.observe('mouseout', this.hide.bind(this));

		options.items.each(

			function(item) {
				var	menuItem	= new Element('div');
				menuItem.addClassName('menuItem');
				menuItem.insert(item.title);
				this.menu.insert(menuItem);
				menuItem.observe('click', item.fn.bind(this, this.el));
			}.bind(this)

		);

	},

	show	: function() {
//		this.layer.show();
		this.menu.show();
	},

	hide	: function() {
//		this.layer.hide();
		this.menu.hide();
	}


});






/**
 * charge une fiche boulanger
 */
function loadFiche(url) {

    new Ajax.Updater('ficheBoulanger', url,
            {
                method		: 'get',
				onComplete	: initFicheBoulanger
            }
    );

}

/**
 * initialise la fiche boulanger
 */
function initFicheBoulanger() {

	

	var	btnClose		= $$('#ficheBoulanger div.fermer a');

	if(!btnClose[0]) {
		setTimeout(initFicheBoulanger, 100);
	} else {
		spDebug.info('initFicheBoulanger');

		btnClose			= btnClose[0];
		btnClose.onclick	= function() {return false;};

//		alert(btnClose);

		btnClose.observe('click', function(){$('ficheBoulanger').fade({afterUpdate: function(){$('ficheBoulanger').setStyle({zIndex: 90});}});});

	    $('ficheBoulanger').appear({afterUpdate: function(){$('ficheBoulanger').setStyle({zIndex: 90});}});

		initScrollFiche();
		initListes();


			$$('#contenu-pro .images').each(

				function(el) {

					new slideShow(el, {
											auto			: true,
											delayAuto		: 2,
											container		: el.firstDescendant(),	//	l'id de la div contenant la partie visible du slide show
											duration		: 1,			//	la durée de l'effet
											item			: 'itemSlide',		//	la classe permettant d'identifier le nombre de blocs dans le slide show
											nbItemsVisible	: 1,			//	le nombre d'élément visible
											step			: 1,
											offsetMarginX	: 0
									});
				}

			);

	}
}

function initListes() {
	if($('contenu-pro')) {
		$$('#contenu-pro div.liste').each(
			function(blocListe) {

				var	scrollContent	= blocListe.select('.list')[0];
				var	scrollTrack		= blocListe.select('.scrollbar_track_fiche')[0];

				var scrollMention = new Control.ScrollBar(scrollContent.id, scrollTrack.id);

				setTimeout(function(){scrollMention.recalculateLayout();}, 500);

				blocListe.select('.itemListe').each(
					function(el) {
						var	titre			= el.select('div.itemTitre')[0];
						var	action			= null;

						titre.observe('click',
							function(event) {
								
								if(action != true) {
									action	= true;
									Effect.toggle(el.select('div.texteListe')[0], 'slide', {afterFinish: function(){action = null;}, queue: {position: 'end', scope: 'slideListe'}, delay: 0.2, afterUpdate: function(){scrollMention.recalculateLayout();}});
									var	image	= Event.element(event);

									if(image.tagName == 'IMG') {
										image	= image.parentNode;
									}

									if(image.hasClassName('open')) {
										image.removeClassName('open').addClassName('close');
									} else {
										image.removeClassName('close').addClassName('open');
									}

								}
							}
						);
					}
				);

			}
		);

	} else {
		setTimeout(initListes, 500);
	}

}

function initScrollFiche() {

	if($('contenu-pro')) {

		$$('#contenu-pro div.texte').each(

			function(el) {
				var	scrollContent	= el.select('.text')[0];
				var	scrollTrack		= el.select('.scrollbar_track_fiche')[0];
				
				var scrollMention = new Control.ScrollBar(scrollContent.id, scrollTrack.id);

				setTimeout(function(){scrollMention.recalculateLayout();}, 2000);
			}

		);

	} else {
		setTimeout(initScrollFiche, 500);
	}


}

function initSlideShowFiche() {
	
	$$('#contenu-pro .images').each(

		function(el) {

			new slideShow(el, {
									auto			: true,
									delayAuto		: 2,
									container		: el.firstDescendant(),	//	l'id de la div contenant la partie visible du slide show
									duration		: 1,			//	la durée de l'effet
									item			: 'itemSlide',		//	la classe permettant d'identifier le nombre de blocs dans le slide show
									nbItemsVisible	: 1,			//	le nombre d'élément visible
									step			: 1,
									offsetMarginX	: 0
							});
		}

	);

}

/**
 * Comment
 */
function initLiensBoulanger() {

	$$('a.linkFiche').each(
		function(el){
			el.onclick	= function(){return false;};

			el.observe('click',
				function() {
					loadFiche(el.href + '&ajax=oui');
				}.bind(el)
			);
		}
	);
}



