var mapid = 'AnnuaireBodyGauche';
var map;
var geocoder = null;
var gmapExistingOnload = null;
var marker = null;
var infoTabs = null;
var gmarkers=[];
var i=0;
var gdir;
var locale = 'fr';

// dÃ©clation variable globale.
var themesTree;
var odd = false;
var organisme_s = [];
var themeId;

//
var offset = 0;

/*-----------------------------------------------------------*/
var cercle = new Array();
var cercleCouleur = "#0000ff";
var cercleEpaisseur = "2";
var cercleOpacite = ".5";
var disqueCouleur = "#0000ff";
var disqueOpacite = ".1";
var rayon = 5;
var segment = 60;
var centre;
/*-----------------------------------------------------------*/

/*-----------------------------------------------------------
ajoute aux favoris
-----------------------------------------------------------*/
function addToFavoritesGeo(url,title)
{
if(!url==""){
    if (document.all)
    window.external.AddFavorite(url, title);
    else if (window.sidebar)
    window.sidebar.addPanel(title, url, "")
}
}

/*-----------------------------------------------------------
Retire ts les marqueurs sur une carte.
-----------------------------------------------------------*/
function remove(){
	map.clearOverlays();
	gmarkers=[];
}

/**
 * Centre la carte sur un dÃ©partement
 *
 */
function centerdepartement(lt,lng,index,alphabet){

	// CrÃ©ation de mini icones
	var icon = new GIcon();

	icon.image = "http://maps.google.com/mapfiles/marker"+alphabet+".png";
	icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
	icon.iconSize = new GSize(20, 34);
	icon.shadowSize = new GSize(22, 20);
	icon.iconAnchor = new GPoint(6, 20);
	icon.infoWindowAnchor = new GPoint(5, 1);

	var point = new GLatLng(lt,lng);
	var markers = new GMarker(point, icon);

	/* Tableau de GInfoWindowTab qui va contenir les onglets de l'info-bulle */
    var infoTabs = [
        new GInfoWindowTab("Adresse", $('popupwindow_'+index).innerHTML),
        new GInfoWindowTab("Informations", $('popupwindow2_'+index).innerHTML)
    ];


	GEvent.addListener(markers, "click", function() {
		markers.openInfoWindowTabsHtml(infoTabs);
	});


	map.addOverlay(markers);

	gmarkers.push(markers);

}

function center(lt,lg,zoom){

    map.setZoom(12);
	map.setCenter(new GLatLng(lt, lg));

	drawcercle();

}

function zoomagence(lt,lg,index) {

	map.closeInfoWindow();

	 var infoTabs = [
        new GInfoWindowTab("Adresse", $('popupwindow_'+index).innerHTML),
        new GInfoWindowTab("Informations", $('popupwindow2_'+index).innerHTML)
     ];

	gmarkers[index].openInfoWindowTabsHtml(infoTabs);

}

if (window.onload) {
	//Hang on to any existing onload function.
	gmapsExistingOnload = window.onload;
}

/*--------------------------------------------------------------
Au chargement de la page, on initialise l'api Google Map.
--------------------------------------------------------------*/

function determineIfGoogleMapsCompatible () {

	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById(mapid));
		map.addControl(new GMapTypeControl());
		map.addControl(new GLargeMapControl());
		map.setCenter(new GLatLng(initLatitude, initLongitude),7);
		map.addControl(new GLargeMapControl());
		var bounds = new GLatLngBounds();

		gdir = new GDirections(map, document.getElementById("communes"));

		GEvent.addListener(gdir, "load", onGDirectionsLoad);
		GEvent.addListener(gdir, "error", handleErrors);

	}
	else {
		alert("DesolÃ©, l'API Google Maps n'est pas compatible avec votre navigateur.");
	}

}

//determineIfGoogleMapsCompatible();

Event.observe(window,'load',determineIfGoogleMapsCompatible);



/*----------------------------------------------------------------
Gestion des erreurs.
----------------------------------------------------------------*/
function handleErrors(){
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);

	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

	//	else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)	<--- Doc bug... this is either not defined, or Doc is wrong
	//	 alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);

	else if (gdir.getStatus().code == G_GEO_BAD_KEY)
		alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);

	else alert("An unknown error occurred.");

}

function onGDirectionsLoad(){
	// Use this function to access information about the latest load()
	// results.

	// e.g.Â²
	// document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	// and yada yada yada...
}

/*---------------------------------------------------
Donne la direction pour une adresse donnÃ©e.
---------------------------------------------------*/
function Getdirection(index){

	var toAddress	= $F('adresse_d_'+index);
	var street		= $F('lieu');
	var postal		= $F('postal_code_and_commune')

	document.getElementById("communes").innerHTML = '';

	map.clearOverlays();
	gmarkers=[];

	var fromAddress = street +' '+ postal;

	gdir.load("from: " + fromAddress + " to: " + toAddress,{ "locale": locale });

}

