var geoXml ;
var map ;
var cadre_map ;
var path_kml ;
var opt_global = {messagebox:false,nozoom:true,icontype:"style",noshadow:true};
var opt_camping = {messagebox:false,nozoom:true,width_icon:32,icontype:"style",noshadow:true};
var opt_geo ;
var type_map = "global";
var doit_maj ;
var id_camping ;
var num_diapo ;
var search ;
var overview;
var is_recherche = false ;
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.contains = function(t) { return this.indexOf(t) >= 0 ? true : false }
function jeval(str){
	return eval("("+str+")");
}
function ImageSize(src) {
	var newImg1 = new Image();
	newImg1.src = src;
	return {height:newImg1.height,width:newImg1.width};
}
function loadScript(callbackName) {	
	eval(callbackName+"();");
}
function is_def(va){
	return (typeof(va) != "undefined");
}
if(!Array.indexOf){
	    Array.prototype.indexOf = function(obj){
	        for(var i=0; i<this.length; i++){
	            if(this[i]==obj){
	                return i;
	            }
	        }
	        return -1;
	    }
	}
function load_googlemap(){	
	if (GBrowserIsCompatible()) 
	{  
		retaillFenetre();		
		map = new GMap2(cadre_map); 
		map.tab_id_cpg = new Array();
		map.tab_marker_default = new Array();
		if(type_map != "global"){
			map.setCenter(new GLatLng(lat,lon), zoo); 			
		}
		else{
			map.setCenter(new GLatLng(46.89023157359399, 4.04296875), 4);
			//map.setCenter(new GLatLng(49.4664306640625,-1.23532998561859), 10);
		}
		/*overview = new GOverviewMapControl();
		map.addControl(overview);*/
		map.addControl(new GMapTypeControl(),new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(40,7)));
		map.addMapType(G_PHYSICAL_MAP);
		map.enableScrollWheelZoom(); 		
		chargerKML();
		GEvent.addListener(geoXml,'parsed',event_parsed);
	}
	else{
		alert('Votre navigateur n\'est pas compatible avec cette carte');
	}	
}
var ecouteurAjoutes ;
function event_parsed(){
   /* if(type_map == "global")
	    maj_nb_camping();*/
    cacherAttente();
	if(!ecouteurAjoutes ){	
		GEvent.clearInstanceListeners(map);	
		GEvent.addListener(map, 'click',traite_marker );	
		GEvent.addListener(map, 'moveend', fin_mouvement);		
				GEvent.addListener(map, 'zoomend', traite_zoom);
	}
	
	    maj_nb_camping();
	/*if(map.getZoom() == zoom_anc && overlay_temp){		
		map.addOverlay(overlay_temp);
		overlay_temp = null;		
	}*/
	maj_nb_camping();
}
function aller_orig(){
	map.setCenter(new GLatLng(46.89023157359399, 4.04296875), 4);
	closeOverlay();
}

function traite_marker(overlay, point) {
	//si click sur marqueur
	if(overlay && overlay.openInfoWindow){		
		//si description vide alors c'est un regroupement, donc on zoome, sinon on affiche la description		
		if(type_map == "global" && (!overlay.title || overlay.title.trim() == "")){
			var nouvo_zoom = parseInt(map.getZoom())+1;
			map.setCenter(new GLatLng(overlay.getLatLng().lat(),overlay.getLatLng().lng()),(nouvo_zoom));			
		}			
	}	
}
function creer_url_maj_kml(){
	var bound = map.getBounds();
	var xmin = bound.getSouthWest().lng();
	var ymin = bound.getSouthWest().lat();
	var xmax = bound.getNorthEast().lng();
	var ymax = bound.getNorthEast().lat();
	var zoom = map.getZoom();	
	var path_aspx = (type_map == "global") ? "./kml/gen_kml.aspx" : "./kml/gen_kml_camp.aspx";
	if(type_map == "global"){
		if(map.getZoom() <= 5){
			path_kml =path_aspx+"?zoom="+map.getZoom();
		}
		else{
			path_kml = path_aspx+"?xmax="+xmax+"&ymax="+ymax+"&xmin="+xmin+"&ymin="+ymin+"&zoom="+zoom;
		}
		if(search){
			path_kml+= "&search="+search;
		}
	}
	else{
		path_kml = path_aspx+"?xmax="+xmax+"&ymax="+ymax+"&xmin="+xmin+"&ymin="+ymin+"&zoom="+zoom+"&id="+id_camping+"&d="+num_diapo;
	}		
	return path_kml ;
}
var timeout_fin_mouvement ;
function fin_mouvement(){
	if(timeout_fin_mouvement != null)
	    clearTimeout(timeout_fin_mouvement);
	timeout_fin_mouvement =setTimeout("traitement_fin_mouvement();",200);	
}
function traitement_fin_mouvement(){
      chargerKML();			 		
}


