// based on gxmarker.1.js
var overlay = new Array();

function GxMarkerNamespace() {

var n4=(document.layers);
var n6=(document.getElementById&&!document.all);
var ie=(document.all);
var o6=(navigator.appName.indexOf("Opera") != -1);
var safari=(navigator.userAgent.indexOf("Safari") != -1);

function GxMarker( a, b, tooltip, clickURL, ajax_div) {
    this.inheritFrom = GMarker;
    this.inheritFrom(a,b);
    if ( typeof tooltip != "undefined" ) {
        this.setTooltip( tooltip );
    }
	this.clickURL = clickURL;
	this.ajaxDiv = ajax_div;
}

GxMarker.prototype = new GMarker(new GLatLng(1,1));

GxMarker.prototype.setTooltip = function( string ) {
    this.tooltip = new Object();
    //this.tooltip.opacity  = 70;
    this.tooltip.contents = string;
};

GxMarker.prototype.initialize = function( a ) {
    try {
        GMarker.prototype.initialize.call(this, a);
        // Setup the mouse over/out events
		GEvent.bind(this, "mouseover", this, this.onMouseOver);
		GEvent.bind(this, "mouseout",  this, this.onMouseOut);
		GEvent.bindDom(this, "click",  this, this.onClick);
		this.map = a;
    } catch(e) {
	;
   }
}

GxMarker.prototype.remove = function( a ) {
    GMarker.prototype.remove.call(this);
    if ( this.tooltipObject )
        //this.map.div.removeChild(this.tooltipObject);
        document.body.removeChild(this.tooltipObject);
}

GxMarker.prototype.onInfoWindowOpen = function() {
    this.hideMouseOver();
    GMarker.prototype.onInfoWindowOpen.call(this);
}

GxMarker.prototype.onClick = function() {
	if (this.clickURL)
	{
		this.hideMouseOver();
		ajaxGET(this.clickURL, this.ajaxDiv);
	}
}

GxMarker.prototype.onMouseOver = function() {
    this.showMouseOver();
};

GxMarker.prototype.onMouseOut = function() {
    this.hideMouseOver();
};

GxMarker.prototype.showMouseOver = function() {
    if ( this.tooltip ) {
        if ( typeof this.tooltipObject == "undefined" ) {
            this.tooltipObject = document.createElement("div");
            this.tooltipObject.style.display    = "none";
            this.tooltipObject.style.position   = "absolute";
            this.tooltipObject.style.background = "#ffffff";
            this.tooltipObject.style.padding    = "0";
            this.tooltipObject.style.margin     = "0";
            this.tooltipObject.style.zIndex     = 50000;
            this.tooltipObject.innerHTML        = "<div class=\"markerTooltip\">" + this.tooltip.contents + "</div>";

/*
            var opacity = this.tooltip.opacity / 100;
            this.tooltipObject.style.MozOpacity = opacity;
            this.tooltipObject.style.filter     = "alpha(opacity=" + this.tooltip.opacity + ")";
            this.tooltipObject.style.opacity    = opacity;
*/

            document.body.appendChild(this.tooltipObject);
        }

		function getElementPosition(elem) {
		    var offsetTrail = elem;
		    var offsetLeft = 0;
		    var offsetTop = 0;
		    while (offsetTrail) {
		        offsetLeft += offsetTrail.offsetLeft;
		        offsetTop += offsetTrail.offsetTop;
		        offsetTrail = offsetTrail.offsetParent;
		    }
		    if (navigator.userAgent.indexOf("Mac") != -1 && 
		        typeof document.body.leftMargin != "undefined") {
		        offsetLeft += document.body.leftMargin;
		        offsetTop += document.body.topMargin;
		    }
		    return {left:offsetLeft, top:offsetTop};
		}


		var tlcLatLng = this.map.fromContainerPixelToLatLng(new GPoint(0,0), true);
		var tlcDivPixel = this.map.fromLatLngToDivPixel(tlcLatLng);
		var pointDivPixel = this.map.fromLatLngToDivPixel(this.getPoint());
		var c = new GPoint(pointDivPixel.x-tlcDivPixel.x, pointDivPixel.y-tlcDivPixel.y);
		var mapPos = getElementPosition(this.map.getContainer());

		this.tooltipObject.style.left = "-1000px";
        this.tooltipObject.style.top = "-1000px";
        this.tooltipObject.style.display = "block";

        var tipLeft = c.x - this.getIcon().iconAnchor.x + mapPos.left;
        if (tipLeft > (document.body.offsetWidth/2)) {
        	tipLeft -= this.tooltipObject.offsetWidth;
        } else {
        	tipLeft += this.getIcon().iconSize.width;
        }
        this.tooltipObject.style.left = tipLeft + "px";

        var tipTop = c.y - this.getIcon().iconAnchor.y + mapPos.top;
        if ((c.y + this.map.getContainer().offsetTop) > (this.map.getContainer().offsetHeight/2)) {
        	tipTop -= this.tooltipObject.offsetHeight;
        } else {
        	tipTop += this.getIcon().iconSize.height;
        }
        this.tooltipObject.style.top = tipTop + "px";
    }
}

GxMarker.prototype.hideMouseOver = function() {
    if ( typeof this.tooltipObject != "undefined" ) {
        this.tooltipObject.style.display = "none";
    }
}

function makeInterface(a) {
    var b = a || window;
    b.GxMarker = GxMarker;
}

makeInterface();
}

