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

//switch les formulaires de recherches
function switchDirectory(el)
{
  var form_reverse_block = $("search_form_reverse_block") ;
  var form_normal_block = $("search_form_normal_block") ;

  if(form_normal_block.getStyle("display") == "block")
  {
    form_normal_block.setStyle({display:"none"}) ;
    form_reverse_block.setStyle({display:"block"}) ;
    el.innerHTML = "Annuaire" ;
  }else
  {
    form_normal_block.setStyle({display:"block"}) ;
    form_reverse_block.setStyle({display:"none"}) ;
    el.innerHTML = "Annuaire Inversé" ;
  }
}

/******************************************************************************/
/* GMap                                                                       */
/******************************************************************************/
  function showMap(link,name,address,thumbnail)
  {
    var gmapsrc = '/inc/gmap.php?name=' + name + '&address=' + address + '&thumburi=' + thumbnail ;
    //var gmapsrc = 'http://spiritualmind.free.fr' ;
    return hs.htmlExpand(link, { objectType: 'iframe', src: gmapsrc, contentId: 'gmap_box'} );
  }

  function showDirections(link,name,address,thumbnail)
  {
    var gdirectionssrc = '/inc/gdirections.php?name=' + name + '&address=' + address + '&thumburi=' + thumbnail ;
    return hs.htmlExpand(link, { objectType: 'iframe', src: gdirectionssrc, contentId: 'gdirections_box'} );
  }

/*******************************************************************************
 * City_zipcode autocompleter
 ******************************************************************************/

var city_zipcode_selected = false ;
var city_zipcode_buffer = "" ;

/**
 * Callback function called after the element in the autocompleter list has been
 * updated
 * @param {Object} input input type text
 * @param {Object} li  li from the unordered list
 */
 function setSelectedCityZipcode(input, li){
  city_zipcode_selected = true ;
  city_zipcode_buffer = li.title ;
  input.value = li.title ;
  $("idse_search_btn").focus() ;
 }

 function blurCityZipcodeField(input){
  if(!city_zipcode_selected
     ||
     (city_zipcode_selected && input.value != city_zipcode_buffer))
  input.value = "" ;
 }

 function blurActivityField(input){
  //no needed by this directory
 }

 function forceBlur(){
    blurCityZipcodeField($("city_zipcode"))
    return true;
}

/*******************************************************************************
 * Activity autocompleter
 ******************************************************************************/

var activity_selected = false ;
var activity_buffer = "" ;
function setSelectedActivity(input, li){
  activity_selected = true ;
  activity_buffer = li.title ;
	var hash = li.id.split("_") ;
  input.value = li.title ;
  $("id_activity").value = hash[1] ;
}

function resetIdActivity()
{
  $("id_activity").value="" ;
}


/* METEO MAP SWITCHER */
function switchMeteoImage(to_active,to_desactive){
	$(to_active).style.display = "inline";
	$(to_desactive).style.display = "none";
}

/* GESTION ERGONOMIQUE DES CHAMPS DE FORMUlAIRES
 *efface la valeur d'un input text au click de la souris
 utilisation :
  1) ajouter "jsField" à la classe de l'input voulue
  2) renseigner le title de l'input avec la valeur du "value" d'origine)
  3) executer cette fonction au window.onload ou DOMreadystate */
function initInputFields(){
	my_fields = $$('.jsField').each( function(element){
		element.onfocus = function(){
			if(this.value == this.title)
			this.value = "";
		};

		element.onblur = function(){
			if(this.value == "")
				this.value = this.title;
		}
	});
}

/* trouve le tag "parentTagName" parent de "element" */
function getParent(element, parentTagName) {
	if ( ! element )
		return null;
	else if ( element.nodeType == 1 && element.tagName.toLowerCase() == parentTagName.toLowerCase() )
		return element;
	else
		return getParent(element.parentNode, parentTagName);
}

function initDepotCvForm(){
	if($('depot_cv')){
		$$('#depot_cv a.go_to_step_link').each( function(element){

			element.onclick = function(){

				//on cache l'actuelle DIV
				getParent(element,'div').className = "hidden";

				//et on affiche la nouvelle apres avoir récupérer le href du lien uqi indique quelle div afficher (href="#2" => on affiche div.#step_2)
				$("step_"+ element.href.toString().slice(-1)).className = "displayed";

				//mise a jour du fil d'ariane
				$$('#depot_cv_breadcrumb span').each( function(element2){
					element2.className= "";
				});
				$("depot_cv_breadcrumb_step_"+ element.href.toString().slice(-1)).className = "current_step";

				return true;
			};
		} );

		$('submit_form_link').onclick = function (){
			$('depot_cv').submit();
			return false;
		};
	}
}

function initDepotOffreForm(){
	if($('depot_offre')){
		$$('.form_field').each( function(element){
			element.disabled = true;
		});
	}
}

function initNextExperience(){
	if($('add_experience')){
		var my_step = 1;
		$('add_experience').onclick = function(){
			if(my_step <= 5){
				$('exp_'+my_step).className= "displayed";
				my_step++;
			}
			if(my_step > 5)	this.style.cursor = "not-allowed";
		};
	}
}

