var initPage = function(){
	// FONCTIONS COMMUNES
	RollOverImage();
	focusInput();
	menuDHTML();
	
	/* HOME */
	if($('home')){
		if($('ss')){
			var ss = new slideShow('ss','cont_ss','item',{
				slideAutostart : true,
				slideDuree:1,
				slideTempo: 7
			});
		}
		autocompletUE();
		initCarte();	
	}
	
	/*SLIDER ALTERNANCE*/
	if($('decouvrir')){
		if($('alt')){
			var alt = new slideShow('alt','diapo','bloc_bg',{
				slideAutostart : true,
				slideDuree:1,
				slideTempo: 4,
			});
		}
	}
	
	if($$('.pagination form').length>0){
		$$('.pagination form select').each(function(e,i){
			e.observe('change',function(){
				e.up('form').submit();							
			});
		});
	}
	
	/* ENTREPRISES : FORMATIONS */
	if($('formations_entreprise')){
		$$('#formations_entreprise .recherche .onglet a').each(function(e,i){
			e.observe('click',function(event){
				$$('#formations_entreprise .recherche .onglet a').each(function(e2){
					e2.removeClassName('on');
				});
				e.addClassName('on');
				$$('#formations_entreprise .recherche .f .liste').each(function(e2){
					e2.hide();
				});
				$(e.hash.substr(1)).show();
				event.stop();
			});
		});
		$$('#formations_entreprise .resultats tr').each(function(e,i){
			e.observe('mouseenter',function(){
				e.addClassName('hover');					   
			});
			e.observe('mouseleave',function(){
				e.removeClassName('hover');
			});
		});
	}

	/* PARTICULIER : RECHERCHE */
	if($('formations_particulier')){
		$$('#formations_particulier .resultats tr').each(function(e,i){
			e.observe('mouseenter',function(){
				e.addClassName('hover');					   
			});
			e.observe('mouseleave',function(){
				e.removeClassName('hover');
			});
		});
	}

	/* PARTICULIER : FORMATION */
	if($('formation_particulier')){
		etatBtOnglet(0);
		$$('#formation_particulier .formation .onglet a').each(function(e,i){
			e.observe('click',function(event){
				$$('#formation_particulier .formation .onglet a').each(function(e2){
					e2.removeClassName('on');
				});
				e.addClassName('on');
				$$('#formation_particulier .formation .cont_onglet').each(function(e2){
					e2.hide();
				});
				$(e.hash.substr(1)).show();
				etatBtOnglet(i);
				event.stop();
			});
		});
		$$('#formation_particulier .ue .filtres a').each(function(e,i){
			e.observe('click',function(event){
				$$('#formation_particulier .ue .filtres a').each(function(e2){
					e2.removeClassName('on');
				});
				e.addClassName('on');
				$$('#formation_particulier .ue table').each(function(e2){
					e2.hide();
				});
				$(e.hash.substr(1)).show();
				event.stop();
			});
		});		
		$$('#formation_particulier .ue tr').each(function(e,i){
			e.observe('mouseenter',function(){
				e.addClassName('hover');					   
			});
			e.observe('mouseleave',function(){
				e.removeClassName('hover');
			});
		});
	}

	/* FORM CONSEILLER */
	if($('frm_conseiller')){
		$('bt_demande').observe('click',function(event){
			$('msgGlobal').hide();
			$('confirmation1').hide();
			$('frm_conseiller').show();
			event.stop();
		});
		$('frm_conseiller').observe('submit',function(event){
			param_form = {
				mep: 'msg_global',
				autoScroll: false,
				action: 'submit'				
			};
			champs_form = {
				nom_conseiller: {alerte:'Votre nom est obligatoire.'}
			};
			if($F('email_conseiller') == '' && $F('tel_conseiller') == ''){
				champs_form['email_conseiller'] = {type:'mel',alerte:'Votre email ou t&eacute;l&eacute;phone est obligatoire.'};
				champs_form['tel_conseiller'] = {alerte:''};
			}else if($F('email_conseiller') != ''){
				champs_form['email_conseiller'] = {type:'mel',alerte:'Votre email n\'est pas valide.'};
				$('tel_conseiller').removeClassName('inputError');
			}else if($F('tel_conseiller') != ''){
				champs_form['tel_conseiller'] = {alerte:'Votre t&eacute;l&eacute;phone est obligatoire.'};
				$('email_conseiller').removeClassName('inputError');
			}else{
				$('tel_conseiller').removeClassName('inputError');
				$('email_conseiller').removeClassName('inputError');
			}
			var res = formVerif('frm_conseiller', champs_form, param_form);
			if(res == false){
				formVerif('frm_conseiller', champs_form, param_form);
				event.stop();
			}else{
				new Ajax.Request('_ajax.php?ACT=conseiller',{
					onComplete : function(cb){
						if(cb.responseText == 'true'){
							$('frm_conseiller').hide();
							$('confirmation1').show();
						}
					}
				});
				event.stop();
			}
		});
	}
	if($('frm_contact')){
		$('bt_tous_contacts').observe('click',function(event){
			var url = $('bt_tous_contacts').href;
			var ib = new infoBox(url,{
				BoxdomNode:'infoNode',
				BoxSrcFermer:'./images/infoBox/infobox_bt_fermer.gif',
				BoxAltFermer:'Fermer',
				BoxCallback:'RollOverImage()'
			});
			ib.ouvrir();
			event.stop();
		});		
		$('bt_recherche').observe('click',function(event){
			$('cbContact').hide();
			$('confirmation2').hide();
			$('frm_contact').show();
			event.stop();
		});
		$('frm_contact').observe('submit',function(event){
			param_form = {
				mep: 'msg_global',
				autoScroll: false,
				action: 'submit'				
			};
			champs_form = {
				cp_contact: {alerte:'Votre nom est obligatoire.'}
			};
			opt = {
				idMsgGlobal : 'cbContact'	
			}
			var res = formVerif('frm_contact', champs_form, param_form,opt);
			if(res == false){
				formVerif('frm_contact', champs_form, param_form,opt);
				event.stop();
			}else{
				new Ajax.Request('_ajax.php?ACT=contact',{
					onComplete : function(cb){
						data = cb.responseJSON;
						if(data != ''){
							$('frm_contact').hide();
							var tpl = '';
							tpl+='<h3>'+data.nom+'</h3>';
							tpl+='<p class="departement">département : '+data.departement+'</p>';
							tpl+='<p class="tel">'+data.tel+'</p>';
							tpl+='<p class="email"><a href="mailto:'+data.email+'">'+data.nom+'</a></p>';
							$('cont_confirmation2').update(tpl);
							$('confirmation2').show();
						}
					}
				});
				event.stop();
			}
		});
	}
	
};

