
var map;
var mesmarkers = new Array();
var infosMarkers = new Array();
var lieuxmarkers = new Array();
var infosLieuxMarkers = new Array();
var idFocus;
var geocoder;
var markerTest;
/*
* 
* Utilitaires.. That's about interface, baby ! 
*
*/

function stopLoading(idElt) {
	// arrêt de l'affichage du petit bitoniau
	document.getElementById(idElt).src = 'themes/images/toolDown.gif';
}

function startLoading(idElt) {
	
	document.getElementById(idElt).src = 'themes/images/toolLoader.gif';
}

function accordion(el) {
    if (el.id == 'visible') {
        return false;
    }
    eltVisible = document.getElementById('visible');
    if (eltVisible) {
    	startLoading(el.parentNode.id+'-state');
        var eldown = el.parentNode.id+'-body';
        var elup = eltVisible.parentNode.id+'-body';
    	new Ajax.Updater(eldown, '?io=get&elt=' + el.parentNode.id, { asynchronous:true, evalScripts:true, onComplete: function () {
	        new Effect.Parallel(
	        [
	            new Effect.BlindUp(elup),
	            new Effect.BlindDown(eldown)
	        ], {
	            duration: 0.3
	        });
	    	stopLoading(el.parentNode.id+'-state');
    		document.getElementById(eltVisible.parentNode.id+'-state').src = 'themes/images/toolUp.gif';
    		eltVisible.id = '';
    	}});
    	 el.id = 'visible';
    }
}

function toolFiltre(idElt, filtre) {
	startLoading(idElt+'-state');
   new Ajax.Updater(idElt+'-body', '?io=get&elt=' + idElt + '&filtre=' + encodeURIComponent(filtre), { asynchronous:true, evalScripts:true, onComplete: function () {
    	stopLoading(idElt+'-state');
	}});
}



function updateUserTest(type, valeurData) {
	new Ajax.Updater('updaterdiv', '?io=get&elt=updaterdiv&type=' + encodeURIComponent(type) + '&valeurData=' + encodeURIComponent(valeurData), { asynchronous:true, evalScripts:true });
}

function addEvent(elm, evType, fn, useCapture) {
    elm["on"+evType]=fn;return;
}

/*
*
* Teoo -> navigation googlemap
*
*/



/**********************************************************************************************************************
GOOGLE MAPS


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

function arCoreOuvrePopup(pageScript, elementAAfficher, parametres) {

	new Ajax.Updater('contextPopupIn', pageScript, {parameters:'element=' + encodeURIComponent(elementAAfficher) + '&' + parametres, method:'get', evalScripts:true, asynchronous: true});
	if(document.getElementById('contextPopup').style.display != 'block') {
		document.getElementById('contextPopup').style.display = 'block'
		Effect.Appear('contextPopup');
	}
	else {
		//Effect.Appear('contextPopup');
		new Effect.Highlight('contextPopup');
	}
	return false;
}

function arCoreClosePopup() {
	Element.update( 'contextPopupIn', '' );
	document.getElementById('contextPopup').style.display = 'none';
	
	//document.body.removeChild(document.getElementById('leditor'));
}

function invit(zami) {
	new Ajax.Updater('contextPopupIn', '?io=get&elt=popup', {parameters:'element=invit&zami=' + encodeURIComponent(zami), method:'get', evalScripts:true, asynchronous: true});
	new Effect.Highlight('contextPopup');
}

function traiteInvit(idZami, accepteInvit, proposeInvit) {
	new Ajax.Updater('contextPopupIn', '?io=get&elt=popup', {parameters:'element=receptionInvit&idZami=' + encodeURIComponent(idZami) + '&accepteInvit=' + accepteInvit + '&proposeInvit=' + proposeInvit, method:'get', evalScripts:true, asynchronous: true});
	new Effect.Highlight('contextPopup');
}


function modifCoords(lat, lng) {
	arCoreOuvrePopup('?io=get&elt=popup', 'modifCoordonnees', 'lat=' + lat + '&lng=' + lng);
}


function modifCoordsParAdr(lat, lng) {
	arCoreOuvrePopup('?io=get&elt=popup', 'modifCoordParAdresse', 'lat=' + lat + '&lng=' + lng);
}

// pour lancer l'affichage et l'update de la brique infos.
function updateInfos() {
	new Ajax.Updater('infoPlace', '?io=get&elt=infos', {method:'get', evalScripts:true, asynchronous: true});
	new Effect.Highlight('infoPlace');
}

//   	Using function as seen on http://www.tripmojo.com/api/main.jsp?query=10001 
function drawCircle(point, radius) {
// alert("drawCircle@"+point+" r="+radius); 
  var cColor = "#3366ff";
  var cWidth = 5;
  var Cradius = radius;   
  var d2r = Math.PI/180; 
  var r2d = 180/Math.PI; 
  var Clat = (Cradius/3963)*r2d; 
// alert("point.lat()="+point.lat()+" point.lng()="+point.lng());  
  var Clng = Clat/Math.cos(point.lat()*d2r); 
  var Cpoints = []; 
  for (var i=0; i < 33; i++) { 
    var theta = Math.PI * (i/16); 
    var CPlng = point.lng() + (Clng * Math.cos(theta)); 
    var CPlat = point.lat() + (Clat * Math.sin(theta)); 
    var P = new GLatLng(CPlat,CPlng);
    newBounds.extend(P);
    Cpoints.push(P); 
  }
// alert("circle@"+point+" color="+cColor+" width="+cWidth+" length="+Cpoints.length);
  map.addOverlay(new GPolyline(Cpoints,cColor,cWidth)); 
} 


/*
 * Enregistre dans le tableau le marqueur passé en parametre et l'associe a l'id utilisateur
*/
function registerMarker(marker, id, infosHtml) {
	if(mesmarkers[id]) {
		map.removeOverlay(mesmarkers[id]);
	}
	mesmarkers[id] = marker;
	infosMarkers[id] = infosHtml;
	// si le marler n'existais pas, on le pose sur la carte
	
	map.addOverlay(marker);
	// sinon, on modifie simplement sa position
	
}