//submit formulaire subscribe newsletter (ajax)
function initSuscribeNewsletterSubmit(){
	var my_form = $('submit_subscribe_newsletter');
	var my_submit_button = $('newsletter_submit_button');
	var my_submit_button_src_orig = my_submit_button.src;

	my_form.onsubmit = function(){

		new Ajax.Request('souscrire-newsletter.html',{
			method: 'post',
			asynchronous: true,
			contentType:  'application/x-www-form-urlencoded',
			encoding:     'UTF-8',
			parameters: Form.serialize(my_form)+"&my_method=submit_ajax", //sends all $_post vars
			//everything's OK, updating the cartBox display :
			onLoading: function() {
				my_submit_button.src = "/img/default/loader.gif";
			},
			onSuccess: function(transport){
				this.$('newsletter_customer').value = transport.responseText;
			},
			onFailure: function(){
				this.$('newsletter_customer').value = "failure";
				return false;
			},
			onComplete: function(){
				my_submit_button.src = my_submit_button_src_orig;
			}
		});
		return false;
	};
}

//init des clicks douverture/fermeture des divs de details des metiers sur la page : Metiers du BTP
function initMetiersFolding(){
	if($('metiers_btp')){
		$$('a.metier_link').each(function(element){
			element.onclick = function(){

				if(/closed/.test(this.className)){
					//le lien est fermé, on va donc dérouler la div
					//on ferme tous les autres liens avant tout (pour n'en garder qu'un actif)

					$$('a.metier_link').each(function(element2){
						element2.className = "metier_link closed";
						getParent(element2,"div").style.height = "13px";
					});

					getParent(this,"div").style.height = "auto";
					this.className = "metier_link opened";
				}else{
					getParent(this,"div").style.height = "13px";
					this.className = "metier_link closed";
				}
			};
		});
	}
}

var map = null;
var geocoder = null;

function loadGMap() {

      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("my_map"));
        map.setCenter(new GLatLng(47.15984, 2.988281), 5);
		map.addControl(new GLargeMapControl());
		map.enableScrollWheelZoom();
		map.enableContinuousZoom();
		map.addControl(new GMapTypeControl());
		geocoder = new GClientGeocoder();
      }
    }


  function showAddress(addresses) {

  if (geocoder) {

  	addresses.each(function(element){
        geocoder.getLatLng(
          element[0],
          function(point) {
            if (!point) {
              //console.log(element[0] + " not found");
            } else {
              //map.setCenter(point, 13);
              var marker = new GMarker(point);
			  GEvent.addListener(marker, "click", function() {
				  map.closeInfoWindow();
				  marker.openInfoWindowHtml(element[1]);
				  });
              map.addOverlay(marker);

            }
          }
        );
	});
  }
}

function initGoogleMapListeOffre(){
	if($('googlemap_liste_offres')){
	    loadGMap();
		if(adressesArray)
			showAddress(adressesArray);
	}

}

/* fonction pour la dialogue flash / JS pour le jukebox flash*/
function getMovieName(movieName) {
 if (navigator.appName.indexOf("Microsoft") != -1) {
 return window[movieName]
 }
 else {
 return document[movieName]
 }
}

function callExternalInterface(url) {
 getMovieName("player").callvideo(url);
 return false ;
}


/* fonction de switch entre l'affichage des vidéos et des sons dans le menu lastFiles*/
function ShowMe(cat,video, sound){
 document.getElementById("cat"+video).style.display = "none";
 document.getElementById("cat"+sound).style.display = "none";
 document.getElementById("cat"+cat).style.display = "block";
 document.getElementById("links_show").style.background = "url('/img/bg_switch_media_"+cat+".gif') no-repeat";
 document.getElementById("link"+video).style.color = "black";
 document.getElementById("link"+sound).style.color = "black";
 document.getElementById("link"+cat).style.color = "red";
}

function TopMe(obj){
 $$('.now_playing').each(function(element){
 	element.className = "";
 	});

 obj.className = "now_playing";
}

function DirectViewMe(id){
 if (typeof(getMovieName("player").callvideo) == 'function'){
   $(id).getElementsByTagName('a')[0].onclick();
   $(id).getElementsByTagName('li')[0].onclick();
 }
}



/* depot CV : formulaire divisé en 4 pages + navigation via display/hidden JS */
window.onload = function (){

	//initialisation du menu de navigation generale
	initMainTopMenu();

	//init du formulaire de depot de CV
	initDepotCvForm();

	//init du formulaire de depot d'une offre
	//initDepotOffreForm();

	initNextExperience();

	//init des champs de formulaires (disparition du value au onclick)
	initInputFields();

	//init du submit formulaire subscribe newsletter (ajax)
	initSuscribeNewsletterSubmit();

	//init des clicks douverture/fermeture des divs de details des metiers sur la page : Metiers du BTP
	initMetiersFolding();

	//init de la liste des offres affichés via google map
	initGoogleMapListeOffre();
}