function getUrlBase64(val){

    var url = document.location;
    var url_long = url+'?q='+val;

    var url_link = url_long.replace("#", "")

    $('lien').value = url_link;

}

/**
 * Recherche d'organismes
 */
function runSearch(){

	document.getElementById('voirbutton').style.display = 'block';

	var lieu					= $F('lieu');
	var postal_code_and_commune = $F('postal_code_and_commune');
	//var service				 = $F('service').split(',').without("");
	var service                 = organisme_s;
	var accessibilite			= $F('accessibilite');


	var distance = $F('distance');

	// cache les organismes avant la recherche
	hideServicesMenu();

	xajax_getsearch(accessibilite,lieu,postal_code_and_commune,service,distance);
}

/**
 * Recherche automatisÃ©e
 *
 * Exemple de paramÃ¨tre :
 * {
 *   adr: "12, rue de la Poste",
 *   loc: "50000 Saint-LÃ´",
 *   svc: [12,26,3],
 *   acc: 1
 * }
 *
 * @param object param Objet contenant les paramÃ¨tres de recherche.
 */
function automatedSearch(param){
	var adresse  = param['adr'];
	var localite = param['loc'];
	var services = param['svc'];
	var acces    = param['acc'];

	/* Mide Ã  jour des Ã©lÃ©ments de la page */
	$('lieu').value                    = adresse;
	$('postal_code_and_commune').value = localite;
	organisme_s                        = services;
	$('accessibilite').checked         = !!acces;

	/* Recherche */
	document.getElementById("geolocalisation_getsearch_btn").click();
}

function hideServicesMenu() {
	$('AnnuaireDroiteListe').hide();
	$('AnnuaireDroiteListe').innerHTML = '';

	$$('#FormRechercheDroite .contentOn').invoke('removeClassName','contentOn').invoke('addClassName','content');
	$$('#FormRechercheDroite h2').invoke('removeClassName','on');
	$$('.fermer').invoke('hide');
	$$('.liste-services').invoke('show');
}

// chargement de la page , appel de la fonction ajax.
Event.observe(window,'load',function(){
	xajax_getsplfilters();

	/* Recherche automatisÃ©e */
	var qparams = document.location.href.toQueryParams();
	if(qparams.q){
		//try {
			var s = qparams.q.base64decode();
			var params = s.evalJSON(true);
			//NDA - l'appel à console.log pose problème sous IE et bloque le chargement de la page 
			//console.log(params); 
			automatedSearch(params);
		//}
		//catch(e){
			/* une erreur est survenue... */
		//}
	}
});

// fonction via l'ajax xajax_getsplfilters
function themes(obj){
	themesTree = eval(obj);
}

/**
 * Ajoute l'ogranisme sÃ©lectionnÃ© Ã  la liste
 *
 * @param integer id
 * @param mixed themeid
 */
function add_organisme(id,themeid) {
document.getElementById('voirbutton').style.display = 'block';

	var exist = false;

	for(var i=0, len=organisme_s.length; i<len; i++) {
		if(organisme_s[i]==id){
			alert('Vous avez deja selectionnÃ© cet organisme.');
			return;
		}
	}

	organisme_s.push(id);
	var ad_selection = '';

	organisme_s.each(function(organisme) {
		odd = !odd;
		themesTree.each(function(a,i) {
			a.elements.each(function(c,s){
				if(organisme==c.id){
						ad_selection += '<li id="org_'+organisme+'" class="" style="margin-left:0px;">';
						ad_selection += '<a href="#" onclick="delete_organisme('+organisme+','+themeid+',true);return false;">';
						ad_selection += '<span class="del">Â» <\/span> ' +c.label;
						ad_selection += '<\/a>';
						ad_selection += '<\/li>';
				}
			});
		});
	});
	$('view_organismes').innerHTML = (ad_selection);

	/* bug IE6 reconstruction de la liste des themes */

	// on vide les occurences
	$('list_orgs').innerHTML = '';

    // remplissage des items
    liste_organimes  = '';

    themesTree.each(function(a,i) {
		if (themeid == i) {
			a.elements.each(function(c){

				var organismTypeName = c.label;
				var organismID = c.id;

				odd = !odd;

				liste_organimes += '<li class="' + (odd ? 'odd' : 'even') + '" style="margin-left:0px;">';
				liste_organimes += '<a href="#" onclick="add_organisme('+organismID+','+themeid+');return false;">';
				liste_organimes += '<span>Â» <\/span>' + organismTypeName;
				liste_organimes += '<\/a>';
				liste_organimes += '<\/li>';
			});
		}
	});

	$('list_orgs').innerHTML = liste_organimes;

    /* bug IE6 reconstruction de la liste des themes */


}