/* FONCTIONS */
var etatBtOnglet = function(pos){
	courant = pos;
	if(courant != 0){
		$('onglet_precedent').update($$('#formation_particulier .formation .onglet a')[courant-1].innerHTML);
		$('onglet_precedent').href = $$('#formation_particulier .formation .onglet a')[courant-1].href;
		$('onglet_precedent').show();
	}else{
		$('onglet_precedent').hide();
	}
	if(courant != $$('#formation_particulier .formation .onglet a').length-1){
		$('onglet_suivant').update($$('#formation_particulier .formation .onglet a')[courant+1].innerHTML);
		$('onglet_suivant').href = $$('#formation_particulier .formation .onglet a')[courant+1].href;
		$('onglet_suivant').show();
	}else{
		$('onglet_suivant').hide();
	}
	$$('.nav_onglet a').each(function(e,i){
		e.stopObserving('click');
		e.observe('click',function(event){
			$$('#formation_particulier .formation .onglet a').each(function(a){
				a.removeClassName('on');
			});
			if(e.hasClassName('suivant') == true){
				$$('#formation_particulier .formation .onglet a')[courant+1].addClassName('on');
			}else{
				$$('#formation_particulier .formation .onglet a')[courant-1].addClassName('on');

			}
			$$('#formation_particulier .formation .cont_onglet').each(function(e2){
				e2.hide();
			});
			$(e.hash.substr(1)).show();
			if(e.hasClassName('suivant') == true){
				etatBtOnglet(courant+1);
			}else{
				etatBtOnglet(courant-1);
			}
			event.stop();
		});
	});
};