function registerMarkerLieu(marker, id, infosHtml) {
	if(lieuxmarkers[id]) {
		map.removeOverlay(lieuxmarkers[id]);
	}
	lieuxmarkers[id] = marker;
	infosLieuxMarkers[id] = infosHtml;
	// si le marler n'existais pas, on le pose sur la carte
	
	map.addOverlay(marker);
	// sinon, on modifie simplement sa position
	
}


function followfriend(id, titre) {
	// on envoie une ptite requete au serveur.
	setfocus(id, titre)
	gotofriend(id);
}

function followme() {
	setfocus(0, 'Ma carte <a style=\"font-size: 10pt; color: #a61078;\" onClick=\"loosefocus();\">( lacher le focus )</a>');
	gotofriend(0);
}

function infosfriend(id) {
	gotofriend(id);
	mesmarkers[id].openInfoWindowHtml(infosMarkers[id]);
}

function infoslieu(id) {
	gotoLieu(id);
	lieuxmarkers[id].openInfoWindowHtml(infosLieuxMarkers[id]);
}

/* mesmarkers[id] doit etre enregistré */
function gotofriend(id) {
	marker = mesmarkers[id];
	poinpoint = marker.getLatLng();	
	map.panTo(poinpoint, 13);
}

function gotoLieu(id) {
	marker = lieuxmarkers[id];
	poinpoint = marker.getLatLng();	
	map.panTo(poinpoint, 13);
}

function loosefocus() {
	//alert("perte du focus");
	Element.update('titreMap', 'Ma carte <a style=\"font-size: 10pt; color: #a61078;\" onClick=\"followme();\">( centrer sur moi )</a>');
	marker = mesmarkers[0];
	poinpoint = marker.getLatLng();
	//new Ajax.Updater('contextPopupIn', pageScript, {parameters:'element=' + encodeURIComponent(elementAAfficher) + '&' + parametres, method:'get', evalScripts:true, asynchronous: true});
	
	Element.update('latMap', poinpoint.lat());
	Element.update('longMap', poinpoint.lng());
	idFocus = -1;
}

function setfocus(id, titre) {
	Element.update('titreMap', titre);
	marker = mesmarkers[id];
	poinpoint = marker.getLatLng();
	//new Ajax.Updater('contextPopupIn', pageScript, {parameters:'element=' + encodeURIComponent(elementAAfficher) + '&' + parametres, method:'get', evalScripts:true, asynchronous: true});
	
	Element.update('latMap', poinpoint.lat());
	Element.update('longMap', poinpoint.lng());
	idFocus = id;
	//alert(id + " chope le focus");
}

function checkfocus() {
	if(idFocus >= 0) {
		gotofriend(idFocus);
	}
}

/* scroll la carte sur un ami*/
function showfriend(latitude, longitude ) {
    map.panTo(new GLatLng(latitude, longitude), 13);
}


