
var map;
var maxMarkers = 50;

/**
 *   Initialise une grande carte
 */
function initializeBigMap()
{
	if (GBrowserIsCompatible())
	{
		map = new GMap2(document.getElementById("bigmap"));
		map.addMapType(G_PHYSICAL_MAP);
		map.setMapType(G_HYBRID_MAP);
		map.setCenter(new GLatLng(46.60, 2.00), 6);
		map.enableScrollWheelZoom();
		map.enableContinuousZoom();

		/* first set of options is for the visual overlay.*/
        var boxStyleOpts = {
          opacity: .2,
          border: "2px solid red"
        }
        /* second set of options is for everything else */
        var otherOpts = {
          buttonHTML: "<img src='style/default/images/zoom-button.gif' />",
          buttonZoomingHTML: "<img src='style/default/images/zoom-button-activated.gif' />",
          buttonStartingStyle: {width: '24px', height: '24px'},
          stickyZoomEnabled: true,
		  rightMouseZoomOutEnabled: true,
		  minDragSize: 5
        };
		// add large map control under the zoom control since the large map control has different sizes...
        map.addControl(new ExtLargeMapControl(),
			new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7,7)));
		map.addControl(new DragZoomControl(boxStyleOpts, otherOpts, {}),
			new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(24,305)));

		// add controls...
		map.addControl(new GScaleControl());

		map.addControl(new GMapTypeControl(),
			new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0,0)));
		map.addControl(new google.maps.LocalSearch(),
			new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,20)));
		
		//GEvent.addListener(map,"move",showZooms);
		var kbdh = new GKeyboardHandler(map);

		GEvent.addListener(map, 'click', function(overlay, latlng, overlaylatlng) {
			if (overlay instanceof GMarker) {
				refreshPos(overlaylatlng);
                refreshPosGps(overlaylatlng);
			}
			else {
                if (latlng) {
                    refreshPosGps(latlng);
                }
			}
		});

		GEvent.addListener(map, 'zoomend', function(oldlevel, newlevel) {

		});

		attachMinimap(map);
		dynamicResizing(map);
	}
}

var mini;
var miniZoom = 0;
var ovMap;

function attachMinimap(map) {
	ovMap = new GOverviewMapControl();
	ovMap.setMapType(G_HYBRID_MAP);
	map.addControl(ovMap);

	GEvent.addListener(map, "maptypechanged", function() {
		if (map.getCurrentMapType() == G_SATELLITE_MAP) {
			ovMap.setMapType(G_HYBRID_MAP);
		} else {
			ovMap.setMapType(map.getCurrentMapType());
		}
	});

	// Délaye le rendu de la mini-carte pour accélérer le chargement de la carte principale
	window.setTimeout('mini=ovMap.getOverviewMap();', 1000);
}

/**
 *   Ajoute le nom de chaque couche dans la sidebar
 */
function addTR(id) {
	var layerTR = document.createElement("tr");
	var inputTD = document.createElement("td");
	var input = document.createElement("input");
	
	input.type = "checkbox";
	input.id = id;
	input.onclick = function () { /*toggleGeoXML(this.id, this.checked); */ refreshMap(); };
	inputTD.appendChild(input);

	var nameTD = document.createElement("td");
	var nameA = document.createElement("a");
	nameA.href = layers[id].url;

	var name = document.createTextNode(layers[id].name);
	nameA.appendChild(name);
	nameTD.appendChild(nameA);

	layerTR.appendChild(inputTD);
	layerTR.appendChild(nameTD);
	document.getElementById("sidebarTBODY").appendChild(layerTR);
}

/**
 *   Affiche ou cache une couche
 */
function toggleGeoXML(id, checked) {
	if (checked) {
		var geoXml = new GGeoXml(layers[id].url);

		GEvent.addListener(geoXml, 'load', function() {
				if (geoXml.loadedCorrectly()) {
					layers[id].geoxml = geoXml;
					document.getElementById("status").innerHTML = "";
				}
		});

		layers[id].geoXml = geoXml;
		map.addOverlay(layers[id].geoXml);
		document.getElementById("status").innerHTML = "Chargement...";
	}
	else if (layers[id].geoXml) {
		map.removeOverlay(layers[id].geoXml);
	}
}

/**
 *   Retourne la latitude avec 5 décimales à partir d'une position Google Maps
 */
function getLat(pos) {
	if(pos instanceof GLatLng) {
		var r = pos.lat().toString();
		var s = r.substring(0, r.indexOf("."));
		var t = r.substr(r.indexOf("."), 6);
		
		return s + t;
	} else {
		return 0;
	}
}

/**
 *   Retourne la longitude avec 5 décimales à partir d'une position Google Maps
 */
