// make map available for easy debugging
var map;
var fichier_kml;

function selectionnerZone(lon, lat, zoom) {
	var defaultLonglat = new OpenLayers.LonLat(lon, lat);
	var wgs84 = new OpenLayers.Projection("EPSG:4326");
	var merc = new OpenLayers.Projection("EPSG:900913");
	defaultLonglat.transform(wgs84, merc);
	map.setCenter(defaultLonglat, zoom);
}

function doClick(feature) {	
	selectedFeature = feature;
	vis=[];
	if (feature.attributes.description.substr(0,3)=='new') {
		tab = eval(feature.attributes.description)
		afficherCommune(tab, true)
		selectControl.unselect(selectedFeature);
	} else {
		afficherVille(new Array(feature.attributes.name,feature.attributes.description),true)
		selectControl.unselect(selectedFeature);
	}	
}

// fonction pour forcer le cache sur les fichiers kml
//function code_random(){
//	return Math.round(Math.random()*1000000);
//}

// avoid pink tiles
OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
OpenLayers.Util.onImageLoadErrorColor = "transparent";

// TUILES JPG
function get_my_url (bounds) {
	var res = this.map.getResolution();
	var x = Math.round ((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
	var y = Math.round ((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
	var z = this.map.getZoom();

	var path = z + "/row" + y + "/" + z + "_" + x + "-" + y + ".jpg";
	var url = this.url;
	if (url instanceof Array) {
		url = this.selectUrl(path, url);
	}
	return url + path;
}

// fonction pour gerer les tuiles des rivieres
function get_my_url_gif (bounds) {
	var res = this.map.getResolution();
	var x = Math.round ((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
	var y = Math.round ((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
	var z = this.map.getZoom();

	var path = z + "/row" + y + "/" + z + "_" + x + "-" + y + ".gif";
	var url = this.url;
	if (url instanceof Array) {
		url = this.selectUrl(path, url);
	}
    return url + path;
}


// Initialisation
function init(lon, lat, zoom, div){

	function doubleClick(evt) {
		lonLat = map.getLonLatFromPixel(evt.xy);
        if (map.displayProjection) {
               lonLat.transform(map.getProjectionObject(), 
                                map.displayProjection );
		}  
       	//alert('lon='+lonLat.lon+' lat='+lonLat.lat+' zoom='+map.getZoom())
             
        if (controlerLonLat(lonLat.lon,lonLat.lat)) {
           		if (confirm("Voulez-vous signaler un phénomène à ces coordonnées ?")) {    
        			window.open('sys_choixPheno.php?lon='+lonLat.lon+'&lat='+lonLat.lat,'_self')
        		}
        }
    }
     
	PanBar = new OpenLayers.Control.PanZoom()
	PanBar.zoomWorldIcon = true
	
	// Remplacement de l'évènement double click par défaut qui fait un zoom par la signalisation d'un phénomène
	NavControl = new OpenLayers.Control.NavToolbar()
	NavControl.controls[0].defaultDblClick = doubleClick;
	
	var options = {
		projection: new OpenLayers.Projection("EPSG:900913"),
		displayProjection: new OpenLayers.Projection("EPSG:4326"),
		units: "m",
		numZoomLevels: 11,
		maxResolution: 156543.0339,
		maxExtent: new OpenLayers.Bounds(-20037508, -20037508,20037508, 20037508.34),
		restrictedExtent: new OpenLayers.Bounds(-20037508, -20037508,20037508, 20037508.34),
		controls: [PanBar, NavControl, new OpenLayers.Control.MousePosition(),
		new OpenLayers.Control.LayerSwitcher(),new OpenLayers.Control.ScaleBar()]
	}
	
	// Constructeur
	map = new OpenLayers.Map(div, options);
	
	// creation du fond carte_relief donnees en local
	var carte_relief = new OpenLayers.Layer.TMS("Relief", "../../relief/z", { 'getURL':get_my_url } ,{'maxZoomLevel':11,'buffer':1,'maxExtent': new OpenLayers.Bounds(-180,-90,180,90),
	'maxResolution': "auto"} );
	carte_relief.setIsBaseLayer(true);
	
	// creation de la couche Observations
	var observations = new OpenLayers.Layer.GML(
		"Observations", 
		"../kml/obs"+fichier_kml+".kml" , 
		{projection: new OpenLayers.Projection("EPSG:4326"), formatOptions: {extractAttributes: true, extractStyles: true, maxDepth:1}, 
		format: OpenLayers.Format.KML}
	)
	
	// creation de la couche des communes
	var communes = new OpenLayers.Layer.GML(
		"Communes", 
		"../kml/commune10000.kml" , 
		{projection: new OpenLayers.Projection("EPSG:4326"), formatOptions: {extractAttributes: true, extractStyles: true, maxDepth:0}, 
		format: OpenLayers.Format.KML}
	)
	communes.setVisibility(false);
	
	// creation de la couche hydro
    var water = new OpenLayers.Layer.TMS( "Fleuves-rivières","../../water/z",{ 'getURL':get_my_url_gif}  ,{'maxZoomLevel':9});
	water.setIsBaseLayer(false);
	water.setVisibility(false);

	// creation de la couche admin
	var admin = new OpenLayers.Layer.TMS( 
		"Régions-Agglomerations",
		"../../admin/z",
		{ 'getURL':get_my_url_gif},
		{'maxZoomLevel':11}
	);
	admin.setIsBaseLayer(false);
	admin.setVisibility(false);

	// Ajout des couches
	map.addLayers([carte_relief,communes,observations,water,admin]);
	map.zoomToMaxExtent(); 

	// initialise la carte centrage et zoom
	var wgs84 = new OpenLayers.Projection("EPSG:4326");
	var merc = new OpenLayers.Projection("EPSG:900913");
	var defaultLat = lat;
	var defaultLong = lon;
	var defaultLonglat = new OpenLayers.LonLat(defaultLong, defaultLat);
	defaultLonglat.transform(wgs84, merc);
	var defaultZoom = zoom;
	map.setCenter(defaultLonglat, defaultZoom);

	// permet de faire glisser la carte a la souris
	selectControl = new OpenLayers.Control.SelectFeature(
		[map.layers[1], map.layers[2]],
		{callbacks: {'click':doClick}
		}
	)
	map.addControl(selectControl);
	selectControl.activate();
	
	NavControl.controls[0].events.on({
		"activate": function(){
			selectControl.activate();
		},
		"deactivate": function(){
			selectControl.deactivate();
		}
	});
}

       
