

/* An InfoBox is like an info window, but it displays
 * under the marker, opens quicker, and has flexible styling.
 * @param {GLatLng} latlng Point to place bar at
 * @param {Map} map The map on which to display this InfoBox.
 * @param {Object} opts Passes configuration options - content,
 *   offsetVertical, offsetHorizontal, className, height, width
 */

/**
* Returns an XMLHttp instance to use for asynchronous
* downloading. This method will never throw an exception, but will
* return NULL if the browser does not support XmlHttp for any reason.
* @return {XMLHttpRequest|Null}
*/
function createXmlHttpRequest() {
 try {
   if (typeof ActiveXObject != 'undefined') {
     return new ActiveXObject('Microsoft.XMLHTTP');
   } else if (window["XMLHttpRequest"]) {
     return new XMLHttpRequest();
   }
 } catch (e) {
   changeStatus(e);
 }
 return null;
};

/**
* This functions wraps XMLHttpRequest open/send function.
* It lets you specify a URL and will call the callback if
* it gets a status code of 200.
* @param {String} url The URL to retrieve
* @param {Function} callback The function to call once retrieved.
*/
function downloadUrl(url, callback) {
 var status = -1;
 var request = createXmlHttpRequest();
 if (!request) {
   return false;
 }

 request.onreadystatechange = function() {
   if (request.readyState == 4) {
     try {
       status = request.status;
     } catch (e) {
       // Usually indicates request timed out in FF.
     }
     if (status == 200) {
       callback(request.responseXML, request.status);
       request.onreadystatechange = function() {};
     }
   }
 }
 request.open('GET', url, true);
 try {
   request.send(null);
 } catch (e) {
   changeStatus(e);
 }
};

/**
 * Parses the given XML string and returns the parsed document in a
 * DOM data structure. This function will return an empty DOM node if
 * XML parsing is not supported in this browser.
 * @param {string} str XML string.
 * @return {Element|Document} DOM.
 */
function xmlParse(str) {
  if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
    var doc = new ActiveXObject('Microsoft.XMLDOM');
    doc.loadXML(str);
    return doc;
  }

  if (typeof DOMParser != 'undefined') {
    return (new DOMParser()).parseFromString(str, 'text/xml');
  }

  return createElement('div', null);
}

/**
 * Appends a JavaScript file to the page.
 * @param {string} url
 */
function downloadScript(url) {
  var script = document.createElement('script');
  script.src = url;
  document.body.appendChild(script);
}


var map_en_place;
var aMarkers = [];
var mapMarkers = [];
var mapHTMLS = [];
var maphauteur =[]
var infowindow ;
var contenu_resultats='';
var marker_hover;
var result_hover;
var tr_hover;

function select_marker(id) {

var image_hover='/img/marqueur_hover.png';
var image='/img/marqueur.png';
//if (infowindow)  infowindow.setMap(null);
if (marker_hover) marker_hover.setIcon(image);

	  //infobox= new InfoBox({latlng : mapMarkers[id], map: map,content: mapHTMLS[id] ,height:maphauteur[id] });
 		aMarkers[id].setIcon(image_hover);
	  	marker_hover=aMarkers[id];

		if ($('liste_resultats'))
		{
			// if (result_hover) result_hover.src=image;
			  if (tr_hover) tr_hover.toggleClass('div_over');
			//$('img_'+id).src=image_hover;
			//result_hover=$('img_'+id);
			$('div_'+id).toggleClass('div_over');
			tr_hover=$('div_'+id);
		}
		map.panTo(mapMarkers[id]);

if (infowindow) infowindow.close();
var infowindowOptions = {
    content: mapHTMLS[id]
  }
infowindow = new google.maps.InfoWindow(infowindowOptions);
infowindow.open(map, aMarkers[id]);
}