// Creates a marker whose info window displays the given number
function createMarker(point, comment, image_icone, ombre_icone)
{
	if(ombre_icone == null) {
		ombre_icone = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
	}
    // Show this markers index in the info window when it is clicked
    var icon = new GIcon();
    icon.image = "http://www.teoo.fr/" + image_icone;
    icon.shadow = ombre_icone;
    icon.iconSize = new GSize(60, 60);
    icon.shadowSize = new GSize(44, 40);
    icon.iconAnchor = new GPoint(30, 30);
    icon.infoWindowAnchor = new GPoint(30, 30);
    // End of Create our marker icon


    var marker = new GMarker(point, icon );
    
    GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(comment);});
    return marker;
}


//*******************************************************************************
// Crée le marqueur (draggable) de l'utilisateur.
//  
// point, un commentaire à placer, les images de l'icone et de l'ombre (j'ai enlevé l'ombre, on pourra la remettre en pensant à générer en php des ombrages png.)
// les événements :
//   - click -> ouvre la googleDiv, et y affiche le commentaire (typiquement : 'je suis là : (x, y)')
//   //- dragstart -> ferme la googleDiv (removed)
//   - dragend -> **ajax** envoie les coordonnées au serveur. Le serveur renvoie en retour une chaine de caractère à afficher dans la nouvelle googleDiv (typiquement, 'et maintenant ici : (x,y)')

function createMarkerPerso(point, image_icone)
{
    // Show this markers index in the info window when it is clicked
    var icone = new GIcon();
    icone.image = image_icone;
    // icone.shadow = ombre_icone;
    icone.iconSize = new GSize(60, 60);
    icone.shadowSize = new GSize(44, 40);
    icone.iconAnchor = new GPoint(30, 30);
    icone.infoWindowAnchor = new GPoint(30, 30);
    
    // creation du marqueur
    var marker = new GMarker(point, {icon: icone, draggable:true});

    // on n'utilise plus pour l'instant le 'comment' passé en parametre. Le <div id='gdiv' permet la requete ajax
    var comment = '<div id=\'gdiv\'><h3>Je suis ici : </h3><ul><li>latitude (x):  ' + marker.getPoint().lat() + '</li><li>longitude (y): ' + marker.getPoint().lng() + '</li></ul><h6>(bougez l\'icone pour modifier votre position)</h6></div>';
    
    //~ var marker = new GMarker(point, icon);
    GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(comment);});
    /*GEvent.addListener(marker, "dragstart", function() {
													        map.closeInfoWindow();
													  	});*/
	GEvent.addListener(marker, "dragend", function() {
			var comment = '<div id=\'gdiv\'><h3>Patientez.. : </h3><ul><li>&nbsp;</li><li>&nbsp;</li></ul><p>enregistrement en cours ...</p></div>';
    		registerMarker(marker, 0, comment);
			marker.openInfoWindowHtml(comment);	
			new Ajax.Updater(	'gdiv', 
								'?io=get&elt=gdiv&action=updatePos&x=' + encodeURIComponent(marker.getPoint().lat()) + '&y=' + encodeURIComponent(marker.getPoint().lng()), 
								{method:'get', asynchronous: true, onComplete: function (request) { 
																								//marker.openInfoWindowHtml(comment);	
																			 }
						});
	});
	
	// on renvoie un marqueur prêt à être 'overlayé'
    return marker;
};


function ShowCellId( latitude, longitude ) {
        UnPoint = new GLatLng( latitude, longitude);
        var marqueur = new GMarker(UnPoint);
        //map.panTo(UnPoint, 26);
        map.addOverlay(marqueur);
        //map.panTo(new GLatLng( %s, %s ), 26);
        //map.addOverlay(new GMarker(new GLatLng( %s, %s )));
}


// addAddressToMap() is called when the geocoder returns an
// answer.  It adds a marker to the map with an open info window
// showing the nicely formatted version of the address and the country code.
function addAddressToMap(response) {
    
  if (!response || response.Status.code != 200)
  {
    alert("Désolé, mais je ne parviens pas à lire cette adresse.");
  }
  else
  {
    place = response.Placemark[0];
    //point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
    //marker = new GMarker(point);
    //marker.openInfoWindowHtml(place.address + '<br>' + '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
    document.getElementById('addressConfirm').style.display = 'block';
    document.getElementById('lat').value = place.Point.coordinates[1];
    document.getElementById('lng').value = place.Point.coordinates[0];
    
    vect = [place.Point.coordinates[1], place.Point.coordinates[0]];
    
    map.panTo(new GLatLng( vect[0], vect[1] ), 13);
  }
}