function traite_zoom(oldLevel,  newLevel){
	closeOverlay();
    var direction = oldLevel > newLevel ? -1 : 1;
    if(newLevel >= 17) direction = -1;
    if(newLevel <= 0) direction = +1;
    var validZoom = [3,4,6,8,10,12,14,16,17];
    if (validZoom.indexOf(newLevel) == -1) {
        map.setZoom(newLevel + direction);    
        return false ;    
    }	
    setDisabled('form_recherche_dispo',newLevel <= 6);
}


var timer = 0 ;
var timeout_parser_xml ;
var est_dispo = false ;
function chargerKML(){
    if(!est_dispo){
        document.getElementById(id_bt_annuler_recherche_dispo).style.display = 'none';
        var path_kml = creer_url_maj_kml();

	    if(geoXml == null ){
	        geoXml = new GeoXml("geoXml", map,path_kml,opt_geo);
	    }
	    else{
	   geoXml.tab_camp = new Array();
	        geoXml.url = path_kml;
	    }	
	    if(timeout_parser_xml != null)    
	        clearTimeout(timeout_parser_xml);
	     timeout_parser_xml = setTimeout("lancerParseGeoXML("+timer+");",500);
	 }
}
function chargerKMLDispo(path,mess){
    est_dispo = true ;
    document.getElementById(id_bt_annuler_recherche_dispo).style.display = 'inline';
    if(geoXml == null ){
	    geoXml = new GeoXml("geoXml", map,path,opt_geo);
	}
	else{
	    geoXml.url = path;
	    	geoXml.tab_camp = new Array();
	}	
	if(timeout_parser_xml != null)    
	    clearTimeout(timeout_parser_xml);
	 timeout_parser_xml = setTimeout("lancerParseGeoXML("+timer+");",500);
	 
}

function lancerParseGeoXML(id){
	if(timer == id){
		montrerAttente();
		map.clearOverlays();
		geoXml.parse(); 
	}
}
var div_attente ;
function montrerAttente(){

    $("div_attente").style.visibility = "visible";	
    $("img_attente").style.visibility = "visible";	
}
function cacherAttente(){
	$("img_attente").style.visibility = "hidden";
	$("div_attente").style.visibility = "hidden";
}
function centrerCarteSur(lat,lon,zoom,geonameid){
	search = geonameid;
	ferme_mpe(i_mpe_recherche);
	if(map.getZoom() == zoom){
		map.panTo(new GLatLng(lat,lon));
	}
	else{
		map.setCenter(new GLatLng(lat,lon), zoom);
	}
}

/****** fonction utilisée dans le tab de detail *****************/
var marker_cercle;
function entourerPoint(lat, lon){
	var fingerIcon =  new GIcon(); 
	fingerIcon.image = "./style/circle.png" ;
	fingerIcon.shadow = "";
	fingerIcon.iconSize = new GSize(28, 28);
	fingerIcon.iconAnchor = new GPoint(14, 14);
	fingerIcon.transparent = "";
	fingerIcon.printImage = "";
	fingerIcon.mozPrintImage = "";
	if(!marker_cercle){
        marker_cercle = new GMarker(new GLatLng(lat,lon),{icon:fingerIcon,zIndexProcess:importanceOrder});
        marker_cercle.importance  = 1;        
        map.addOverlay(marker_cercle);
    }
    else{
        marker_cercle.setLatLng(new GLatLng(lat,lon));
        marker_cercle.show();
    }	
}
function supprimerEntourage()
{
    if(marker_cercle)
	    marker_cercle.hide();
}
function afficheInfoWindowMarker(i){
	GEvent.trigger(geoXml.tab_marker[i],"click");
}
/*********************************************************/
//permet de mettre des marker au dessus des autres
function importanceOrder (marker,b) {
	return GOverlay.getZIndex(marker.getPoint().lat()) + marker.importance*1000000;
}