function getLng(pos) {
	if(pos instanceof GLatLng) {
		var u = pos.lng().toString();
		var v = u.substring(0, u.indexOf("."));
		var w = u.substr(u.indexOf("."), 6);
		
		return v + w;
	} else {
		return 0;
	}
}

/**
 *
 */
function refreshPos(pos) {
	document.getElementById('lat').value = getLat(pos);
	document.getElementById('lng').value = getLng(pos);
}

/**
 *
 */
function sanitize(str) {
	return addslashes(stripslashes(str_replace("\"", "'", str_replace("\r", "", str_replace("\n", " ", str)))));
}

/**
 *   Centre la carte sur les coordonnées fournies en effectuant un zoom
 */
function centerOn(map, lat, lng, zoom) {
	var pos = new GLatLng(lat, lng);
	
	if (zoom === undefined) {
		map.panTo(pos);
	}
	else {
		map.setZoom(zoom);
		map.panTo(pos);
	}
}

/**
 *
 */
function download(params) {
	document.location = getLink(params);
}

/**
 *
 */
function getLink(params) {
	return "index.php?" + xhr.MakeQuerystring(params);
}

/**
 *
 */
function changeImage(id, src) {
	document.getElementById(id).src = src;
}

/**
 *
 */
function getUsername() {
	return document.getElementById('userLogin').value;
}

/**
 *	Affiche ou fait disparaitre l'élément div et modifie le text associé
 */
function expandCollapse(div, text) {
	var block = document.getElementById(text);

	if (document.getElementById(div).style.display == "none") {
		block.innerHTML = "- " + block.innerHTML.substr(2, block.innerHTML.length - 2);
		document.getElementById(div).style.display = "block";
	} else {
		block.innerHTML = "+ " + block.innerHTML.substr(2, block.innerHTML.length - 2);
		document.getElementById(div).style.display = "none";
	}
}


var xhr = {};

/**
  *   Exécute une requête XMLHttpRequest en mode POST.
  *   Les paramètres à fournir doivent être sous la forme d'un tableau à deux dimensions.
  *
  *   Paramètres :
  *			postData	tableau envoyé dans la requête
  *						[[ 'lat', getLat(pos) ],
  *						 [ 'lng', getLng(pos) ],
  *						 [ 'name', name.value ]];
  *			dataPage	url indiquant la page à interroger
  *			elementToUpdate
  *			callback	si true, elementToUpdate doit être une méthode javascript appelée en callback dès que la requête est terminée (à passer en paramètre sans les parenthèses).
  *						si false, elementToUpdate doit être un élément HTML ayant une balise d'ouverture et une de fermeture (pas img, br, ...).
  */
xhr.Query = function (postData, dataPage, elementToUpdate, callback)
{
	if (callback === undefined) {
		callback = true;
	}
	var XHR = xhr.Create();

	if (callback) {
		XHR.onreadystatechange = function() {
			if (XHR.readyState == 4) {
				if (elementToUpdate != null) {
					elementToUpdate();
				}
			}
		}
	}
	else {
		XHR.onreadystatechange = function() { // attribution de la fonction
			if (XHR.readyState == 4 ) {
				if (elementToUpdate != null) {
					elementToUpdate.innerHTML = XHR.responseText;
				}
			}
		}
	}

	XHR.open('POST', dataPage, true);
	XHR.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	
	if (postData != null) {
		XHR.send(xhr.MakeQuerystring(postData));
	}
	else {
		XHR.send(null);
	}
}

/**
  *   Crée un objet XMLHttpRequest
  */
xhr.Create = function() {
    var request = false;
	try {
		request = new ActiveXObject('Msxml2.XMLHTTP');
	}
	catch (err2) {
		try {
			request = new ActiveXObject('Microsoft.XMLHTTP');
		}
		catch (err3) {
			try {
				request = new XMLHttpRequest();
			}
			catch (err1) {
				request = false;
			}
		}
	}
    return request;
}

/**
  *   Transforme le tableau à deux dimensions en chaîne de paramètres POST GET
  */
xhr.MakeQuerystring = function (data) {
	var str = '';
	
	for (var i=0; i < data.length; i++)
		str = str + data[i][0] + '=' + data[i][1] + '&';
		
	str = substr(str, 0, str.length-1);

	// For itératif incompatible avec IE
	//for each (var d in data) {
	//	str = str + d[0] + '=' + d[1] + '&';
	//}
	return str;
}




/**
  *   A le même effet que la fonction PHP du même nom
  */
function addslashes( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   improved by: marrtins
    // +   improved by: Nate
    // +   improved by: Onno Marsman
    // *     example 1: addslashes("kevin's birthday");
    // *     returns 1: 'kevin\'s birthday'
 
    return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0");
}