// showLocation() is called when you click on the Search button
// in the form.  It geocodes the address entered into the form
// and adds a marker to the map at that location.
function showLocation()
{
  var address = document.getElementById('q').value;
  geocoder.getLocations(address,addAddressToMap);
}

/**********************************************************************************************************************
AFFICHAGE
***********************************************************************************************************************/
function openwindow(){
    window.open ("","Help","toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=no,copyhistory=no,width=600,height=400");
}

/*  v3.0 */
function preloadImages() 
{
    var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

/*  v3.0 */
function swapImgRestore()
{
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

/*  v3.0 */
function findObj(n, d)
{
    var p,i,x;  if(!d) d=document;
    if((p=n.indexOf("?"))>0&&parent.frames.length)
    {
        d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
    }
    if(!(x=d[n])&&d.all) x=d.all[n];
    for (i=0;!x&&i<d.forms.length;i++)
        x=d.forms[i][n];
    for(i=0;!x&&d.layers&&i<d.layers.length;i++)
        x=findObj(n,d.layers[i].document);
    return x;
}

/*  v3.0 */
function swapImage()
{
  var i,j=0,x,a=swapImage.arguments; 
  document.MM_sr=new Array; 
  for(i=0;i<(a.length-2);i+=3)
    if ((x=findObj(a[i]))!=null)
    {
        document.MM_sr[j++]=x; 
        if(!x.oSrc) x.oSrc=x.src; 
        x.src=a[i+2];
    }
}

/**********************************************************************************************************************
INITIALISATION
***********************************************************************************************************************/
function initializeTeoo(lat, lng) {
	initializeGoogleMap(lat, lng);
	initAccordion();
}

function initializeMiniTeoo() {
	initializeMiniGoogleMap();
}

function initAccordion() {
	new Draggable('contextPopup',{handle:'h_contextPopup'});
	
    // hide all elements apart from the one with id visible
    var acc = document.getElementById('accordion');
    var apanels = acc.getElementsByTagName('div');
    for (i = 0; i < apanels.length; i++) {
        if (apanels[i].className == 'panel_body') {
            apanels[i].style.display = 'none';
        }
    }
    var avis = document.getElementById('visible').parentNode.id;
    document.getElementById(avis+'-body').style.display = 'block';
    toolFiltre(avis, 'init');
}

function initializeGoogleMap(lat, lng) {
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
    	map.setCenter(new GLatLng(lat, lng), 13);
        geocoder = new GClientGeocoder();
        // DEBUT Ajout M�dhi: 01/10/2007
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.enableScrollWheelZoom();
        // FIN   Ajout M�dhi: 01/10/2007
        
        //showfriend(refLatitude, refLongitude);
      }
}


function initializeMiniGoogleMap() {
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
    	// on centre a paris
        map.setCenter(new GLatLng(48.863107,2.354467), 16);
        
        // DEBUT Ajout M�dhi: 01/10/2007
        map.addControl(new GSmallMapControl());
        map.enableScrollWheelZoom();
        // FIN   Ajout M�dhi: 01/10/2007
		
        // DEBUT Ajout M�dhi: 12/10/2007
        // pascal : on retrouve tout ce code dans briques/updaterdiv.php
		//Point = new GLatLng(48.863107,2.354467);
		//image_icone = "/medias/Avatars/wyvern-ewock-tux.png";
		//comment = "Utilisateur de test, faisant son footing";
		//ombre_icone = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";

		
		//markerTest = createMarker(Point, comment, image_icone, ombre_icone);
		//registerMarker(markerTest, "test", comment);
		//map.addOverlay(markerTest);
		
		
		// au bout de deux secondes d'attente on update une div invisible avec le script briques/updaterdiv.php
		window.setTimeout("updateUserTest('file', 'medias/MedhiFooting.csv')",2000);
		//window.setTimeout("updateUserTest('sql', 'jjmedhi')",2000);
		
		//MedhiFooting = file("medias/MedhiFooting.csv");
		//Marker.setPoint(Point);
		//Marker.redraw(true);
		//map.panTo(Point);
        // FIN   Ajout M�dhi: 12/10/2007
		
        //showfriend(refLatitude, refLongitude);
      }
}

// DEBUT Ajout M�dhi: 12/10/2007
function file(fichier)
{
     if(window.XMLHttpRequest) // FIREFOX
          xhr_object = new XMLHttpRequest();
     else if(window.ActiveXObject) // IE
          xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
     else
          return(false);
     xhr_object.open("GET", fichier, false);
     xhr_object.send(null);
     if(xhr_object.readyState == 4) return(xhr_object.responseText);
     else return(false);
}
// FIN   Ajout M�dhi: 12/10/2007

function load() { }
