// JavaScript Document

window.addEvent('domready', function(){

	// scroll doux vers les ancres
	new SmoothScroll({ duration:500 }, window);
	
	
	// Centrage pages
	/*var bdy = $(document.body);
	$(window).addEvent('resize', function(e) {
		$clear(timer);
		var timer = (function(){
			var win = $(window).getSize();
			if($('res')) $('res').dispose();
			var res = new Element('div', {
				'styles': {
					'position': 'absolute', 
					'top': 0,
					'left': 0, 
					'width': '50px',
					'height': '20px', 
					'font-size': '14px',
					'border': '1px solid #000', 
					'background-color': '#fff'
				}, 
				'id': 'res'
			}).inject($(document.body)).set('html', win.x);
			if(win.x<1200)  {
				$(document.body).setStyle('position', 'relative');
				if(win.x<980) 	$(window).setStyle('overflow', 'scroll');
				$('fond').setStyles({
					'position': 'absolute', 
					'left': -((1200-win.x)/2)+'px'
				});
			}
			else {
				$('fond').setStyles({
					'position': 'relative', 
					'margin': '0 auto'
				});
			}
			
		}).delay(50);
	});*/

	// FORMULAIRES 
		// VERIFICATION DES CHAMPS REQUIS : CSS CLASSE "verif"
		if( $$('input[type=submit]') ) {	// $('subInscription')
			// verif on click
			$$('input[type=submit]').addEvents({
				'click': function(e){
					var allVar = '';
					var separateur = '- ';
					
					var lang = ($('locale'))? $('locale').get('lang') : 'en';
					if(lang=='fr') {
						var txtReponse = '• Les champs suivants doivent être renseignés : ' + "\n\n";
					}
					else /*if(lang=='en')*/ {
						var txtReponse = '• Fields required : ' + "\n\n";
					}
					
					var thisForm = this.getParent('form');	//alert( thisForm.get('id') );
					var oldColor = '#444';
	
					// Vérif
					thisForm.getElements( '.verif' ).each(function(champ) {
						if(champ.get('value').length==0) {
							if(champ.getPrevious('label')){
								var monLabel = champ.getPrevious('label'); //alert(monLabel.get('text'));
								monLabel.setStyles( {'color': '#ff0000'} );
								var texte = monLabel.get('text').replace('*', '');
							}
							else { var texte = champ.get('id'); }
							
							allVar += separateur + texte + "\n";
						}
						else {
							if(champ.getPrevious('label')){
								var monLabel = champ.getPrevious('label'); //alert(monLabel.get('text'));
								monLabel.setStyles( {'color': oldColor} );
								//monLabel.set('text', monLabel.get('text').replace('*', ''));
							}
						}
					});
					

					// Bis - utilisations multiples par form (deux par deux bien sûr)
						var bis = thisForm.getElements( '.bis' );
						var nbBis = bis.length;
						var cpt = 0;
						for(var i=0; i<nbBis; i++) {
							//var pair = (i%2==0)? true : false;
							if(i%2==0){
								if( bis[i].get('value') != bis[i+1].get('value')){
									var first = bis[i].getPrevious('label').get('text');
									if(lang=='fr') { allVar += "\n" + '• Vous devez confirmer : ' + first + "\n"; }
									else { allVar += "\n" + '• You must confirm : ' + first + "\n"; }
									var monLabel1 = bis[i].getPrevious('label');
									monLabel1.setStyles( {'color': '#ff0000'} );
									var monLabel2 = bis[i+1].getPrevious('label');
									monLabel2.setStyles( {'color': '#ff0000'} );
								}
								else {
									allVar += '';
									var monLabel1 = bis[i].getPrevious('label');
									monLabel1.setStyles( {'color': oldColor} );
									var monLabel2 = bis[i+1].getPrevious('label');
									monLabel2.setStyles( {'color': oldColor} );
								}
							}
						}

					
					// e-mail
					if(thisForm.getElement( '.mail' )){
						var email = thisForm.getElement( '.mail' );
						var mail = email.get('value');
						var filter = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
						if (!filter.test(mail)) {
							if(lang=='fr') { allVar += "\n" + '• Vous devez entrer un email valide' + "\n"; }
							else { allVar += "\n" + '• You must enter a valid e-mail' + "\n"; }
							var mailLabel = email.getPrevious('label');
							mailLabel.setStyles( {'color': '#ff0000'} );
							email.focus();
						}
					}
					
					
					// pass
					if(thisForm.getElement( '.pass' )){
						var pass = thisForm.getElement('.pass');
						var passv = pass.get('value');
						if (passv.length<8) {
							if(lang=='fr') { allVar += "\n" + '• Votre mot de passe doit contenir au moins 8 caractères' + "\n"; }
							else { allVar += "\n" + '• Your password must contain at least 8 characters' + "\n"; }
							var passLabel = pass.getPrevious('label');
							passLabel.setStyles( {'color': '#ff0000'} );
							pass.focus();
						}
					}
					
					// pass edit mode
					if(thisForm.getElement( '.passe' )){
						var pass = thisForm.getElement('.passe');
						var passv = pass.get('value');
						if (passv.length>0 && passv.length<8) {
							if(lang=='fr') { allVar += "\n" + '• Votre mot de passe doit contenir au moins 8 caractères' + "\n"; }
							else { allVar += "\n" + '• Your password must contain at least 8 characters' + "\n"; }
							var passLabel = pass.getPrevious('label');
							passLabel.setStyles( {'color': '#ff0000'} );
							pass.focus();
						}
					}
					
					// ANALYSE FORM
					if(allVar.length!=0) {
						alert(txtReponse + allVar);
						return false;
					}
					else {
						return true;
					}
				}
			});
	
	
			// prevent forms to be submitted on "enter" key press
			/*$$('input', 'select').addEvent('keydown', function (event) {
				if (event.key=="enter") {
					event.preventDefault();
					var Tag = this.get('tag');
					if(this.getNext(Tag)) this.getNext(Tag).focus();
					else this.focus();
				}
				if ( (event.key=="enter" && event.shift) || (event.key=="enter" && event.ctrlKey ) ) {
					event.preventDefault();
					var Tag = this.get('tag');
					if(this.getPrevious(Tag)) this.getPrevious(Tag).focus();
					else this.focus();
				}
			});*/
		}
	
	
	// FONCTIONS 
		// Transforme un select en input si on choisis 'autre' 
		goInput = function(el) {
			var valType = el.get('value'); var valId = el.get('id'); var valName = el.get('name'); var valClass = el.get('class'); //alert(valType);
			if(valType=='autre'){
				var monLabel = el.getPrevious('label');
				var optionText = el.getFirst().get('text');
				var selectContent = el.get('html');
				
				el.destroy();
				var newInput = new Element('input', {
					'type': 'text', 
					'id': valId, 
					'name': valName, 
					'class': valClass + ' fl' 
				});
				newInput.inject(monLabel, 'after');
				
				var trigger = new Element('a', {
					'href': '#', 
					'style': 'margin-left:5px;',
					'class': 'reset_input tip fl', 
					'html': '<img src="images/arrow_undo.png" title="reset" />'
				});
				trigger.inject(newInput, 'after');
				
				trigger.addEvents({
					'click': function(e) {
						e.stop();
						trigger.getPrevious('input').destroy();
						trigger.destroy();
						var oldSelect = new Element('select', { 'id': valId, 'name': valName, 'class': valClass, 'onchange': 'goInput(this);'});
						oldSelect.inject(monLabel, 'after');
						oldSelect.adopt(new Element('option').set('text', optionText));
						oldSelect.set('html', selectContent);
						
					}
				});
			}
		}

		
		// TIPS : BULLE D'AIDE
		var tips = function() {
			if($$('.tip')) {
				$$('.tip').each(function(element,index) { 
					//var content = element.get('title').split('::'); 
					//element.store('tip:title', content[0]); 
					//element.store('tip:text', ''); 
					var content = element.get('title'); 
					element.store('tip:title', content); 
					element.store('tip:text', ''); 
				});
				var tipz = new Tips('.tip',{
					className: 'tip_css',
					fixed: false,
					hideDelay: 500,
					showDelay: 500
				});
			}
		}
		
		var tips2 = function() {	// pour result ajax
			if($$('.tip2')) {
				$$('.tip2').each(function(element,index) { 
					var content = element.get('title'); 
					element.store('tip:title', content); 
					element.store('tip:text', ''); 
				});
				var tipz2 = new Tips('.tip2',{
					className: 'tip_css',
					fixed: false,
					hideDelay: 0,
					showDelay: 0
				});
			}
		}
		
		// agenda
		var getCommunes = function() {
			if($('comm')) {
				var inputWord = $('comm');
			 
				new Autocompleter.Request.HTML(inputWord, 'content/agenda/get_communes.php', {
					'indicatorClass': 'autocompleter-loading',
					'postData': {
						'extended': '1' // send additional POST data, check the PHP code
					},
					'injectChoice': function(choice) {					// choice is one <li> element
						var text = choice.getFirst();					// the first element in this <li> is the <span> with the text
						var value = text.innerHTML;						// inputValue saves value of the element for later selection
						choice.inputValue = value;						// overrides the html with the marked query value (wrapped in a <span>)
						text.set('html', this.markQueryValue(value));	// add the mouse events to the <li> element
						this.addChoiceEvents(choice);
					}
				});
			}
		}
		
		var getDates = function() {
			if($('date')) {
				var inputWord = $('date');
			 
				new Autocompleter.Request.HTML(inputWord, 'content/agenda/get_dates.php', {
					'indicatorClass': 'autocompleter-loading',
					'postData': {
						'extended': '1' // send additional POST data, check the PHP code
					},
					'injectChoice': function(choice) {					// choice is one <li> element
						var text = choice.getFirst();					// the first element in this <li> is the <span> with the text
						var value = text.innerHTML;						// inputValue saves value of the element for later selection
						choice.inputValue = value;						// overrides the html with the marked query value (wrapped in a <span>)
						text.set('html', this.markQueryValue(value));	// add the mouse events to the <li> element
						this.addChoiceEvents(choice);
					}
				});
			}
		}
		
		//DETAIL EVENEMENTS
		var getDetails = function() {
			if($$('.more_arch_zoom')) {
		
				$$('.more_arch_zoom').addEvent('click', function(e) {
					e.stop();
					var ev = this.get('id');
					var couleur = this.get('rel');
					var up;
					if($('expo_resp')) up = 'expo_resp';
					else if($('ag_resp')) up = 'ag_resp';
						 else if($('oep_resp'))  up = 'oep_resp';
						 	  else  if($('sed_resp'))  up = 'sed_resp';
					var getExpos = new Request.HTML({
						method: 'post', 
						url: 'content/get_details.php', 
						data : { 'ev': ev, 'couleur': couleur },
						update: $(up), 
						evalScripts: true, 
						onRequest: function() {
							$(up).set('html', '<div style="text-align:center; margin:20px 0;"><img src="images/ajax-loader.gif" alt="computing" /></div>');
						},
						onComplete: function(response) {
							$(up).setStyles({'width':'578px', 'padding':'0'});
							$('expo_res_rech_cw').highlight();
						}
					}).send();

				});
			}
		}
		
		// expositions
		var searchExpoCom = function() {
			var commune = $('exp_com').get('value');
			commune = (commune=="") ? "Toutes" : commune;
			var getExpos = new Request.HTML({
				method: 'post', 
				url: 'content/expos/get_expos.php', 
				data : { 'commune': commune	},
				update: $('expo_resp'), 
				evalScripts: true, 
				onComplete: function(response) {
					$('expo_resp').setStyles({'width':'578px', 'padding':'0'});
					$('exp_com').set('value', '');
					$('expo_res_rech_expo').highlight('#885B89');
				}
			}).send();
		}
		var getExpoCom = function() {
			if($('exp_com')) {
				var inputWord = $('exp_com');
			 
				new Autocompleter.Request.HTML(inputWord, 'content/agenda/get_communes.php', {
					'indicatorClass': 'autocompleter-loading',
					'postData': {
						'extended': '1' // send additional POST data, check the PHP code
					},
					'injectChoice': function(choice) {					// choice is one <li> element
						var text = choice.getFirst();					// the first element in this <li> is the <span> with the text
						var value = text.innerHTML;						// inputValue saves value of the element for later selection
						choice.inputValue = value;						// overrides the html with the marked query value (wrapped in a <span>)
						text.set('html', this.markQueryValue(value));	// add the mouse events to the <li> element
						this.addChoiceEvents(choice);
					}
				});
				$('exp_com').addEvent('keyup', function(event) {
					document.title = 'Expositions à ' + $('exp_com').get('value') + ' - Journal Farandole';
					if (event.key=="enter") {
						event.preventDefault();
						window.location.href='#top';
						searchExpoCom();
					}
				});
				$('exp_com_ok').addEvent('click', function(e) {
					document.title = 'Expositions à ' + $('exp_com').get('value') + ' - Journal Farandole';
					searchExpoCom();
				});
			}
		}
		
		//on en parle
		var searchOepCom = function() {
			var commune = $('oep_com').get('value');
			commune = (commune=="") ? "Toutes" : commune;
			var getExpos = new Request.HTML({
				method: 'post', 
				url: 'content/oep/get_oep.php', 
				data : { 'commune': commune	},
				update: $('oep_resp'), 
				evalScripts: true, 
				onComplete: function(response) {
					$('oep_resp').setStyles({'width':'578px', 'padding':'0'});
					$('oep_com').set('value', '');
					$('expo_res_rech_oep').highlight('#3A8735');
				}
			}).send();
		}
		var getOepCom = function() {
			if($('oep_com')) {
				var inputWord = $('oep_com');
			 
				new Autocompleter.Request.HTML(inputWord, 'content/agenda/get_communes.php', {
					'indicatorClass': 'autocompleter-loading',
					'postData': {
						'extended': '1' // send additional POST data, check the PHP code
					},
					'injectChoice': function(choice) {					// choice is one <li> element
						var text = choice.getFirst();					// the first element in this <li> is the <span> with the text
						var value = text.innerHTML;						// inputValue saves value of the element for later selection
						choice.inputValue = value;						// overrides the html with the marked query value (wrapped in a <span>)
						text.set('html', this.markQueryValue(value));	// add the mouse events to the <li> element
						this.addChoiceEvents(choice);
					}
				});
				
				$('oep_com').addEvent('keyup', function(event) {
					document.title = 'On en parle à ' + $('oep_com').get('value') + ' - Journal Farandole';
					if (event.key=="enter") {
						event.preventDefault();
						window.location.href='#top';
						searchOepCom();
					}
				});
				$('oep_com_ok').addEvent('click', function(e) {
					document.title = 'On en parle à ' + $('oep_com').get('value') + ' - Journal Farandole';
					searchOepCom(); 
				});
			}
		}
		
	
		//stages et découvertes
		var searchSedCom = function() {
			var commune = $('sed_com').get('value');
			commune = (commune=="") ? "Toutes" : commune;
			var getExpos = new Request.HTML({
				method: 'post', 
				url: 'content/sed/get_sed.php', 
				data : { 'commune': commune	},
				update: $('sed_resp'), 
				evalScripts: true, 
				onComplete: function(response) {
					$('sed_resp').setStyles({'width':'578px', 'padding':'0'});
					$('sed_com').set('value', '');
					$('expo_res_rech_sed').highlight('#AE1F48');
				}
			}).send();
		}
		var getSedCom = function() {
			if($('sed_com')) {
				var inputWord = $('sed_com');
				new Autocompleter.Request.HTML(inputWord, 'content/agenda/get_communes.php', {
					'indicatorClass': 'autocompleter-loading',
					'postData': {
						'extended': '1' // send additional POST data, check the PHP code
					},
					'injectChoice': function(choice) {					// choice is one <li> element
						var text = choice.getFirst();					// the first element in this <li> is the <span> with the text
						var value = text.innerHTML;						// inputValue saves value of the element for later selection
						choice.inputValue = value;						// overrides the html with the marked query value (wrapped in a <span>)
						text.set('html', this.markQueryValue(value));	// add the mouse events to the <li> element
						this.addChoiceEvents(choice);
					}
				});
				$('sed_com').addEvent('keyup', function(event) {
					document.title = 'Stages et découvertes à ' + $('sed_com').get('value') + ' - Journal Farandole';
					if (event.key=="enter") {
						event.preventDefault();
						window.location.href='#top';
						searchSedCom();
					}
				});
				$('sed_com_ok').addEvent('click', function(e) { 
					document.title = 'Stages et découvertes à ' + $('sed_com').get('value') + ' - Journal Farandole';
					searchSedCom(); 
				});
			}
		}
		
		//agenda
		var searchEvt = function() {
			var commune = $('comm').get('value');
			commune = (commune=="") ? "Toutes" : commune;
			commune = (commune=='Rechercher une commune') ? '' : commune;
			
			var today = new Date();
			var jour = (today.getDate()<10)? '0'+today.getDate() : today.getDate();
			var mois = ((today.getMonth()+1)<10)? '0'+(today.getMonth()+1) : (today.getMonth()+1);
			var annee = today.getFullYear();
			var date = $('date').get('value');
			var ap;
			if($('ap').checked) ap='1';
			else ap='2';
			var getExpos = new Request.HTML({
				method: 'post', 
				url: 'content/agenda/get_agenda.php', 
				data : { 'commune': commune, 'date' : date, 'ap' : ap},
				update: $('ag_resp'), 
				evalScripts: true, 
				onRequest: function() {
					$('computing').set('html', '<img src="images/ajax-loader.gif" alt="computing" />');
					new SmoothScroll({ duration:500 }, window);
					$('ag_resp').set('html', '<div style="text-align:center; margin:20px 0;"><img src="images/ajax-loader.gif" alt="computing" /></div>');
				},
				onComplete: function(response) {
					$('ag_resp').setStyles({'width':'578px', 'padding':'0'});
					$('computing').set('html', '');
					$('expo_res_rech_aj').highlight('#CE151B');
					$$('.autocompleter-choices').setStyle('display', 'none');
				}
			}).send();
			//var date = annee + '-' + mois + '-' + jour;
			//var dateFr =  jour+ '-' + mois + '-' + annee;
			//date = ($('date').get('value').length!=0)? $('date').get('value') : date;
			//$('date').getNext('input[type=text]').set('value', dateFr);
		}
		
		var getAgCom = function() {
			if($('comm') && $('date')) {
				$('ag_com_ok').addEvent('click', function(e) { 
					e.stop(); searchEvt(); 
					document.title = 'Évènements à ' + $('comm').get('value') + ' - Journal Farandole';
				});
				$('comm').addEvent('keypress', function(event) {
					document.title = 'Évènements à ' + $('comm').get('value') + ' - Journal Farandole';
					if('enter'==event.key || event.enter || 13==event.keyCode) {
						event.preventDefault();
						window.location.href='#top';
						searchEvt();
					}
				});
			}
		}
		
		var goTop = function(lien) {
			var lk = $(lien);
			lk.addEvent('click', function(e) {
				e.stop();
			});
		}
		
		// Datepicker
		if($$('.demo_jqui')) {
			// aujourd'hui
			var date = new Date();
			//var minDate = date.getFullYear() + '-' + (((date.getMonth()+1)<10) ? '0'+(date.getMonth()+1) : (date.getMonth()+1)) + '-' + ((date.getDate()<10) ? '0'+date.getDate() : date.getDate());
			new DatePicker('.demo_jqui', {
				allowEmpty: false, 
				pickerClass: 'datepicker_jqui', 
				timePicker: false, 
				format: 'd-m-Y', /* format: 'Y-m-d H:i', */
				inputOutputFormat: 'Y-m-d',	/* 'Y-m-d H:i' */
				positionOffset: { x: 0, y: 5 }, 
				//minDate: { date: minDate, format: 'Y-m-d' }, 
				days : ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
				months : ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre']
			});
			//$('date').set('value', minDate);
		}
		
		
		//cpteur clic
		if($$('.cpt_clic')) {
		
				$$('.cpt_clic').addEvent('click', function(e) {
					var pb = this.get('id');
					var cptClic = new Request.HTML({
						method: 'post', 
						url: 'content/cpt_clic.php', 
						data : { 'pb': pb	},
						evalScripts: true
					}).send();
				});
		}
		
		// Redirection liens page accueil
		var agendaGo = function() {
			$$('.dsp_suite').each(function(item, index) {
				item.addEvent('click', function(e) {
					e.stop();
					var id = item.get('rel');
					var getAgenda = new Request.HTML({
						method: 'post', 
						url: 'content/agenda/get_agenda_article.php', 
						data : { 'id': id},
						update: $('ag_resp'), 
						evalScripts: true, 
						onComplete: function(response) {
							$('ag_resp').setStyles({'width':'578px', 'padding':'0'});
							window.location.href = '#top';
							tips2();
						}
					}).send();
				});
			});
		}
		
		
		
	// ACTIONS
		// tips
		tips();
		getCommunes();
		getExpoCom();
		getOepCom();
		getSedCom();
		getDetails();
		getAgCom();
		if($$('.dsp_suite')) agendaGo();
		if($('hdp')) goTop('hdp');
		
		var box = {};
		box = new multiBox('mb', {useOverlay: false});
}); // fin domready