function ouvrir_bulle(id)
{	if	(! $('masque_matt'))
	{
	var div_masque=new Element('div',{id:'masque_matt'});
	div_masque.inject	(document.body,'top');
	}
	$('masque_matt').setStyles({
							'background-color': '#000000',
							'z-index' : '99995',
	 						'opacity' : '0.5',
    						'filter' : 'alpha(opacity=50)',
							'position' : 'absolute',
							'display' : 'block',
							'visibility' : 'visible'
						  });
	var scroll=window.getScrollSize();

	$('masque_matt').style.width = scroll.x+'px';
	$('masque_matt').style.height = scroll.y+'px';

	if	(! $('div_palette'))
	{
	var div_palette=new Element('div',{id:'div_palette'});
	div_palette.inject	(document.body);
	}

		$('div_palette').innerHTML = "<div id='poignee' ><a onclick=\"palette_fermeture('div_palette')\">Fermer</a></div><div id='details_etab' style=' width:550px;'></div>";
		$('div_palette').setStyles({'margin-left':'0px','position':'absolute','top':'0px','left':'0px','display':'block','visibility':'visible','z-index':'99996','background-color':'#FFFFFF','width':'600px'});




		var myDrag = new Drag($('div_palette'), {
		handle: $('poignee'),
		snap: 0,
		onSnap: function(el){
			el.addClass('dragging');
		},
		onComplete: function(el){
			el.removeClass('dragging');
		}
	});


	var params_ajax='mode=etablissement&affich=detail&id='+id;

	var myRequest=new Request
		({url:'ajax_ctrl.php',onSuccess: function(reponse)
	{
	//if (reponse!=0) $('div_submit').style.display='block'; else $('pas_resultats').style.display='block';
	$('details_etab').innerHTML=reponse;
	$('div_palette').position();
			myRequest.cancel();
		},evalScripts:true});

		myRequest.send(params_ajax)




}

 function carte_etab_unique(id_etab)
 {

 initialize('mode=etablissement&id_etab='+id_etab);
 }