var initCarte = function(){
	new Ajax.Request('cnam/_ajax.php?ACT=carte1',{
		parameters : {},
		onComplete : function(transport){
			var data = transport.responseJSON;
			$$('body')[0].insert({top:'<div id="etiquette" display:none;></div>'});
			$$('#mapCarte area').each(function(e){
				Event.observe(e,'mouseout',function(){
					Event.stopObserving(document,'mousemove',coordMouse);
					pX=0;
					pY=0;
					$('etiquette').hide();
				});
				Event.observe(e,'mouseover',function(){
					$('etiquette').show();
					var tpl = '';
					tpl+= '<h4>'+e.alt.substr(5)+'</h4>';
					data[e.hash.substr(1)].each(function(centre,i){
						tpl+='<p>'+centre+'</p>';								 
					});
					$('etiquette').update(tpl);
					Event.observe(document,'mousemove',coordMouse);				
				});
				e.stopObserving('click');
				e.observe('click',function(event){
					carteGmap(e.hash.substr(1));
					event.stop();
				});
			});
		}
	});
	$('bt_autre_recherche').observe('click',function(event){
		$('liste').update('');
		$('carte1').show();
		$('recherche_carte').show();
		$('resultat_carte').hide();
		event.stop();
	});
	$('frm_centre').observe('submit',function(event){
		tab_param = $('frm_centre').serialize(true);
		if(tab_param.cp_centre != '' && tab_param.localisation_centre != ''){
			carteGmap(tab_param.cp_centre,tab_param.localisation_centre);
		}
		event.stop();										  
	});
};

var map;
var baseIcon = new GIcon(G_DEFAULT_ICON);