GxMarkerNamespace();

function showPopupIndex(index) {
	overlay[index].showMouseOver();
	//highlightMarker = new GMarker(overlay[index].getPoint(), createSliceIcon(index, SLICE_STYLE_HIGHLIGHTED));
	//map.addOverlay(highlightMarker);
}

function hidePopupIndex(index) {

	overlay[index].hideMouseOver();
	//map.removeOverlay(highlightMarker);
}


/*****************************/
/*** fonctions utilitaires ***/
/*****************************/

function load_without_controls()
{
  load('false');
}

function insideCreateIcon(icon_path, shadow_path)
{
	var icon_other = new GIcon();

	icon_other.image = icon_path;
	icon_other.shadow = shadow_path;

	icon_other.iconSize = new GSize(28, 37);
	icon_other.shadowSize = new GSize(50, 37);
	icon_other.iconAnchor = new GPoint(14, 37);
	icon_other.infoWindowAnchor = new GPoint(5, 1);

	return (icon_other);
}

var map = null;
/*var main_text = null;
var main_lat = null;
var main_long = null;

/* recupere taille de la carte pour connaie pos des 4 coins */
function getMapWindowInfos(Container, current_map)
{

	current_map.checkResize();
	var adjBounds = {};
	var center = current_map.getCenter();
	var lat = center.lng();
	var long = center.lat();
	var topDead = 25;
	var leftDead = 10;
	var rightDead = 5;
 	var bounds = current_map.getBounds();
	var lonPerPix = (bounds.getNorthEast().lng() - bounds.getSouthWest().lng())/Container.clientWidth;
	var latPerPix = (bounds.getNorthEast().lat() - bounds.getSouthWest().lat())/Container.clientHeight;
	var type = null;

	
	adjBounds['minlon'] = bounds.getSouthWest().lng() + leftDead*lonPerPix;
	adjBounds['maxlon'] = bounds.getNorthEast().lng() - rightDead*lonPerPix;
	adjBounds['minlat'] = bounds.getSouthWest().lat();
	adjBounds['maxlat'] = bounds.getNorthEast().lat() - topDead*latPerPix;
	adjBounds['long'] = long;
	adjBounds['lat'] = lat;
	if (document.getElementById('see_type'))
	{
		adjBounds['type'] = document.getElementById('see_type').value;
	}

	return adjBounds;
}

var polyline = null;

/* appelé pour mettre a jour les valeurs des 4 coins */
function updateMinMaxXY(m_min, m_max)
{
	var adjBounds = new Array();

	adjBounds['minlon'] = m_min.getPoint().x;
	adjBounds['minlat'] = m_min.getPoint().y;
	adjBounds['maxlon'] = m_max.getPoint().x;
	adjBounds['maxlat'] = m_max.getPoint().y;

	if (adjBounds['minlon'] > adjBounds['maxlon'])
		return(false);
	if (adjBounds['minlat'] > adjBounds['maxlat'])
		return(false);

	//var adjBounds = getMapWindowInfos(document.getElementById("map_div"));  
	document.getElementById('min_map_x').value = adjBounds['minlon'];
	document.getElementById('max_map_x').value = adjBounds['maxlon'];
	document.getElementById('min_map_y').value = adjBounds['minlat'];
	document.getElementById('max_map_y').value = adjBounds['maxlat'];

	map.removeOverlay(polyline);
	polyline = new GPolyline([
					new GLatLng(adjBounds['minlat'], adjBounds['minlon']),
					new GLatLng(adjBounds['minlat'], adjBounds['maxlon']),
					new GLatLng(adjBounds['maxlat'], adjBounds['maxlon']),
					new GLatLng(adjBounds['maxlat'], adjBounds['minlon']),
					new GLatLng(adjBounds['minlat'], adjBounds['minlon'])
					], "#FF0000", 5);
	map.addOverlay(polyline);
}

/* appele qd on bouge la carte, recharge les points */
function updateNearMap()
{
	var params = getMapWindowInfos(document.getElementById("bloc_map"), mapHome);
	var aff_result = '';

	if (document.getElementById('glgmap_event') && document.getElementById('glgmap_event').checked == true)
           aff_result = "&glgmap_event=true";
	if (document.getElementById('glgmap_album') && document.getElementById('glgmap_album').checked == true)
           aff_result = aff_result+"&glgmap_album=true";
	if (document.getElementById('glgmap_user') && document.getElementById('glgmap_user').checked == true)
           aff_result = aff_result+"&glgmap_user=true";
	if (document.getElementById('id_user_focus'))
           aff_result = aff_result+"&id_user_focus="+document.getElementById('id_user_focus').value;

	ajaxGET(admin_path+'ajax.php?section=/divers/update_map'+encode_tab_to_get(params)+aff_result, 'bloc_map_update');
}