function pos_index(id){
	for (var i=0, len=organisme_s.length ; i < len ; i++){
		if (organisme_s[i] == id){
			return i;
		}
	}
	return null;
}

function delete_organisme(id,themeid,re_contruct_orgs) {

	

	// efface la ligne de l'organisme
	$('org_'+id).remove();
	
	// efface l'organisme du tableau
	organisme_s.splice(pos_index(id),1);

	if(organisme_s.length==0 && themeid==-1){
		var d_content =	'<div class="content">';
		d_content += '<h3>Votre sÃ©lection<\/h3>';
		d_content += '<a class="retour" href="#" onclick="showServicesMenu(null)">Retour<\/a>';
		d_content += '<ul class="droplist service">';
		d_content += '<li style="margin:5px;">';
		d_content += '<ul style="display: block;">';
		d_content += '<li style="margin-left:0px;">Votre sÃ©lection d\'organismes est vide</li>';
		d_content += '<\/ul>';
		d_content += '<\/li>';
		d_content += '<\/ul>';
		d_content += '<\/div>';

		$('org').innerHTML = (d_content);
	}
	else if(organisme_s.length==0 && themeid!=-1){
		document.getElementById('voirbutton').style.display = 'none';
		$('view_organismes').innerHTML = '<li style="margin-left:0px;">Votre sÃ©lection d\'organismes est vide</li>';
	}


	/* bug IE6 reconstruction de la liste des themes */
	// on vide les occurences
	if(re_contruct_orgs){
    	$('list_orgs').innerHTML = '';

        // remplissage des items
        liste_organimes  = '';
        themesTree.each(function(a,i) {
    		if (themeid == i) {
    			a.elements.each(function(c){

    				var organismTypeName = c.label;
    				var organismID = c.id;

    				odd = !odd;

    				liste_organimes += '<li class="' + (odd ? 'odd' : 'even') + '" style="margin-left:0px;">';
    				liste_organimes += '<a href="#" onclick="add_organisme('+organismID+','+themeid+');return false;">';
    				liste_organimes += '<span>Â» <\/span>' + organismTypeName;
    				liste_organimes += '<\/a>';
    				liste_organimes += '<\/li>';
    			});
    		}
    	});
	$('list_orgs').innerHTML = liste_organimes;
	}
    /* bug IE6 reconstruction de la liste des themes */


}

function showonlyselect(){
 if(organisme_s.length!=0){

    $$('#FormRechercheDroite .content').invoke('removeClassName','content').invoke('addClassName','contentOn');
	$$('#FormRechercheDroite h2').invoke('addClassName','on');
	$$('.liste-services').invoke('hide','.liste-services');
	$$('.fermer').invoke('show','.fermer');


	$('AnnuaireDroiteListe').setStyle({ display: 'block' });
	$('AnnuaireDroiteListe').innerHTML = ('<div class="content"><ul class="services" id="org"><\/ul><\/div>');


	var selection = '<div class="content">';
	selection += '<h3>Votre sÃ©lection';
	selection += '<a class="retour" href="#" onclick="hideServicesMenu(); return false;">Retour<\/a>';
	selection += '<\/h3>';
	selection += '<ul class="droplist service">';
	selection += '<li style="margin:5px;">';
	selection += '<ul id="view_organismes" style="display: block;">';

		var odd=false;
		organisme_s.each(function(organisme){
			odd = !odd;
			themesTree.each(function(theme) {
				theme.elements.each(function(c,s){
					if(organisme==c.id){
	 					selection += '<li id="org_'+organisme+'" class="' + (odd ? 'odd' : 'even') + '" style="margin-left:0px;">';
						selection += '<a href="#" onclick="delete_organisme('+c.id+',false);return false;">';
						selection += '<span class="del">Â» </span> ' +c.label;
						selection += '</a>';
						selection += '</li>';
					}
				});
			});
		});
	selection += '</ul>';
	selection += '</li>';
	selection += '</ul>';
	selection += '</div>';
	$('org').innerHTML = (selection);
	/*document.getElementById('voirbutton').style.background='url(/extension/esenior/design/esenior/images/voir.gif) no-repeat 0 0';*/
	}
}
function showServicesMenu(themeId) {
	if (!themesTree){
		// Tree of themes has not yet been downloaded => Do nothing.
		return;
	}

	$$('#FormRechercheDroite .content').invoke('removeClassName','content').invoke('addClassName','contentOn');
	$$('#FormRechercheDroite h2').invoke('addClassName','on');
	$$('.liste-services').invoke('hide','.liste-services');
	$$('.fermer').invoke('show','.fermer');

	if (themeId == null) {
		$('AnnuaireDroiteListe').setStyle({ display: 'block' });
		$('AnnuaireDroiteListe').innerHTML = ('<div class="content"><ul class="services" id="org"><\/ul><\/div>');

		$('org').innerHTML += ('<li class="' + (odd ? 'odd' : 'even') + '"><a href="#" onclick="showServicesMenu(-1); return false;"><span class="titre">Votre sÃ©lection<\/span></a></li>');

		themesTree.each(function(s,index) {
			odd = !odd;
			$('org').innerHTML += ('<li class="' + (odd ? 'odd' : 'even') + '"><a href="#" onclick="showServicesMenu('+index+'); return false;"><span class="titre">'+s.label+'<\/span></a></li>');
		});

	}
	else if (themeId == -1) {
		show_selection(themeId);
	}
	else {
		show_selection(themeId);

		var content = '<div class="content">';
		content += '<h3>' + themesTree[themeId].label + '<\/h3>';
		content += '<a class="retour" href="#" onclick="showServicesMenu(null); return false;">Retour<\/a>';
		content += '<ul class="droplist service">';
		content += '<li style="margin:5px;">';
		content += '<ul style="display: block;" id="list_orgs">';

		themesTree.each(function(a,i) {
			if (themeId == i) {
				a.elements.each(function(c){
					var organismTypeName = c.label;
					var organismID = c.id;

					odd = !odd;

					content += '<li class="' + (odd ? 'odd' : 'even') + '" style="margin-left:0px;">';
					content += '<a href="#" onclick="add_organisme('+organismID+','+themeId+');return false;">';
					content += '<span>Â» <\/span>' + organismTypeName;
					content += '<\/a>';
					content += '<\/li>';
				});
			}
		});

		content += '<\/ul>';
		content += '<\/li>';
		content += '<\/ul>';
		content += '<\/div>';

		$('org').innerHTML += (content);
	}
}