function initialize(params_ajax) {

    var myLatlng = new google.maps.LatLng(45.747019,4.83078);
  	 var bounds = new google.maps.LatLngBounds();

	var nb_resultats=0;
    var myOptions = {
      zoom: 13,
      center: myLatlng,
      mapTypeId: google.maps.MapTypeId.TERRAIN,
	  scrollwheel:false
    }
	map_en_place = 1;
    map = new google.maps.Map(document.getElementById("carte"), myOptions);
    downloadUrl('ajax_ctrl.php?'+params_ajax, function(data) {
      var markers = data.documentElement.getElementsByTagName("marker");
	  var zoomListner = google.maps.event.addListener(map, 'zoom_changed', function() {
	google.maps.event.removeListener(zoomListner);

	if (this.getZoom() > 13) // Change max/min zoom here
	this.setZoom(13);
	if (this.getZoom() < 8) // Change max/min zoom here
	this.setZoom(8);
	});
      for (var i = 0; i < markers.length; i++) {
        var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
                                    parseFloat(markers[i].getAttribute("lng")));
		var bulle=	"<div class='bulle' >";
		bulle+="<table align='center'>";
		bulle+="<tr><td  valign='middle' colspan='2'> <table border='0' cellspacing='0' cellpadding='0'>  <tr>   <td  valign='bottom' class='titre_bulle' nowrap=''><a target='_blank' href='"+ markers[i].getAttribute("site")+"' target='_blank'>"+markers[i].getAttribute("name")+"</a></td>  <td rowspan='2' width='150'  class='txt_bulle_img'><img align='absMiddle' width='"+markers[i].getAttribute("largeur_image")+"' height='"+markers[i].getAttribute("hauteur_image")+"' src='/img/etablissements/"+markers[i].getAttribute("id")+"/logo.jpg' alt=''/> </td> </tr>  <tr>    <td valign='top' class='fiche_bulle' ><a href='etablissements-"+markers[i].getAttribute("fiche")+"-"+markers[i].getAttribute("id")+".html' >>>>Plus d'infos</a></td>  </tr></table></td></tr>";


		bulle+="<tr><td >   ";

		bulle+="<table border='0' cellspacing='0' cellpadding='0' >  <tr>";
		bulle+="<td  class='txt_bulle_img'>";
		bulle+=" <img  width='100' height='83' src='/img/etablissements/"+markers[i].getAttribute("id")+"/site.jpg' alt=''/>";
		bulle+="</td> <td class='txt_bulle'>";
				bulle+=markers[i].getAttribute("adresse") +"<br/>"+markers[i].getAttribute("code_postal")+" "+markers[i].getAttribute("ville")+"<br/>";
		bulle+=" Tel :<b>"+markers[i].getAttribute("tel");
		bulle+="</b><br/>Fax : <b>"+markers[i].getAttribute("fax");
		bulle+="</b><br/>";
		bulle+=markers[i].getAttribute("mail");
		bulle+="<br/>";
		bulle+="<a target='_blank' href='"+ markers[i].getAttribute("site")+"' target='_blank' onClick=\"recordOutboundLink(this, 'Liens sortants', '"+ markers[i].getAttribute("site")+"');return false;\">"+markers[i].getAttribute("site")+"</a><br/>";
		bulle+="</td>  </tr>";
		bulle+="<tr><td colspan='2' width='350'>";
		bulle+=markers[i].getAttribute("descriptif");
		bulle+="</td>  </tr>";

		bulle+="</table>";



		bulle+="</td>";
		bulle+="</tr></table>";
//			var formations = data.documentElement.getElementsByTagName("formation_"+markers[i].getAttribute("id"));
//			bulle+="<div style='font-size:8px; '>";
//			bulle+="<table>";
//					for (var j = 0; j < formations.length; j++) {
//					bulle+="<tr><td>"+formations[j].getAttribute("name")+"</td></tr>";
//					}
//			bulle+="</table>";
//				bulle+="</div>"
		bulle+="</div>"	;
		//maphauteur.push(markers[i].getAttribute("hauteur"));
		//var bulle;
        var marker = createMarker(bulle, latlng,i,markers[i].getAttribute("id"));
		aMarkers.push(marker);
		mapMarkers.push(latlng);
		var html="<div class='carte_resultats' id='div_"+i+"'>";
		html+="<table>";
		html+="<tr>";

		html+="<td width='200'> <a onmouseover='select_marker(" + i +")' href='"+ markers[i].getAttribute("site")+"' target='_blank' onClick=\"recordOutboundLink(this, 'Liens sortants', '"+ markers[i].getAttribute("site")+"');return false;\">"+markers[i].getAttribute("name")+"</a><br/>";
		html+=markers[i].getAttribute("code_postal")+" "+markers[i].getAttribute("ville")+"</td>";
		html+="<td width='25'><a  href='"+ markers[i].getAttribute("site")+"' target='_blank' onClick=\"recordOutboundLink(this, 'Liens sortants', '"+ markers[i].getAttribute("site")+"');return false;\"><img id='img_"+i+"' src='/img/interface/internet.png' border='0' title='Accéder au site internet'  /></a></td>";
		html+="<td width='25'><a href='etablissements-"+markers[i].getAttribute("fiche")+"-"+markers[i].getAttribute("id")+".html' ><img src='/img/interface/loupe.png' border='0' title='Voir la fiche détaillée'  /></a></td>";
		html+="</tr>";
		html+="</table>";
		html+="</div>";
		contenu_resultats+=html;
		mapHTMLS.push(bulle);

		nb_resultats++;
		bounds.extend(latlng);
       }
	 // if (nb_resultats <10) {$('liste_resultats').innerHTML=''; $('liste_resultats').innerHTML=contenu_resultats;} else {$('liste_resultats').innerHTML='Désolé trop de résultats';}
	// alert (contenu_resultats);
	// alert ( $('liste_resultats'));
	if ($('liste_resultats'))
		{
	$('liste_resultats').innerHTML=contenu_resultats;
		}


	 map.fitBounds(bounds);

     });

  }


  function createMarker(name, latlng,i,id) {
  	var image = '/img/marqueur.png';
    var marker = new google.maps.Marker({position: latlng, map: map,icon:image});
    google.maps.event.addListener(marker, "mouseover", function() {
     // if (infowindow)  infowindow.setMap(null);
	 // infobox= new InfoBox({latlng : latlng, map: map,content: name,height:maphauteur[i]});
	  var image_hover='/img/marqueur_hover.png';
	  if (marker_hover) marker_hover.setIcon(image);
	  if (result_hover) result_hover.src=image;
	  if (tr_hover) tr_hover.toggleClass('div_over');
	  marker.setIcon(image_hover);
	  marker_hover=marker;
	  if ($('liste_resultats'))
		{

	 // result_hover=	$('img_'+i);
	  //$('img_'+i).src=image_hover;
	   var test=$('img_'+i).getPosition($('liste_resultats')).y;
	   var scroll = $('liste_resultats').getScroll().y;

	 	var scroll_jump=test+scroll-($('liste_resultats').getSize().y/2);

	  $('liste_resultats').scrollTo(0,scroll_jump);


		$('div_'+i).toggleClass('div_over');
		tr_hover=$('div_'+i);
	 	 }

    });
	 google.maps.event.addListener(marker, "click", function() {
	if (infowindow)  infowindow.close();
      infowindow = new google.maps.InfoWindow({content: name});
      infowindow.open(map, marker);
	 });
    return marker;
  }

