/**************************************************************************
Copyright : 2009 - GEOSIGNAL - www.geosignal.fr - contact@geosignal.fr
Projet :	GUADELOUPE	
**********************************************************************************/
OpenLayers.DOTS_PER_INCH = 96;
var PARAM_TRANSPOSE_MEASURE_UNITS = 10000;
var MEASURE_LONGUEUR = 'Distance';
var MEASURE_AREA = 'Surface';
var MEASURE_PERIMETRE = 'Périmètre';
var CMap = {
		divloadingId : 'visualisationLoading',
		visu : 'visualisation',
		visubg: 'zone2b',
		projection : 'EPSG:27572',
		mouseposition : { 
			div : 'infoCoord'
		},
		cadrageInit : false ,
		chargementInit : true ,
		slideFactor : 100 ,
		map : null,
		w : 0,
		h : 0,
		pan : null,
		zoomin : null,
		zoomout : null,
		fullextent : new OpenLayers.Bounds(307000,2220700,339500,2245500) ,
		hist : null,
		fond : null,
		resolutions : [39.6875,26.4583,13.2292,6.6146,2.6458,1.9844,1.3229,0.7938],
		maxRes : 39.6875,
		minRes : 0.7938,
		scale : ['1/150000', '1/100000', '1/50000', '1/25000', '1/10000', '1/7500', '1/5000', '1/3000'],
		layerVectoractive : null,
		init : function() {
		  /**
			** Outil de déplacement
			**/
			this.pan = new OpenLayers.Control.DragPan({
			              name: 'DragPan',
			              cursor: 'url(images/cursor/grab.cur), move',
			              handlerOptions: {
			                  cursors: {
			                      mousedown: 'url(images/cursor/grabbing.cur), move',
			                      mouseup: 'url(images/cursor/grab.cur), move'
			                  }
			              }
		     					});     	
		     					
			this.map = new OpenLayers.Map(this.visu , {
					        maxExtent: this.fullextent,
					        resolutions: this.resolutions,        
					        projection: this.projection,
					        fractionalZoom : false ,
					        units: "m",
					        minScale : 3000 ,
					        maxScale : 150000 ,
					        controls :[this.pan],
					        eventListeners: {
					            'movestart': this.mapMoveStart,
					            'move': this.mouseMove,
					            'moveend': this.mapMoveEnd,
					            'loadstart' : this.showLoading,
					            'loadend' : this.hideLoading,
					            'loadcancel' : this.hideLoading,
					            'zoomend': this.mapZoomEnd
					        }
		    });
			
			if(typeof(copyrighttexte) != "undefined"){
				copyrighttexte.initCopyrigth() ;
			}					
		},
		
		sendXload : function(param){
			navCurrent('sub',1,13);
			CMap.clearcontrol();
			CMap.zoomin.activate();
			statusopen(false);
			var url = "ajax.xload.php";
		  	new Ajax(url,{
				evalScripts: true,
				postBody: param,
				onComplete: function(originalResponse){
			    var vector = CMap.map.getLayersByName('gsMap') ;
			    vector[0].query = param ;
			    vector[0].redraw() ;
			    vector[0].query = "" ;
				}
			}).request();
		},
		
		sendXloadZoomin : function(param){
			navCurrent('sub',1,13);
			CMap.clearcontrol();
			CMap.zoomin.activate();
			statusopen(false);
			var url = "ajax.xload.php";
		  	new Ajax(url,{
				evalScripts: true,
				postBody: param, 
				onComplete: function(originalResponse){
				eval("var odata = "+originalResponse);
				if(odata.toeval) eval(odata.toeval);
				if(odata.minx){
					var minx = parseInt(odata.minx);
					var miny = parseInt(odata.miny);
					var maxx = parseInt(odata.maxx);
					var maxy = parseInt(odata.maxy);
					var mybounds = new OpenLayers.Bounds(minx, miny, maxx, maxy);
					var scaleAvantZoom = CMap.map.getScale() ;
					CMap.map.zoomToExtent(mybounds);
					var scaleApresZoom = CMap.map.getScale() ;
					if(Math.abs(scaleApresZoom - scaleAvantZoom) < 10)CMap.layerVector.redraw(true);
				} 
			 }
			}).request();
		},
		
		random : function(min, max){
			return Math.floor(Math.random() * (max - min + 1) + min);
		},
		reinitToZoom : function(){
			navCurrent('sub',1,13);
			CMap.clearcontrol();
			CMap.zoomin.activate();
			statusopen(false);
		},
		draw : function(extent) {
			extent = extent || false;
			if(!this.map) this.init();

				this.embedRaster() ;
		    this.layerVector = new OpenLayers.Layer.gsMap("gsMap", 
		        "x_load.php",
		        {
		            map: '',
		            h:this.h,
		            w:this.w
		        },
		        {
					    maxExtent: this.fullextent,
	            buffer: 0,
			isBaseLayer: false,  
	            visibility : true,
			opacity: 1,
	            async: true,
	            ratio: 1,
			        eventListeners: {
		            'loadstart' : this.showLoading,
		            'loadend' : this.hideLoading,
		            'loadcancel' : this.hideLoading
			        }
		        }
		    );
		    
		    this.layerVectoractive = new OpenLayers.Layer.gsMap("gsMapactive", 
		        "activexload.php",
		        {
		            map: '',
		            h:this.h,
		            w:this.w
		        },
		        {
					    maxExtent: this.fullextent,
	            buffer: 0,
			isBaseLayer: false,  
	            visibility : true,
			opacity: 1,
	            async: true,
	            ratio: 1
		        }
		    );
		    
		    //this.map.addLayer(this.layerVectoractive);
		    this.map.addLayer(this.layerVector);
		    this.layerVector.isActive = true;	
		    //this.layerVectoractive.isActive = true;
		    
				if(typeof(EchellePredef) != "undefined"){
					EchellePredef.initScale() ;
				}
    		
				this.settool();
				
				if(extent){
					this.map.zoomToExtent(new OpenLayers.Bounds(extent.minx,extent.miny,extent.maxx,extent.maxy));
					this.map.zoomToScale(5000);
				}
				else{
					this.map.zoomToExtent(this.fullextent);
				}
				return true ;
		},
				
		setsize : function(w, h) {
			this.w = w;
			this.h = h;
		},
		embedRaster : function(){
			if(typeof(FOND_CARTO) == 'undefined')return false ;
			for(var i=0; i < FOND_CARTO.length; i++){
				this.map.addLayer(FOND_CARTO[i].fond);
				FOND_CARTO[i].fondTileCache.isActive = true;	
			}
		},
		settool : function() {
    		
				/**
				** Outil de mesure linéaire
				**/
							    
				this.measureLine = new OpenLayers.Control.Measure(OpenLayers.Handler.Path.Ux, 
																			{
																			 left : 250,
																			 top : 10,
																			 cursor: 'crosshair', 
																			 displayUnits: 'km', 
																			 handlerOptions: {persist: true}
																			});
				this.map.addControl(this.measureLine);
				
				/**
				** Outil de mesure par polygone
				**/
				
				this.measurePoly = new OpenLayers.Control.Measure(OpenLayers.Handler.Polygon.Ux, 
																			{
																			 left : 250,
																			 top : 10,
																			 cursor: 'url(images/cursor/polysel.cur), move',
																			 displayUnits: 'km',
																			 handlerOptions: {persist: true}
																			});
		
				this.map.addControl(this.measurePoly);
				
				/**
				** Outil zoom moins
				**/
				
		    this.zoomout = new OpenLayers.Control.ZoomBox({cursor: 'url(images/cursor/zoomout.cur), move',out: true});								    
				this.map.addControl(this.zoomout);
				
				/**
				** Outil historique de zoom
				**/
				
				this.hist = new OpenLayers.Control.NavigationHistory();
				this.map.addControl(this.hist);
				
				
				/**
				** Selection point
				**/
				this.olSelectPoint = new OpenLayers.Control.SelectPoint(CMap.layerVector, {
				cursor: 'default',
				afterSelect: function(){
				}
			});

				this.map.addControl(this.olSelectPoint); 	
								
				/**
				** Selection rectangle
				**/
				this.xrect = new OpenLayers.Control.SelectRectangle(CMap.layerVector, {cursor: 'url(images/cursor/rectsel.cur), crosshair',afterSelect:ListeInfo.afficheSelection});
				this.map.addControl(this.xrect);
				
		    /**
		    * Outil zoom par scroll de la souris
		    **/
		    this.zoomwheel = new OpenLayers.Control.Navigation();
			  this.map.addControl(this.zoomwheel);
			  
		    /**
		    ** Carte de localisation
		    **/
		    
		    var ovExtent = new OpenLayers.Bounds(303823,2220700,342676,2245500);
		    var graphic = new OpenLayers.Layer.Image(
		        'clisson',
		        'images/refmap.gif',
		        ovExtent,
		        new OpenLayers.Size(188, 120),
		        {
		          maxExtent: ovExtent,
		      		resolutions: [206.6665708],
		          projection: CMap.projection
		        }
		    );
		    this.overview = new OpenLayers.Control.OverviewMap({
		        layers: [graphic],
		        div : $('refmap'),
		        size: new OpenLayers.Size(188, 120),
		        mapOptions: {
		            restrictedExtent: ovExtent
		        }
		    });
		    this.map.addControl(this.overview);
				/**
				** Outil zoom plus
				**/
				this.zoomin = new OpenLayers.Control.ZoomBox({
							        cursor: 'url(images/cursor/zoomin.cur), move',
							        name : 'zoomBoxIn',
							        handlerOptions: {
							            cursors: {
							                mousedown: 'url(images/cursor/zoomin.cur), move',
							                mouseup: 'url(images/cursor/zoomin.cur), move'
							            }
							        }    	
							    });	    
				this.map.addControl(this.zoomin);
				this.olSelectPoint.activate();	
	     	
		},
		setPanZoomBar : function(){
			if(Ext.get('movenorth')){
				Ext.getDom('movenorth').onclick = function(){
					CMap.map.pan(0, -CMap.slideFactor);
				};
			}
			if(Ext.get('movewest')){
				Ext.getDom('movewest').onclick = function(){
					CMap.map.pan(CMap.slideFactor, 0);
				};
			}
			if(Ext.get('moveeast')){
				Ext.getDom('moveeast').onclick = function(){
					CMap.map.pan(-CMap.slideFactor, 0);
				};
			}
			if(Ext.get('movesouth')){
				Ext.getDom('movesouth').onclick = function(){
					CMap.map.pan(0, CMap.slideFactor);
				};
			}
		},
		setfullextent : function () {
			this.map.zoomToExtent(this.fullextent);
			CMap.clearcontrol();
			CMap.zoomin.activate();
		},
		
		clearcontrol : function(){
			for(var i=0; i < this.map.controls.length ; i++){
				if(this.map.controls[i].CLASS_NAME != "OpenLayers.Control.NavigationHistory"){
					this.map.controls[i].deactivate() ;
				}
			}
    },
		mapMoveStart : function(e) {
			return ;
		},
		mouseMove : function(e) {
			if(!e.object.dragging){		
				if(this.measureLine)this.measureLine.clearMeasure();
				if(this.measurePoly)this.measurePoly.clearMeasure();
			}
			return ;
		},
		mapMoveEnd : function(e) {
			return ;
		},
		showLoading : function() {
			var divLoading = null ;
			if(!$(CMap.divloadingId)){
				var divLoading = document.createElement('div');
				divLoading.id = CMap.divloadingId ;
				divLoading.className = 'loading' ;
				divLoading.style.position = 'absolute' ;
				divLoading.style.zIndex = 500000 ;
				var mapDiv = $(CMap.visu) ;
				var positionDiv = mapDiv.getDimensions() ;
				var leftLoading = parseInt(190+positionDiv.width/2);
				var topLoading = parseInt(80+positionDiv.height/2);
				divLoading.style.left = leftLoading+'px' ;
				divLoading.style.top = topLoading+'px' ;
				document.body.appendChild(divLoading);
			}
			else divLoading = $(CMap.divloadingId) ;
				
			CMap.measureLine.clearMeasure() ;
			CMap.measurePoly.clearMeasure() ;
				
			if(divLoading == null) {
				return;
			}
			divLoading.style.display = 'block';
			if(typeof(Visualiser) != 'undefined')Visualiser.effacer();
		},
		hideLoading : function() {
			var echellecur = Math.round(CMap.map.getScale());
			$(DIVECHELLE).value = echellecur;	
			setSlider(echellecur);
			if(!$(CMap.divloadingId)) return;
			var divLoading = $(CMap.divloadingId);
			divLoading.style.display = 'none';
			if(CMap.cadrageInit){
				CMap.cadrageInit = false ;
				PlaceZoom() ;
			}
		},
		mapZoomEnd : function (e){
      return true ;
		},
		alerteExpire : function(){
		},
		verifSession : function(){
				new Ajax('x_load.php',{
				 	method:'post',
					postBody:{ 
			   		session: 'savename'
			    },
					evalScripts : true,		
					onComplete : function (request) {
						try {
							eval("var reponse1 = "+request);		
			      }
			      catch(e) {
			      	return;
			      }
			      if(res.erreur == 'session_expire'){
		   				CMap.alerteExpire() ;
		   			}
					}
				}).request();	
		}
};