function stripslashes( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +      fixed by: Mick@el
    // +   improved by: marrtins
    // +   bugfixed by: Onno Marsman
    // +   improved by: rezna
    // *     example 1: stripslashes('Kevin\'s code');
    // *     returns 1: "Kevin's code"
    // *     example 2: stripslashes('Kevin\\\'s code');
    // *     returns 2: "Kevin\'s code"
 
    return (str+'').replace(/\0/g, '0').replace(/\\([\\'"])/g, '$1');
}

function htmlentities (string, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: nobbler
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: get_html_translation_table
    // *     example 1: htmlentities('Kevin & van Zonneveld');
    // *     returns 1: 'Kevin &amp; van Zonneveld'
 
    var histogram = {}, symbol = '', tmp_str = '', i = 0;
    tmp_str = string.toString();
    
    if (false === (histogram = get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
    
    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
    
    return tmp_str;
}

function substr( f_string, f_start, f_length ) {
    // http://kevin.vanzonneveld.net
    // +     original by: Martijn Wieringa
    // +     bugfixed by: T.Wild
    // +      tweaked by: Onno Marsman
    // *       example 1: substr('abcdef', 0, -1);
    // *       returns 1: 'abcde'
    // *       example 2: substr(2, 0, -6);
    // *       returns 2: ''
 
    f_string += '';
 
    if(f_start < 0) {
        f_start += f_string.length;
    }
 
    if(f_length == undefined) {
        f_length = f_string.length;
    } else if(f_length < 0){
        f_length += f_string.length;
    } else {
        f_length += f_start;
    }
 
    if(f_length < f_start) {
        f_length = f_start;
    }
 
    return f_string.substring(f_start, f_length);
}

function strlen (string) {
    // Get string length  
    // 
    // version: 810.1317
    // discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_strlen

    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Sakimori
    // +      input by: Kirk Strobeck
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // *     example 1: strlen('Kevin van Zonneveld');
    // *     returns 1: 19
    return (string+'').length;
}

function str_replace(search, replace, subject) {
    // Replaces all occurrences of search in haystack with replace  
    // 
    // version: 812.1017
    // discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_str_replace

    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'
    var f = search, r = replace, s = subject;
    var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;

    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = (s[i]+'').split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    };

    return sa ? s : s[0];
}

function str_split ( f_string, f_split_length){
    // Convert a string to an array. If split_length is specified, break the string down into chunks each split_length characters long.  
    // 
    // version: 810.1317
    // discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_str_split

    // +     original by: Martijn Wieringa
    // +     improved by: Brett Zamir
    // +     bugfixed by: Onno Marsman
    // *         example 1: str_split('Hello Friend', 3);
    // *         returns 1: ['Hel', 'lo ', 'Fri', 'end']
    f_string += '';

    if (f_split_length == undefined) {
        f_split_length = 1;
    }
    if(f_split_length > 0){
        var result = [];
        while(f_string.length > f_split_length) {
            result[result.length] = f_string.substring(0, f_split_length);
            f_string = f_string.substring(f_split_length);
        }
        result[result.length] = f_string;
        return result;
    }
    return false;
}


function trim (str, charlist) {
    // Strips whitespace from the beginning and end of a string  
    // 
    // version: 812.316
    // discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_trim

    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: mdsjack (http://www.mdsjack.bo.it)
    // +   improved by: Alexander Ermolaev (http://snippets.dzone.com/user/AlexanderErmolaev)
    // +      input by: Erkekjetter
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: DxGx
    // +   improved by: Steven Levithan (http://blog.stevenlevithan.com)
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // *     example 1: trim('    Kevin van Zonneveld    ');
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: trim('Hello World', 'Hdle');
    // *     returns 2: 'o Wor'
    // *     example 3: trim(16, 1);
    // *     returns 3: 6
    var whitespace, l = 0, i = 0;
    str += '';
    
    if (!charlist) {
        // default list
        whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
    } else {
        // preg_quote custom list
        charlist += '';
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\$1');
    }
    
    l = str.length;
    for (i = 0; i < l; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        }
    }
    
    l = str.length;
    for (i = l - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    
    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

function get_html_translation_table(table, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js. Meaning the constants are not
    // %          note: real constants, but strings instead. integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // %          note: Table from http://www.the-art-of-web.com/html/character-codes/
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, histogram = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    useTable      = (table ? table.toUpperCase() : 'HTML_SPECIALCHARS');
    useQuoteStyle = (quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT');
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
    
    // Map numbers to strings for compatibilty with PHP constants
    if (!isNaN(useTable)) {
        useTable = constMappingTable[useTable];
    }
    if (!isNaN(useQuoteStyle)) {
        useQuoteStyle = constMappingQuoteStyle[useQuoteStyle];
    }
    
    if (useTable == 'HTML_SPECIALCHARS') {
        // ascii decimals for better compatibility
        entities['38'] = '&amp;';
        entities['60'] = '&lt;';
        entities['62'] = '&gt;';
    } else if (useTable == 'HTML_ENTITIES') {
        // ascii decimals for better compatibility
      entities['38'] = '&amp;';
      entities['60'] = '&lt;';
      entities['62'] = '&gt;';
      entities['160'] = '&nbsp;';
      entities['161'] = '&iexcl;';
      entities['162'] = '&cent;';
      entities['163'] = '&pound;';
      entities['164'] = '&curren;';
      entities['165'] = '&yen;';
      entities['166'] = '&brvbar;';
      entities['167'] = '&sect;';
      entities['168'] = '&uml;';
      entities['169'] = '&copy;';
      entities['170'] = '&ordf;';
      entities['171'] = '&laquo;';
      entities['172'] = '&not;';
      entities['173'] = '&shy;';
      entities['174'] = '&reg;';
      entities['175'] = '&macr;';
      entities['176'] = '&deg;';
      entities['177'] = '&plusmn;';
      entities['178'] = '&sup2;';
      entities['179'] = '&sup3;';
      entities['180'] = '&acute;';
      entities['181'] = '&micro;';
      entities['182'] = '&para;';
      entities['183'] = '&middot;';
      entities['184'] = '&cedil;';
      entities['185'] = '&sup1;';
      entities['186'] = '&ordm;';
      entities['187'] = '&raquo;';
      entities['188'] = '&frac14;';
      entities['189'] = '&frac12;';
      entities['190'] = '&frac34;';
      entities['191'] = '&iquest;';
      entities['192'] = '&Agrave;';
      entities['193'] = '&Aacute;';
      entities['194'] = '&Acirc;';
      entities['195'] = '&Atilde;';
      entities['196'] = '&Auml;';
      entities['197'] = '&Aring;';
      entities['198'] = '&AElig;';
      entities['199'] = '&Ccedil;';
      entities['200'] = '&Egrave;';
      entities['201'] = '&Eacute;';
      entities['202'] = '&Ecirc;';
      entities['203'] = '&Euml;';
      entities['204'] = '&Igrave;';
      entities['205'] = '&Iacute;';
      entities['206'] = '&Icirc;';
      entities['207'] = '&Iuml;';
      entities['208'] = '&ETH;';
      entities['209'] = '&Ntilde;';
      entities['210'] = '&Ograve;';
      entities['211'] = '&Oacute;';
      entities['212'] = '&Ocirc;';
      entities['213'] = '&Otilde;';
      entities['214'] = '&Ouml;';
      entities['215'] = '&times;';
      entities['216'] = '&Oslash;';
      entities['217'] = '&Ugrave;';
      entities['218'] = '&Uacute;';
      entities['219'] = '&Ucirc;';
      entities['220'] = '&Uuml;';
      entities['221'] = '&Yacute;';
      entities['222'] = '&THORN;';
      entities['223'] = '&szlig;';
      entities['224'] = '&agrave;';
      entities['225'] = '&aacute;';
      entities['226'] = '&acirc;';
      entities['227'] = '&atilde;';
      entities['228'] = '&auml;';
      entities['229'] = '&aring;';
      entities['230'] = '&aelig;';
      entities['231'] = '&ccedil;';
      entities['232'] = '&egrave;';
      entities['233'] = '&eacute;';
      entities['234'] = '&ecirc;';
      entities['235'] = '&euml;';
      entities['236'] = '&igrave;';
      entities['237'] = '&iacute;';
      entities['238'] = '&icirc;';
      entities['239'] = '&iuml;';
      entities['240'] = '&eth;';
      entities['241'] = '&ntilde;';
      entities['242'] = '&ograve;';
      entities['243'] = '&oacute;';
      entities['244'] = '&ocirc;';
      entities['245'] = '&otilde;';
      entities['246'] = '&ouml;';
      entities['247'] = '&divide;';
      entities['248'] = '&oslash;';
      entities['249'] = '&ugrave;';
      entities['250'] = '&uacute;';
      entities['251'] = '&ucirc;';
      entities['252'] = '&uuml;';
      entities['253'] = '&yacute;';
      entities['254'] = '&thorn;';
      entities['255'] = '&yuml;';
    } else {
        throw Error("Table: "+useTable+' not supported');
        return false;
    }
    
    if (useQuoteStyle != 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    
    if (useQuoteStyle == 'ENT_QUOTES') {
        entities['39'] = '&#039;';
    }
    
    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal)
        histogram[symbol] = entities[decimal];
    }
    
    return histogram;
}