var currentMarker ;
var MyOverlay = function(marker, html) {
	this.marker = marker;
	this.html = html;
}
function subGPoints(a,b) {
	return new GPoint(a.x-b.x, a.y-b.y);
}    
function addGPoints(a,b) {
	return new GPoint(a.x+b.x, a.y+b.y);
} 

function change_pays(val){
	setTimeout("enable_region("+(val == "")+");",500) ;    
}
function enable_region(oui){
	document.getElementById(id_ddl_region).disabled = oui ;
}


//retourne un tableau contenant tout les marqueurs présent dans le cadre
function setMarkerBound(include_hidden){	
var tab_marker_bound;
    if(typeof(include_hidden) == "undefined") include_hidden = true ;
	var b = map.getBounds();
	tab_marker_bound = new Array();
	var l = geoXml.tab_marker.length;
	for(var i = 0;i<l;i++){
		var m = geoXml.tab_marker[i];
		if(b.contains(m.getPoint()) && (include_hidden || (!include_hidden && !m.isHidden()))) {
			tab_marker_bound.push(m);
		}		
	}
	return tab_marker_bound ;
}
//traite la réponse de la dispo
function reponse_dispo(str_cpg_64,err){
    if(err != null){ 
        alert(err);
    }
    else{
	    var str_id_cpg = "+"+decode64(str_cpg_64)+"+";
	    is_recherche = true ;
	    var tab_marker_bound = setMarkerBound();
	    var l = tab_marker_bound.length ;
	    for(var i = 0;i<l;i++){
		    if(tab_marker_bound[i].camping){
			    var c = tab_marker_bound[i].camping.id ;
			    if(!str_id_cpg.contains("+"+c+"+")){
				    tab_marker_bound[i].hide();
			    }
			    else{
			        tab_marker_bound[i].show();
				    tab_marker_bound[i].setImage("./style/camping_dispo.png");
			    }
		    }	
	    }
	    }
	//maj_nb_camping();
	cacherAttente()
}
//met a jour l'onglet du nombre de camping
function maj_nb_camping(){	
    if(est_dispo){
    document.getElementById("detail_recherche").style.display = 'block';
    var obj = {};			        
    obj.camps = new Array();
    for(var i = 0;i<geoXml.tab_camp.length;i++){
        obj.camps.push(geoXml.tab_camp[i]);
    }
	document.getElementById("liste_campings_resultat").innerHTML = TrimPath.processDOMTemplate("liste_cpg_jst",obj);
	}
	else{
	    document.getElementById("detail_recherche").style.display = 'none';
	}
	
}
function annuler_recherche(){
    var l = geoXml.tab_marker.length ;
    for(var i = 0;i<l;i++){
	    geoXml.tab_marker[i].show();
		geoXml.tab_marker[i].setImage("./style/camping.png");	
	}
	is_recherche = false ;
	//maj_nb_camping();
}

/****************** ENCODEUR /DECODEUR 64 *****************/
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
function encode64(input) {
	var output = "";
	var chr1, chr2, chr3;
	var enc1, enc2, enc3, enc4;
	var i = 0;
	do {
		chr1 = input.charCodeAt(i++);
		chr2 = input.charCodeAt(i++);
		chr3 = input.charCodeAt(i++);
		enc1 = chr1 >> 2;
		enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
		enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
		enc4 = chr3 & 63;
		if (isNaN(chr2)) {
			enc3 = enc4 = 64;
		} else if (isNaN(chr3)) {
			enc4 = 64;
		}
		output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + 
		keyStr.charAt(enc3) + keyStr.charAt(enc4);
	} while (i < input.length);
	return output;
}
function decode64(input) {
	var output = "";
	var chr1, chr2, chr3;
	var enc1, enc2, enc3, enc4;
	var i = 0;
	// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
	input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
	do {
		enc1 = keyStr.indexOf(input.charAt(i++));
		enc2 = keyStr.indexOf(input.charAt(i++));
		enc3 = keyStr.indexOf(input.charAt(i++));
		enc4 = keyStr.indexOf(input.charAt(i++));
		chr1 = (enc1 << 2) | (enc2 >> 4);
		chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
		chr3 = ((enc3 & 3) << 6) | enc4;
		output = output + String.fromCharCode(chr1);
		if (enc3 != 64) {
			output = output + String.fromCharCode(chr2);
		}
		if (enc4 != 64) {
			output = output + String.fromCharCode(chr3);
		}
	} while (i < input.length);
	return output;
}