var carteGmap = function(id,type){
	baseIcon.iconSize = new GSize(20,30);
	baseIcon.shadow = 'images/commun/ombre.png';
	baseIcon.shadowSize = new GSize(0,0);
	baseIcon.iconAnchor = new GPoint(10,15);
	baseIcon.infoWindowAnchor = new GPoint(0, 0);
	new Ajax.Request('cnam/_ajax.php?ACT=carte2&cp='+id+'&type='+type,{
		parameters: {id : id},
		onComplete: function(transport){
			$('carte1').hide();
			tab_point = transport.responseText.evalJSON();
			if(tab_point.size()>1)
			{
				map = new GMap2($("gmap"));
				map.clearOverlays();
				map.enableScrollWheelZoom();
				creerPoint();
				$('recherche_carte').hide();
				$('carte3').hide();
				$('carte2').show();
				$('resultat_carte').show();
				if(!type)
				{
					$('message_resultat').update('Vous cherchez un centre du <span>'+id+'</span>');
				}
				else
				{
					tab_type={
						1 : 'domicile',
						2 : 'travail'
					};
					$('message_resultat').update('Vous cherchez un centre proche du <span>'+id+'</span>, code postal de votre <span>'+tab_type[type]+'</span>');
				}
				$('message_resultat').show();
			}
			else
			{
				$('recherche_carte').hide();
				$('message_resultat').hide();
				$('carte2').hide();
				$('carte3').show();
				$('erreur_cp').update('<span>'+id+'</span> ne correspond &agrave; aucun code postal ou d&eacute;partement d\'Ile de France !<br><br> Si votre recherche concerne un centre Cnam hors de l\'Ile de France, <br><a href="http://region.cnam.fr">consultez les coordonnées des centres r&eacute;gionaux sur  http://region.cnam.fr</a>');
				$('erreur_cp').show();
				$('resultat_carte').show();
			}
			map = new GMap2($("gmap"));
			map.clearOverlays();
			map.enableScrollWheelZoom();
			creerPoint();
			
		}
	});
	return id;
}
var centrerCarte = function(){
	var sw = new GLatLng(calculCoord('lat_min'), calculCoord('lng_min'));
	var ne = new GLatLng(calculCoord('lat_max'), calculCoord('lng_max'));
	var bounds = new GLatLngBounds(sw, ne);
	level = map.getBoundsZoomLevel(bounds)-1;
	map.setCenter(new GLatLng(calculCoord('lat_moy'), calculCoord('lng_moy')), level);	
};
var tri_nombres = function(a,b){
	return a-b;
};
var calculCoord = function(calcul){
	var lat_min = parseFloat(tab_lat.sort(tri_nombres).first());
	var lat_max = parseFloat(tab_lat.sort(tri_nombres).last());
	var lng_min = parseFloat(tab_lng.sort(tri_nombres).first());
	var lng_max = parseFloat(tab_lng.sort(tri_nombres).last());
	
	if(calcul=='lat_moy'){return (lat_min+lat_max)/2;}
	if(calcul=='lng_moy'){return (lng_min+lng_max)/2;}
	if(calcul=='lat_min'){return lat_min;}
	if(calcul=='lat_max'){return lat_max;}
	if(calcul=='lng_min'){return lng_min;}
	if(calcul=='lng_max'){return lng_max;}
};
var creerPoint = function(){
	$('liste').update('');
	tab_lat = new Array();
	tab_lng = new Array();
	tab_point.each( function(e,i){
		if(e.lat != 0 && e.lng != 0){
			var point = new GLatLng(e.lat,e.lng);
			map.addOverlay(createMarker(point, i));
			tab_lat.push(e.lat);
			tab_lng.push(e.lng);
			
			tpl = '<div class="item">';
			tpl+= '		<div class="f_item'+parseInt(i+1)+'">';
			tpl+= '			<h2>'+e.nom+'</h2>';
			tpl+= '			<p class="adresse">'+e.adresse+'</p>';
			tpl+= '			<p class="tel">T&egrave;l : '+e.tel+'</p>';
			tpl+= '			<p class="info">'+e.info+'</p>';
			tpl+= '			<a href="http://'+e.url+'" class="lien">Site internet du centre</a>';
			tpl+= '		</div>';
			tpl+= '</div>';
			$('liste').insert({bottom:tpl});
		}
	});
	centrerCarte();
};
var createMarker = function(point,i) {
	var IconType = new GIcon(baseIcon);
	IconType.image = 'cnam/images/commun/marker'+parseInt(i+1)+'.png';
	markerOptions = {
		clickable : false,
		icon:IconType
	};
	var marker = new GMarker(point, markerOptions);
	return marker;
};
var coordMouse = function(e){
	pX = Event.pointerX(e);
	pY = Event.pointerY(e)-30;
	w = $('etiquette').getWidth()/2;
	h = $('etiquette').getHeight()-20;
	$('etiquette').setStyle({display:'block', top:pY-h+'px', left:pX-w+'px'});
};

/* MENU */
var menuDHTML = function(){
	$$('.menu .dhtml').each(function(e){
		var li = e.up('li');
		e.setStyle({
			top : '40px'
		});
		e.hide();
		var img = e.previous('a').down('img');
		var imgSrc = img.src;
		var imgSep = imgSrc.lastIndexOf('.');		
		
		li.observe('mouseover', function(){
			if (!imgSrc.substring(0,imgSep).endsWith('_on')) img.src = imgSrc.substring(0,imgSep)+'_on'+imgSrc.substring(imgSep);	
		});
		li.observe('mouseout', function(){
			if (!imgSrc.substring(0,imgSep).endsWith('_on')) img.src = imgSrc.substring(0,imgSep)+''+imgSrc.substring(imgSep);			
		});	
		li.observe('mouseenter', function(){
			e.show();			
		});
		li.observe('mouseleave', function(){
			e.hide();
		});			
	});
};

var autocompletUE = function(){

new Autocompleter.Local('reque', 'ue_list', UeList, {});
};