function show_selection(themeid){

	var selection = '<div class="content">';
	selection += '<h3>Votre sÃ©lection<\/h3>';
	selection += '<a class="retour" href="#" onclick="showServicesMenu(null); return false;">Retour<\/a>';
	selection += '<ul class="droplist service">';
	selection += '<li style="margin:5px;">';
	selection += '<ul id="view_organismes" style="display: block;">';

	if(organisme_s.length==0){
		selection +='<li style="margin-left:0px;">Votre sÃ©lection d\'organismes est vide</li>';
	}
	else {
		var odd=false;
		organisme_s.each(function(organisme){
			odd = !odd;
			themesTree.each(function(theme) {
				theme.elements.each(function(c,s){
					if(organisme==c.id){
	 					selection += '<li id="org_'+organisme+'" class="' + (odd ? 'odd' : 'even') + '" style="margin-left:0px;">';
						selection += '<a href="#" onclick="delete_organisme('+c.id+',false); return false;">';
						selection += '<span class="del">Â» </span> ' +c.label;
						selection += '</a>';
						selection += '</li>';
					}
				});
			});
		});
	}

	selection += '</ul>';
	selection += '</li>';
	selection += '</ul>';
	selection += '</div>';
	$('org').innerHTML = (selection);


}

function input_change(){

    var input = $('postal_code_and_commune').value;

    if(input.length >= 1){

        xajax_getcommunes(10,0,$F('postal_code_and_commune'));
    } else {
        $('autocompleter').setStyle({ display: 'none' });
    }

}

function up_search(){

    if(offset!=0){
        offset = (offset - 10);
    }

    xajax_getcommunes(10,offset,$F('postal_code_and_commune'));
}

function down_search(){

    offset = (offset + 10);
    xajax_getcommunes(10,offset,$F('postal_code_and_commune'));

}

/**
* Returns the top left position of the given element
*
* @param object obj A DOM object
*/
function findPosition(obj) {

var top = obj.offsetTop || 0;
var left = obj.offsetLeft || 0;

while (obj = obj.offsetParent) {
    top += obj.offsetTop;
    left += obj.offsetLeft;
    
}
top = top + 170;
left = left + 22;

$('autocompleter').setStyle({ display: 'block',
                              top: top+ 'px',
                              left: left+'px',
                              width: '279px'
    });

// bug IE6 cache les inputs
$('distance').setStyle({ display: 'none' });

};

function display_search_communes(html,count) {

    // rÃ©cupÃ©ration du html xajax
    $('autocompleter').innerHTML = html;

    if(count=='0'){
        // on cache la div de recherche
        $('autocompleter').setStyle({ display: 'none' });
        // bug IE6 cache les inputs
        $('distance').setStyle({ display: '' });
    }else{
        findPosition($('postal_code_and_commune'));
    }



}

function selectcom(val){

    // on rÃ©cupÃ©re la valeur dans l'input de recherche
    $('postal_code_and_commune').value = $("cp"+val).innerHTML;

    // on cache la div de recherche
    $('autocompleter').setStyle({ display: 'none' });

    // bug IE6 cache les inputs
    $('distance').setStyle({ display: '' });

}