function afficher_carte_etab (etab)

{
	var params_ajax='mode=etablissement';
	params_ajax+='&id_etab='+etab;
	ML_palette('div_palette','ajax_ctrl.php',params_ajax,1,0);

}

function ML_palette(elmt,url_ajax,params_ajax,carte,i)
{
	if	(! $('masque_matt'))
	{
	var div_masque=new Element('div',{id:'masque_matt',events: {click: function(){ palette_fermeture($('div_palette')); }}});
	div_masque.inject	(document.body,'top');
	}
	$('masque_matt').setStyles({
							'background-color': '#000000',
							'z-index' : '99995',
	 						'opacity' : '0.5',
    						'filter' : 'alpha(opacity=50)',
							'position' : 'absolute',
							'display' : 'block',
							'visibility' : 'visible'
						  });
	var scroll=window.getScrollSize();

	$('masque_matt').style.width = scroll.x+'px';
	$('masque_matt').style.height = scroll.y+'px';

	if	(! $(elmt))
	{
	var div_palette=new Element('div',{id:elmt});
	div_palette.inject	(document.body);
	}

		$(elmt).innerHTML = "<div id='poignee' ><a class='bouton_fermer' onclick=\"palette_fermeture('div_palette')\"></a></div><div id='carte' style=' width:550px; height:450px'></div>";
		$(elmt).setStyles({'margin-left':'0px','position':'absolute','top':'0px','left':'0px','display':'block','visibility':'visible','z-index':'99996'});

		$(elmt).position();


		var myDrag = new Drag(elmt, {
		handle: $('poignee'),
		snap: 0,
		onSnap: function(el){
			el.addClass('dragging');
		},
		onComplete: function(el){
			el.removeClass('dragging');
		}
	});
		if (carte==1)
		initialize(params_ajax);



}

function palette_fermeture(elmt)
{
 $(elmt).innerHTML = "";
 $(elmt).style.display = "none";
 $(elmt).style.top = "0";
 $(elmt).style.left = "0";
 $('masque_matt').style.display = 'none';

 }


var cX = 0; var cY = 0; var rX = 0; var rY = 0;
function AssignPosition(d) {
if(self.pageYOffset) {
	rX = self.pageXOffset;
	rY = self.pageYOffset;
	}
else if(document.documentElement && document.documentElement.scrollTop) {
	rX = document.documentElement.scrollLeft;
	rY = document.documentElement.scrollTop;
	}
else if(document.body) {
	rX = document.body.scrollLeft;
	rY = document.body.scrollTop;
	}
if(document.all) {
	cX += rX;
	cY += rY;
	}
d.style.left = (cX+0) + "px";
d.style.top = (cY+0) + "px";
}
function HideContent(d) {
if(d.length < 1) { return; }
document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
if(d.length < 1) { return; }
var dd = document.getElementById(d);

dd.style.display = "block";
}
function ReverseContentDisplay(d) {
if(d.length < 1) { return; }
var dd = document.getElementById(d);
AssignPosition(dd);
if(dd.style.display == "none") { dd.style.display = "block"; }
else { dd.style.display = "none"; }
}


function cpt_resultats(mode)
{ $('div_submit').style.display='none';
$('pas_resultats').style.display='none';
var params_ajax='mode='+mode+'&cpt=1&'+$('moteur_recherche').toQueryString();
 var myRequest=new Request
  ({url:'ajax_ctrl.php',onSuccess: function(reponse)
 {
 if (reponse!=0) $('div_submit').style.display='block'; else $('pas_resultats').style.display='block';
 $('compteur_resultats').innerHTML=reponse;

   myRequest.cancel();
  },evalScripts:true});

  myRequest.send(params_ajax)

}

function afficher_onglet(id,id_etab,onglet)
{
	$$('.onglet_actif').removeClass('onglet_actif').addClass('onglet_inactif');

	$(onglet).removeClass('onglet_inactif').addClass('onglet_actif');
$$('.div_onglet_actif').removeClass('div_onglet_actif').addClass('div_onglet_inactif');
$(id).removeClass('div_onglet_inactif').addClass('div_onglet_actif');
if (id=='carte'	&& (window.map===undefined))
carte_etab_unique(id_etab);

}