/* initialisation de la carte */
function insideInitMap(controls, long, lat)
{
    GUnload();
    var point = new GLatLng(long, lat, 17);
    this.map = new GMap2(document.getElementById("map"));
    //GEvent.addListener(map, "moveend", updateNearMap);
    if (controls == 'true')
      {
	this.map.addControl(new GSmallMapControl());
	this.map.addControl(new GMapTypeControl());
      }
    else
      {
	this.map.addControl(new GSmallZoomControl());
      }
      this.map.setCenter(point, 16);
   copyrightTimer = window.setInterval('makeCopyrightSmaller()', 150);
    updateNearMap();
}

/* positionne à */
function CenterMapTo(long, lat)
{
    var point = new GLatLng(long, lat, 17);
    this.map.setCenter(point, 16);
}

/* reduit le copyright */
function makeCopyrightSmaller(map_cur) {
	if (map_cur.isLoaded()) 
	{
		for(var i = 0; i < map_cur.getContainer().childNodes.length; ++i) {
			if(map_cur.getContainer().childNodes[i].innerHTML.indexOf(String.fromCharCode(169)) !== -1){
      			map_cur.getContainer().childNodes[i].style.fontSize = '7px';
      			window.clearInterval(copyrightTimer);
      			break;
    		}
    	}
  	}
}


/** creation du marqueur **/

function insideCreateMarker(infos, local_map)
{
	var point = new GLatLng(infos.long, infos.lat, 17);
	var icon = insideCreateIcon(infos.icon, infos.icon_shadow);
	var txt = infos.title;
	var new_log = new GxMarker(point, icon, txt, infos.link, infos.ajax_div);
	local_map.addOverlay(new_log);
}



function encode_tab_to_get(param)
{
	var str = "";

	for (var i in param)
	{
		str = str+"&"+i+"="+param[i];		
	}
	return (str);
}



function aff_addr(point)
{
	if (document.getElementById('map_x'))
	{
		document.getElementById('map_x').value = point.y;
		document.getElementById('map_y').value = point.x;
	}
}

var geocoder = new GClientGeocoder();

function centerOnAdress(address, cur_map, zoom)
{
/*
  geocoder.getLocations(address, function(response) {
	 if (!response) {
	alert(address + " non trouvee");
	}
	else
	{
	place = response.Placemark[0];
	alert(place.Point.coordinates);
	var point = new GLatLng(place.Point.coordinates[0], place.Point.coordinates[1], 17);
	cur_map.setCenter(point, place.Point.coordinates[2]);
	}
}
);
*/
  geocoder.getLatLng(
		     address,
		     function(point) {
    if (!point) {
      alert(address + " non trouvee");
    } else {
      cur_map.setCenter(point, zoom);
	  var marker = new GMarker(point);
      cur_map.addOverlay(marker);
    }
  }
  );

}

function centerOnAdress2(address, cur_map, zoom)
{
  geocoder.getLatLng(
		     address,
		     function(point) {
    if (!point) {
      alert(address + " non trouvee");
    } else {
      cur_map.setCenter(point, zoom);
//	  var marker = new GMarker(point);
//      cur_map.addOverlay(marker);
    }
  }
  );

}


function showAddress(address, cur_map) {
  geocoder.getLatLng(
		     address,
		     function(point) {
    if (!point) {
      alert(address + " non trouvee");
    } else {
      aff_addr(point);
      cur_map.clearOverlays();
      cur_map.setCenter(point, 11);
      var marker = new GMarker(point);
      cur_map.addOverlay(marker);
      marker_flag = 1;
    }
  }
		     );
}


/******************************************************************/
/***** fonctions pour calculer la distance entre deux points  *****/
/******************************************************************/

// Utility function for converting degrees to radians
Math.deg2rad = function ( x ) {
        return x * (Math.PI / 180.0); 
}

// Distance in metres
var EARTH_RADIUS = 6367000;

// Calculates the distance (in metres) between 2 points. 
function distance_between_points ( p1, p2 ) {
        var a = Math.deg2rad( 90 - p1.y);
        var b = Math.deg2rad( 90 - p2.y);
        var theta = Math.deg2rad( p2.x - p1.x);
        var c = Math.acos( Math.cos(a) * Math.cos(b) + Math.sin(a) * Math.sin(b) * Math
.cos(theta));

        return c * EARTH_RADIUS; 
}

function aff_dist(div, x1, y1, x2, y2) {
 	var point1 = new GPoint(x1,y1);
 	var point2 = new GPoint(x2,y2);
	var dist = distance_between_points(point1, point2);
	dist = Math.round(dist / 100);
	dist = dist / 10;
	document.getElementById(div).innerHTML = dist+ " Km";
}




/*********************************/
/*** fonctions specifiques *******/
/*********************************/

function load_map_general()
{
  map = new GMap2(document.getElementById("map_general"));
  
  var point_tmp = new GLatLng(48.856558, 2.350966, 10);
  map.setCenter(point_tmp, 5);
  
  map.addControl(new GSmallMapControl());
  map.addControl(new GMapTypeControl());

  GEvent.addListener(map, "moveend", updateNearMap);
  updateNearMap();
}
