
var swfIsReady = false;
var SVGloadCompled=false;




function setSwfReady(){
	SVGloadCompled=true;
	// alert('set swf ready par map');
	swfIsReady=true;
}
function SVGloadCompled(){

	if(	SVGloadCompled){
		return 1;
	}else{
		
		return false;
	}
}

var HTTP_PREFIX = "http://";
try{
  if(parent.HTTP_PREFIX && parent.HTTP_PREFIX =="https://")
  {
  	HTTP_PREFIX = "https://";
  }
}catch( e ){
  if(window.HTTP_PREFIX && window.HTTP_PREFIX =="https://")
  {
  	HTTP_PREFIX = "https://";
  }
}

var DynmapVueGlobale = Class.create();
DynmapVueGlobale.prototype={
	initialize:function(divVueGlobale,mapJs,params,gestEvtDyn){
		this.mapJs=mapJs;
		this.tmpBBox=false;
		this.swfIsReady=false;
		this.inited=false;
		this.nameObj=params.reflexionName;
		
		this.divVueGlobale=divVueGlobale;
		this.gestEvtDyn=gestEvtDyn;
	
		this.gestEvtDyn.ajouteEcouteur('MAPMOVED',this.onMapMoved,this);
		this.gestEvtDyn.ajouteEcouteur('VUEGLOBALEENABLED',this.onvueGlobalEnabled,this);

		swf="/dynmap/flashengine/vueGlobale/dynmapVueGlobale.swf";


		this.embedScript='<div id="vueGlobale"><object id="'+divVueGlobale+'flashVG" type="application/x-shockwave-flash" data="'+swf+'" width="'+params.width+'" Height="'+params.height+'">'
		+ '<param name="movie" value="/dynmap/flashengine/vueGlobale/dynmapVueGlobale.swf" />'
		+ ' <param name="wmode" value="transparent" />'
		+ '<param name="flashVars" value="pathApplication='+params.pathApplication+'&xmin='+params.xmin+'&ymin='+params.ymin+'&dx='+params.dx+'&dy='+params.dy+'&width='+params.width+'&height='+params.height+'&reflexionName='+params.reflexionName+'"'
		+'/>'
		+ '</object></div>';

	},
	lanceEvenement:function(nameE,arrParam){
try{
		this.gestEvtDyn.lanceEvenement(nameE,arrParam);
}catch(e){
	
	//alert(e.message);
}
	},
	
	onvueGlobalEnabled:function(nomVueGlobale){
		if(nomVueGlobale==this.nameObj){
			this.swfIsReady=true;
		}
		
		if(this.tmpBBox!=false){
			var fla=$(this.divVueGlobale+'flashVG');
			try{
			   fla.onMapMoved(this.tmpBBox);
			}catch(e){
      
      }
		}
	},
	onMapMoved:function(bBox){

		if(this.swfIsReady){
			var fla=$(this.divVueGlobale+'flashVG');
			try{
			
			fla.onMapMoved(bBox);
			}catch(e){
				//flash cachÃ©.  on s'interrompt silencieusement.
			}
			
		}else{

			this.tmpBBox=bBox;
		}

	},
	
	initializeVueGlobale:function(){
		
		$(this.divVueGlobale).innerHTML=this.embedScript;


	},
	goToNewBBox:function(newBox){

		this.mapJs.mapFlashWrapper.goToBBox(newBox);
	}

}

var SelectionStyle=Class.create();

SelectionStyle.prototype={
		initialize:function(map){
			this.map=map;
			this.s={
					'fillHexa':'#FF000',
					'strokeHexa':'#FF000',
					'fillOpacity'	:0.5,
					'strokeOpacity':0.5,
					'strokeWidth'	:'0.5%'
			}
			this.couleurDispo={
					"#FF0000":'rouge',
					"#99ccff":'bleu clair',
					"#0000cc":'bleu',
					"#33ff33":'vert clair',
					"#009933":'vert',
					"#ffff33":'jaune',
					"#990099":'rose',
					"#ff9933":'violet'
					
			};
		},
		setPersoColor:function (params){
			this.s['fillHexa']=params.fill;
			this.s['strokeHexa']=params.stroke;
			this.s['fillOpacity']=params['fill-opacity'];
			this.s['strokeOpacity']=params['stroke-opacity'];
			this.s['strokeWidth']=params['stroke-width'];
			var Arrtour=[this];
			this.personnel=1;
			GestEvtDyn.lanceEvenement("TYPESELECTION",Arrtour);
		},
		setColor:function(color){
			this.s['fillHexa']=color;
			this.s['strokeHexa']=color;
			var Arrtour=[this];
			this.personnel=0;
		
			GestEvtDyn.lanceEvenement("TYPESELECTION",Arrtour);
			Debug("couleur de selection modifie "+color);
		}

};
var ModSel;



var DynmapLayer = Class.create();
DynmapLayer.prototype = {
		
	initialize:function(map){
		this._map=map;
	},
	setVisibility:function(flag){
		this.visibility = flag;
		this._map.chgStateLayer(this.layerId,flag);
		return this;
	},
	refresh:function(){
		this._map.chgStateLayer(this.layerId,this.visibility,1);
	},
	reset:function(){
		this._map.resetLayer(this.layerId);
	},
	mask:function(idObjects){
		var tp = idObjects.split(',');
		var tp2= [];
		for(var i=0;i<tp.length;i++){
			tp2.push(this.layerId+'.'+tp[i]);
		}
		this._map.mask(tp2.join(',',true,true));
	}

}

var DynmapMap=Class.create();
DynmapMap.prototype={

	initialize:function(carteDynmap,params){
		this.params = {
			typeAccess:       'dynmap',
			bgColor: 'FFFFFF',
			parameters: '',
			minWidth:0,
			minHeight:0,
			echelle: 1,
			width: 640,
			height: 480,
			firstInfo:false,
			buffer:0,
			lT:300,
			contextMap:0,
			mask:'',
			anchor:false,
			anchorRayon:5,
			tT:300,
			url:encodeURIComponent(window.location.search),
			menu:['selection','navigation','parametrage','mesure','annotation','export','dessin'],
			resize:false,
			styles:{'draw':
					{'x': 10,'y':10}
					,
					'waiter':
					{'top': 10,'right':10}
					},
			firstAction:'initBbox'
		}.extend(params || {});
	
		this.dynmap_url='/dynmap/flashengine/dynmapcontroler.php?';
		this.recherche_url='/dynmap/recherche/recherche_js_to_php.class.php?';
		this.geographie_url='/dynmap/geom/geom_js_to_php.class.php?';
		this.path_application=this.params.path_application;
		this.carteDynmap=carteDynmap;
		this.xmin=0;
		this.ymin=0;
		this.dx=0;
		this.dy=0;
		this._findComplete = 1;
		this.typeFindSel='select';
		this.typeFindSelUn=false;
		this.lastTypeFind="";
		this._lastBBox=false;
		this.cr=true;
		this._tbidesact=[];
		//initialisation
		
		this._layers= {};
		this.ixmin=0;this.yymin=0;this.idx=0;this.idy=0;
		this.symboleLocalisation={'url':'/dynmap/images/cible.swf','px':'20'}
		this.selStyle= new SelectionStyle(this);
		//this.selStyle.map
		ModSel=this.selStyle;
		GestEvtDyn.ajouteEcouteur('TYPESELECTION',this.setStyleSelection,this);
		GestEvtDyn.ajouteEcouteur('SETHIGHLIGHT',this.drawTmpHilight,this);
		GestEvtDyn.ajouteEcouteur('RMHIGHLIGHT',this.RmHilight,this);
		GestEvtDyn.ajouteEcouteur('ANALYSEMODIFIED',this.a_am,this);
		GestEvtDyn.ajouteEcouteur('ELEMENTS_LOCALIZED',this.a_el,this);
	
	},
	tes:function(varT){
		alert(varT);
	},
	lanceEvenement:function(nameE,arrParam){
		try{
			GestEvtDyn.lanceEvenement(nameE,arrParam);
		}catch(e){
			
			//alert(e.message);
		}
			},
	a_el:function(){
		GestEvtDyn.ajouteEcouteur('LOADMAPDATAFIN',this.a_el2,this);
	},
	a_el2:function(){
		GestEvtDyn.enleveEcouteur('LOADMAPDATAFIN',this.a_el2);
		this._findComplete = 1;
	},
	resizeMap:function(w,h){
		//alert('resize');
			this.params.w=w;
			this.params.h=h;
			this.params.width=w;
			this.params.height=h;

			this.cr=false;
			setTimeout(
		               this.okR.bind(this)
		            , 100);
		           
		 try{
			this.mapFlashWrapper.width=w;
			this.mapFlashWrapper.height=h;
	
			this.mapFlashWrapper.resizeMap(w,h);
		 }catch(e)
		 {}	
		
			
	},

	setStyleObject:function(idObject,styleStr){
		styleStr=styleStr.replace(/"/g,'');
	
		this.mapFlashWrapper.setStyle(idObject,styleStr);
	},
	askModifyObject:function(p){
		idObject=p.idObject;
		var url='/dynmap/class/modules/mvccarte.php?path_application='+this.path_application;
		url+='&cont=STYLEPICKER&event=modifyStyleObject&idObject='+idObject;
			//mvccarte.php?cont=STYLEPICKER&event=getCurrentStyleAnnotation&path_application=
		this.openWindow({'url':url});
	},
	inverseSelectionO:function(obj){
		
		this.inverseSelection(obj.couche,obj.typeIntersection,obj.buffer);
	},
	inverseSelection:function(couche,typeD,buffer){
	
		if(typeD==undefined){
			typeD='intersect';
		}
		if(buffer==undefined){
			buffer=this.params.buffer;
		}else{
		
		}

		var tempParam = 'method=INVERSELECTION&typeD='+typeD+'&couche='+couche+'&buffer='+buffer+'&objs=SELECTION';
		this.appelServeur(tempParam, this.a_inverseSelection,this,this.geographie_url,'post');
	},
	a_inverseSelection:function(res){
		if(res.responseText){
			var NoFind=0;
			var listeElem="";
			arrELEMENT=res.responseText.split("[e]");

			for(var i=0;i<arrELEMENT.length;i++){
				if(arrELEMENT[i]!=""){
					listeElem=listeElem + arrELEMENT[i]+',';

				}
			}
			
			this.findAndSelect(listeElem,true,'','2', '1');
		}
	},
	a_am:function(ida){
		var tabA=ida.split('-');
		ida=tabA[0];
		 tabA=this.getAnalysesActives();
		for(var i=0;i<tabA.length;i++){
			if(tabA[i]==ida){
				 this.chgStateAnalyse(ida, 1, "");
				 break;
			}
		}
	},
	drawTmpHilight:function(idObjs){
	
		var tabIds=idObjs.split(',');
		this.mapFlashWrapper.outDraw(tabIds,true);
	},
	RmHilight:function(idObjs){
		var tabIds=idObjs.split(',');
		this.mapFlashWrapper.outDraw(tabIds,false);
	},
	setAnchorLayer:function(idLayer,anchorRayon){
		
		this.params.anchor=idLayer;
		this.params.anchorRayon=anchorRayon;
		this.mapFlashWrapper.setAnchorLayer(idLayer,anchorRayon);
	},
	getAnchorLayer:function(){
		
		return this.params.anchor;
	},
	alert:function(msg){
		this.api().alert(msg);
	},
	setStyleSelection:function(ev){
	
	    this.mapFlashWrapper.setStyleSelection(ev.s);
	},
	editOptions:function(){
		var linkOpener="/dynmap/class/modules/mvccarte.php?cont=PARAMETRECLIENT&event=getInterface&path_application="+path_application;
		window.open(linkOpener,"","width=640,height=300,scrollbars=yes,resizable=yes,status=yes");
	},
	changeCss:function(ev){
	    this.mapFlashWrapper.changeCss(ev);
	},
	proxyEvt:function(ev){
	
		if (ev.wheelDelta) { /* IE/Opera. */
                ev.delta = event.wheelDelta/120;
                /** In Opera 9, delta differs in sign as compared to IE.
                 */
                if (window.opera)
                        ev.delta = -ev.delta;
        } else if (ev.detail) { /** Mozilla case. */
                /** In Mozilla, sign of delta is different than in IE.
                 * Also, delta is multiple of 3.
                 */
                ev.delta = -ev.detail/3;
        }
        this.mapFlashWrapper.proxyWheel2({'delta': ev.delta });
		Event.stop(ev);
	
	},
	goToBBox:function(newBox){
		this.mapFlashWrapper.goToBBox(newBox);
		 
	},
	removeItem:function(ide){
	
		this.mapFlashWrapper.removeItem(ide);
	},
	okR:function(){
		this.cr=true;
	},
	loadMap:function(){

		this.mapFlashWrapper=this.getSWF(this.carteDynmap);
		Event.observe(this.mapFlashWrapper, 'mousewheel', this.proxyEvt.bindAsEventListener(this));
		Event.observe(this.mapFlashWrapper, 'DOMMouseScroll', this.proxyEvt.bindAsEventListener(this));
		
		this.initParamsUrl();
		//retaillage de la carte
		if(this.params.resize){
			
			this.cr=false;
			setTimeout(
		               this.okR.bind(this)
		            , 100);
			this.params.width=$('IEhackInnerHeight').offsetLeft-this.params.lT;
		
			this.params.height=$('IEhackInnerHeight').offsetTop -this.params.tT;
			
		}
		
		this.mapFlashWrapper.width=this.params.width;
		this.mapFlashWrapper.height=this.params.height;
		
		
		this.mapFlashWrapper.loadMap(this.params); 

	
	},
	getWindowDimension:function(){
		var ob={};
		ob.width= $('IEhackInnerHeight').offsetLeft;
		ob.height =$('IEhackInnerHeight').offsetTop ;
		return ob;
	},
	loadModule:function(nm,p){
		this.mapFlashWrapper.loadModule(nm,p);
	},
	unloadModule:function(nm){
		this.mapFlashWrapper.unloadModule(nm);
	},
	//lecture des demande url pour appel au lancement de la carte specifiques
	initParamsUrl:function(){

		if($('TABLE')){
			this.params.optionsAction={
				'table':$('TABLE').value,
				'champ':$('CHAMP').value,
				'elemss':$('RECHERCHE').value,
				'operateur':'in'
			};
			var test=this.params.optionsAction;
			if(!test.table||!test.champ||!test.elemss){
				alert('un des parametres de recherche par url est manquant');
				return;
			}
			this.params.firstAction='recherche';
		}
		if($('CONTEXTMAP')){
			this.params.contextMap = $F('CONTEXTMAP');
		}
		if($('XMAP')){
			this.params.firstAction='GoToPoint';
			this.params.optionsAction={'coords':'real','point':{'x':parseInt($('XMAP').value),'y':parseInt($('YMAP').value)},'width':parseInt($('WIDTHMAP').value),'height':parseInt($('HEIGHTMAP').value),'facteurScale':1};
			this.params.optionsAction.point.x+=parseInt($('WIDTHMAP').value)/2;
			this.params.optionsAction.point.y-=parseInt($('HEIGHTMAP').value)/2;
		}
		if($('CENTREX')){
			this.params.firstAction='GoToPoint';
			this.params.optionsAction={'coords':'real','point':{'x':parseInt($('CENTREX').value),'y':parseInt($('CENTREY').value)},'width':parseInt($('WIDTHMAP').value),'height':parseInt($('HEIGHTMAP').value),'facteurScale':1};
			//this.params.optionsAction.point.x+=parseInt($('WIDTHMAP').value)/2;
			//this.params.optionsAction.point.y-=parseInt($('HEIGHTMAP').value)/2;
		}
		 
		if($('ELEMENT')) 
		{
		 	this.params.firstAction='localiseElements';
		 	this.params.optionsAction={'elements':$('ELEMENT').value};
			
			//findAll($('ELEMENT').value) 
		}


	},
	goToInitPosition:function(){
	
 		
 		this.goToBBox({'xmin':this.ixmin,'ymin':this.iymin,'dx':this.idx,'dy':this.idy});
 		
	},
	initializeMap:function(){
	
		if(swfIsReady){
			this.loadMap();
		}else{
	
			GestEvtDyn.ajouteEcouteur('MAPENABLED',this.loadMap,this);
			
		}
	},
	getSWF:function(movieName) {
		if (navigator.appName.indexOf("Microsoft") != -1) {
			return window[movieName];
		} else {
			return document[movieName];
		}
	},
	e_listen:function(){
		if(this.cr){
			if(document.onresize){
				this.fireResize();
			}else{
				if (! window.resizeEnd) {
		                window.resizeEnd = -1;
		         }
			 clearTimeout(window.resizeEnd);

		            window.resizeEnd = setTimeout(
		               this.fireResize.bind(this)
		            , 500);
			}
		}
	},
	fireResize:function(){
	
		var nW=$('IEhackInnerHeight').offsetLeft-this.params.lT;
		
		var nH=$('IEhackInnerHeight').offsetTop -this.params.tT;

		if(nW!=this.params.width||nH!=this.params.height){
			if(this.params.minWidth && this.params.minWidth>nW){
		
				nW =this.params.minWidth;
			}
			if(this.params.minHeight && this.params.minHeight>nH){
				nH =this.params.minHeight;
			}
		
			this.resizeMap(nW, nH);
		}
	},
	listenMapResize:function(){
		
		Event.observe(document.onresize ? document : window, "resize", this.e_listen.bindAsEventListener(this));
	},
	scale:function(facteur){
		this.mapFlashWrapper.mapZoom(facteur);
	},
	getMapControl:function(){
		return this.mapFlashWrapper;
	},
	layer:function(id){
		var desc = this.mapFlashWrapper.getLayerById(id);
		if(this._layers[id]==undefined){
			this._layers[id] =new DynmapLayer(this);
		}
		//var lay =new DynmapLayer();
		
		Object.extend(this._layers[id],desc);
		return this._layers[id];
	},
	getEchelle:function(){
		var bb=this.getCurrentBBox();
		var dx = bb.dx;
		
		// on transforme le pixel de l'ecran en cm
		var w  = this.params.width;
		//moyenne pour un ecran 17 pouces resolution 72
		var ratiopxcm =0.03;
		var wcm= this.params.width *ratiopxcm;
		
		var wm = wcm/100;
		
		var ech = dx/wm;
		return ech;
	},
	
	
	print:function(params){
		this.printFlash(params);
	},
	printFlash:function(params){
		var b=this.getCurrentBBox();
	
		
		var echelle=this.getEchelle();
		/**
		 * @todogestion precision
		 */
		var echellePrint = echelle;

		var icurZoomP = b.dx;
		var XminP = b.xmin;
		var YminP = b.ymin;
		var XmaxP = b.xmin+b.dx;
		var YmaxP = b.ymin+b.dy;
	
		if(typeof param=="undefined"){
			param = "";
		}
	
		if(typeof angle=="undefined"){
			angle = 0;
		}
	
		
	
		
	
			var screenW=parent.screen.width;
			var screenH=parent.screen.height;
			var w=410;
			var h=450;
			 try{
			if(typeof params.modele=='undefined'){
				var argsP='';	
			}else{
				var argsP='&modele='+params.modele;
			} 
}catch(e){
argsP='';
}

		
			var funcOpen= openWindow;
			//openWindow
			if (parent.openWindow)
			{
				funcOpen = parent.openWindow;
			}
			funcOpen('/dynmap/printbox.php?XMIN='+XminP+'&YMIN='+YminP+'&XMAX='+XmaxP+'&YMAX='+YmaxP+'&ZOOM='+icurZoomP+'&E='+echellePrint+'&A='+angle+'&path_application='+this.path_application+argsP,'','width='+w+',height='+h+',left='+((screenW-w)/2)+',top='+((screenH-h)/2)+',scrollbars=1,resizable=1,menubar=1,scrollbars=1,status=1');
		
	},
	drawLayer:function(tool,layer,options,rowid){
	
		if(typeof(layer)==undefined){
			if($("DRAWLAYERS")){
				layer==$F("DRAWLAYERS");
			}
		}
		this.loadModule('Draw',{'idLayer':layer,'showToolsBar':false,'tool':tool,'options':options,'rowid':rowid});
	},
	getAnalysesActives:function(){
		return this.mapFlashWrapper.getAnalysesActives();
	},
	selectionToRecherche:function(limitationCouche,objects){
		if(limitationCouche==undefined){
			limitationCouche=0;
		}
		tempParam = 'method=selectionToRecherche&limitationCouche='+limitationCouche;
		if(objects!=undefined){
			tempParam+='&ids='+objects;
		}
		this.appelServeur(tempParam, this.a_selectionToRecherche,this,this.recherche_url,'post');
	},
	/**
	 * Permet de recuperer les données de la selection
	 * @return array liste des objets selectionnées, exemple 113.2,156.4
	 */
	getSelectedItems:function(){
			return this.mapFlashWrapper.getSelectedItems();
	},
	a_selectionToRecherche:function(res){

		if(res.responseText=='11'){
			openrechRes();
		}else{
			alert('problème pour ouvrir la boite de recherche '+res.responseText);
		}
	},
	exportVectors:function(){
		var tabelems=getViewBoxVars();
		var linkOpener="/dynmap/class/modules/mvccarte.php?cont=EXPORTCLIENT&event=getInterfaceExport&path_application="+path_application;
		linkOpener+='&bbox[Xmin]='+tabelems["Xmin"]+'&bbox[Ymin]='+tabelems["YminREEL"]+'&bbox[winDX]='+	tabelems["winDX"]+'&bbox[winDY]='+tabelems["winDY"]+'&bbox[yminCarto]='+tabelems['Ymin'];
		window.open(linkOpener,"","width="+(screen.width/1.5)+",scrollbars=yes,left="+(screen.width/6)+",height=500,top="+((screen.height-500)/2));
	}
	,
	addFiltreRequeteCouche:function (layerid)
	{
		var valeurFiltrePost = "layerid="+layerid;

		myArguments = this.addFiltreRequeteCouche.arguments;

		for(i=1; i < myArguments.length; i++)
		{
			if (typeof(myArguments[i]) == 'object')
			{
				monObjet = myArguments[i];

				if (monObjet.typeObj == 'intervalle' || monObjet.typeObj == 'periode')
				{
					valeurFiltrePost += '&find@@@intervalle@@@'+monObjet.champ+'@@@deb='+monObjet.deb;
					valeurFiltrePost += '&find@@@intervalle@@@'+monObjet.champ+'@@@fin='+monObjet.fin;
				}
				else
				{
					valeurFiltrePost += '&find@@@'+monObjet.typeObj+'@@@'+monObjet.champ+'='+monObjet.valeur;
				}
			}
		}
		dynmap_urlpars = valeurFiltrePost;
		dynmap_urlpars += '&method=FILTRECOUCHE&args=AJOUTEFILTRECOUCHE,afterFiltre';
		this.appelServeur(dynmap_urlpars, this.a_addFiltreRequeteCouche,this,this.dynmap_url,'get');
		//getURL(dynmap_url+dynmap_urlpars,afterfiltre);
	},
	a_addFiltreRequeteCouche:function(sb_dat){

		if(sb_dat.responseText)
		{
			//alert(sb_dat.content);
			var TabcoucheA=sb_dat.responseText.split('@');
			GestEvtDyn.lanceEvenement('FILTREELEMENT',TabcoucheA[0]);
			
			this.chgStateLayer(TabcoucheA[0],1,1);
			if(TabcoucheA[1]!='0'){
				var myAnalyses=TabcoucheA[1].split('|');
				for(var i=0;i<myAnalyses.length;i++){
				   this.chgStateAnalyse(myAnalyses[i],1,"");
				}
			}
		}

	},
	removeFiltreCouche:function(idcouche){
		var dynmap_urlpars='method=RMFILTRECOUCHE&args='+idcouche;
		this.appelServeur(dynmap_urlpars, this.a_removeFiltreCouche,this,this.dynmap_url,'post');
	},
	a_removeFiltreCouche:function(res){

		tabLayer = res.responseText.split(',');
		var strLayer = "";
		var strAnalyse = "";
		for (ind=0;ind<tabLayer.length-1;ind++)
		{
			TabcoucheA = tabLayer[ind].split('@');
			this.chgStateLayer(TabcoucheA[0],1,1);
			strLayer += TabcoucheA[0]+",";
			if(TabcoucheA[1]!='0')
			{
				var myAnalyses=TabcoucheA[1].split('|');
				for(var i=0;i<myAnalyses.length;i++)
				{
					chgStateAnalyse(myAnalyses[i],1,"");
					strAnalyse += "A"+myAnalyses[i]+",";
				}
			}
			GestEvtDyn.lanceEvenement('RMFILTREELEMENT',TabcoucheA[0]);
		}

	},
	panMap:function(panXFacteur,panyFacteur){
		this.mapFlashWrapper.panMap(panXFacteur,panyFacteur);
	},
	chgStateLayer:function(layerid,etat,force_unload,analyseid){
		var reset_layer = 0;
		var analyse_id = 0;
		if(typeof force_unload=="number"){
			reset_layer=force_unload;
		}
		if(typeof analyseid=="number"){
			analyse_id=analyseid;
		}
		
		this.mapFlashWrapper.chgStateLayer(layerid,etat,force_unload,analyseid);
		GestEvtDyn.lanceEvenement('NEW_STATE_LAYER_DONE',[layerid,etat]);
	},
	chgStateLayerEtiquettes:function(layerid,etat){
		this.mapFlashWrapper.chgStateLayerEtiquettes(layerid,etat);
	},
	chgStateAnalyse:function(analyseid,etat,dynmapAnalyseParam){
		if(analyseid.indexOf('-')!=-1){
			var tabIn=analyseid.split('-');
			
			this.mapFlashWrapper.chgStateAnalyse(tabIn[0],etat, dynmapAnalyseParam);
			this.chgStateLayer(tabIn[1],etat,1,tabIn[0])	;
		}else{
			this.mapFlashWrapper.chgStateAnalyse(analyseid,etat, dynmapAnalyseParam);
		}

	},
	chgContexte:function(contexte,params){
	
	  	if(params==undefined){
	  		 params={};
	    }
		this.mapFlashWrapper.chgContexte(contexte,params);
	},
	addFiltreByElements:function(chaine){
		var tabLayers=new Array();
		var tabElems=chaine.split(',');
		for(var i=0;i<tabElems.length;i++){
			var ChaineLim=tabElems[i].split('.');
			var layeri=ChaineLim[0];
			if(!tabLayers[layeri]){
				tabLayers[layeri]=new Array();
			}
			var lgt=tabLayers[layeri].length;
			tabLayers[layeri][lgt]=ChaineLim[1];
		}
		dynmap_urlpars='typepost=BYPOSTURL&method=ADDFILTRECOUCHES';
		var arrObjToFind=new Array();
		for (var couche in tabLayers){
			if(couche!='extend' && couche!='each'){
				arrObjToFind[arrObjToFind.length]=couche+'|'+tabLayers[couche];
				//dataurl='method=ADDFILTRECOUCHE&args='+arrObjToFind;
				//postURL(dynmap_url+'typepost=BYPOSTURL',dataurl,afterfiltre,'application/x-www-form-urlencoded');
			}
		}
		dynmap_urlpars+='&args='+arrObjToFind.join('C');
		//	dynmap_urlpars += '&method=FILTRECOUCHE&args=AJOUTEFILTRECOUCHE,afterFiltre';

		this.appelServeur(dynmap_urlpars, this.a_addFiltreByElements,this,this.dynmap_url,'post');
	},
	a_addFiltreByElements:function(res){
		var tabGeneral=res.responseText.split('C');
		var TabcoucheA=new Array();
		for(var i=0;i<tabGeneral.length;i++){
			TabcoucheA=tabGeneral[i].split('@');
			GestEvtDyn.lanceEvenement('FILTREELEMENT',TabcoucheA[0]);

			GestEvtDyn.lanceEvenement('SETNEWSTATELAYER',[TabcoucheA[0],1]);




			this.chgStateLayer(TabcoucheA[0],1,1);
			if(TabcoucheA[1]!='0'){
				var myAnalyses=TabcoucheA[1].split('|');
				for(var i=0;i<myAnalyses.length;i++){
					this.chgStateAnalyse(myAnalyses[i],1,"");
				}
			}
		}
	},
	setCurrentBBox:function(bboxObject){

		var strDebug='';
		for(var i in bboxObject){
			strDebug+=i+':'+bboxObject[i];
		}
		GestEvtDyn.lanceEvenement('DEBUGDYN','mapmoved'+strDebug);
		this.xmin = bboxObject.xmin;
		this.ymin = bboxObject.ymin;

		this.dx = bboxObject.dx;
		this.dy = bboxObject.dy;
		this._lastBBox=this._curBBox;
		this._curBBox=bboxObject;
		if(this.idx==0){

			this.ixmin=this.xmin;
			this.iymin=this.ymin;
			this.idx=this.dx;
			this.idy=this.dy;
			//alert('debut'+this.xmin+' '+this.iymin);
		}else{

		}

		//alert(this.xmin+","+this.ymin+","+this.dx+","+this.dy);
	},
	zoomPreced:function(){
		if(this._lastBBox){
			var lb=this._lastBBox;
 			this.goToBBox(lb);
		}
	},
	getCurrentBBox:function(){
		return this._curBBox;
	},
	//permet d'intiliasier les parametres a chque envoi dynmap
	initPars:function(){
		return 'path_application='+this.path_application;
		//mainCarte.findAndSelect(laliste,0,false,false,{selectionObject:false})
	},
	findAndSelect:function(liste,replace_selection,select_mode,modifZoom,optionsP){
		this._findComplete=0;
		optionsF = {
			'typeFindSel': this.typeFindSel


		}.extend(optionsP || {});
		
		this.mapFlashWrapper.findAndSelect(liste,replace_selection,select_mode,modifZoom,optionsF);
		if(this.typeFindSelUn){
			this.typeFindSel=this.lastTypeFind;
		}
	},
	mask:function(list,replace,forceVisibility){
		
		if(list==''){
			this.alert('Veuillez sélectionner au moins un objet sur la carte pour créer un masque');
		}else{
		this.mapFlashWrapper.mask(list,replace,forceVisibility);
		}
	},
	setStateMask:function(stateOfMask){
		this.mapFlashWrapper.setStateMask(stateOfMask);
	},
	
	setTypeFind:function(newval,unique){
		if(newval!='localisation'&&newval!='select'&&newval!='selectHilight'&&newval!='localisationHilight'&&newval!='onlySelection'){
			alert('parametre non reconnu pour setTypeFind');
		}

		this.lastTypeFind=this.typeFindSel;
		this.typeFindSel=newval;
		this.typeFindSelUn=false;
		if(unique!=undefined){
			if( typeof unique=="boolean" ){
				this.typeFindSelUn=unique;
			}else{
				if(unique){
					this.typeFindSelUn=true;
				}
			}
		}

		this.typeFindSel=newval;
	
	},
	// CrÃ©er un gÃ©osignet en utilisant la vue courante JI 08/06/2005

 	makeGeosignet:function(){
		var libelleGeosignet = prompt("Entrez le nom du Geosignet ","");
		if (libelleGeosignet == "" || libelleGeosignet == null)
		{
			return false;
		}else{
			// (YMIN+(".$tblSVG.".YMAX-".$tblSVG.".YMIN)/2)
			var c=this.getCurrentBBox();
			Xmax=c.xmax;
			Xmin=c.xmin;
			Ymax=c.ymax;
			Ymin=c.ymin;
			winDX=Xmax-Xmin;
			winDY=Ymax-Ymin;
			param = libelleGeosignet + "|" + (Math.round(Xmin+ (Xmax-Xmin)/2) + "|" + (Math.round( Ymin+ (Ymax-Ymin)/2) ))  + "|" + (Math.round(winDX))  + "|" + (Math.round(winDY))  + "|" ;
			//sURL = dynmap_url + '
		
			//getURL(sURL,cb_makeGeosignet);
			dynmap_urlpars = 'method=ADDGEOSIGNET&args=' + escape(param);
				Debug("geosignet demande a etre ajoute"+param);
			this.appelServeur(dynmap_urlpars, this.cb_makeGeosignet,this,this.dynmap_url,'get');
		}
	},
	// Fonction call-back de makeGeosignet
	 cb_makeGeosignet :function (sb_data)
	{

		
			if (sb_data.responseText)
			{
				var arrParam = sb_data.responseText.split ('|');
	
				var msg = arrParam [0];
				var newValue = arrParam [1];
				var newLibelle = arrParam [2];
	
				//  Mise Ã  jour de la liste de gÃ©osignet dynamiquement
			
				GestEvtDyn.lanceEvenement("AJOUTGEOSIGNET",arrParam);

			}
		
	},
	resetLayer: function(idLayer){
		this.api().resetLayer(idLayer);
		var sURL='method=RESETANNOTATIONS';
		this.appelServeur(sURL,this.a_resetLayer,this);
	},
	a_resetLayer:function(){
			
		},
	resetSelection:function(){
		this.mapFlashWrapper.resetSelection();
	},
	//permet d'appeler la classe dynmap avec une methode specifique
	appelServeur :function(arguments, fonction,objetaLier,urllink,methodG){
		var pars=this.initPars();
		pars+='&'+arguments;
		if(!objetaLier||objetaLier==undefined){
			objetaLier=this;
		}
		if(!urllink||urllink==undefined){
			urllink=this.dynmap_url;
		}
		if(methodG==undefined){
			methodG='get';
		}
		//DebugD2(dynmap_url+pars);
		if(objetaLier!='null'){
			var myAjax = new Ajax.Request(
			urllink,
			{method: methodG, parameters: pars, onComplete: fonction,objetLie:objetaLier}
			);
		}else{
			var myAjax = new Ajax.Request(
					urllink,
					{method: methodG, parameters: pars, onComplete: fonction}
					);
		}

	},
	callRest:function(object,action,arguments,callBack,method){
		var pars=this.initPars();
		for(var i in  arguments){
			if(i!='extend'){
				pars+='&'+i+'='+arguments[i];
			}
		}
		if(method==undefined){
			method='get';
		}
		
		var urlTest='/dynmap/extensions/rest.php?';
		urlTest+='class='+object;
		urlTest+='&event='+action;
		urlTest+='&return=tojson';
	
		var myAjax = new Ajax.Request(
				urlTest,
				{'method': method, parameters: pars, onComplete: callBack}
				);
			
	},
	/*****************Fonctions de raster *************/
	// JD : Permet de changer le fichier de conf d'une couche raster
	//idRaster : numero de couche
	//configName :  nouvelle configuration
	setConfLayer:function (idRaster, configName){
		this.mapFlashWrapper.changeRasterConfig (idRaster, configName);
	},
	// JD : Permet de changer la legende d'une couche raster
	// L'objet legende doit etre de la forme 
	// object["couleur hexa minuscule"]["value"] = "valeur";
	// object["couleur hexa minuscule"]["lib"] = "libelle";
	setRasterLegend:function (idRaster, rasterLegend){
		this.mapFlashWrapper.changeRasterLegend (idRaster, rasterLegend);
	},
	
	//pour parameter l'opacite d'une couche, popur l'instant seulement d'un raster...
	setOpacityLayer:function(idLayer,opa,typeLayer){
		this.mapFlashWrapper.setOpacityLayer(idLayer,opa,typeLayer);
	},
	//pour sauvegarder cote serveur l'opacite d'une couche
	saveOpacityLayer:function(idLayer,opa,typeLayer){
		opa=opa*100;
		dynmap_urlpars = 'method=SETRASTEROPACITY&args='+idLayer+','+opa;
		this.appelServeur(dynmap_urlpars, null,this,this.dynmap_url,'get');
	},
	changeColorRaster:function(idRaster,color){

		//sURL = dynmap_url+'method=SETRASTERCOLORMODE&args='+Raster+','+color_mode;
		this.mapFlashWrapper.changeColorRaster(idRaster,color);
		dynmap_urlpars = 'method=SETRASTERCOLORMODE&args='+idRaster+','+color;
		this.appelServeur(dynmap_urlpars, null,this,this.dynmap_url,'get');
	},
	changeStateRaster:function(idRaster,state){
		this.chgStateLayer(idRaster,state);
	},
	
	getObjectDescription:function(idObj){
	
		var obj= this.mapFlashWrapper.getObjectDescription(idObj);
		return obj;
		
	},
	initDraw:function(){
	
		this.mapFlashWrapper.initDraw();

	},
		
		
	/*****************Fonctions de consultation *************/

	getDataById:function(objId){
		//alert('getdatabyid demande avec '+objId);
		var arrId = new Array();
		var grpId;
		var grpType;
		var elemId;
		var sURL;
 
		if (objId.split(".").length > 1)
		{
			arrId = objId.split(".");
			grpId = arrId[0];
			if (arrId.length == 3) // analyse : objId sous la forme "ANALYSEID.LAYERID.ELEMENTID"
			{
				elemId  = arrId[2];
				grpType = "analyse";
			}
			else // cas par defaut (layer):  objId sous la forme "LAYERID.ELEMENTID"
			{
				elemId  = arrId[1];
				grpType = "layer";
			}


			if(elemId)
			{
				this.appelServeur("ID="+grpId+"&IDELEMENT="+elemId+"&TYPE="+grpType,this.a_getDataById,this,'/dynmap/getdata.php');
			}

		}
	},
	saveDataById:function(objId){
	
		
		if (objId.split(".").length > 1)
		{
			var layer = 0;
			arrId = objId.split(".");
			grpId = arrId[0];
			if (arrId.length == 3) // analyse : objId sous la forme "ANALYSEID.LAYERID.ELEMENTID"
			{
				layer  = arrId[1];
			
			}
			else // cas par defaut (layer):  objId sous la forme "LAYERID.ELEMENTID"
			{
				layer  = arrId[0];
				
			}
			if(this._tbidesact[layer] ==undefined||this._tbidesact[layer]==0 ){
				this.lanceEvenement('ADDELEMENTFROMDRAW',[layer]);
				this.getDataById(objId);
			}else{
				this.lanceEvenement('ADDELEMENTFROMDRAW',[layer]);
			}
		
		}
		
	},
	disableDefaultDrawSave:function(idL){
		this._tbidesact[idL]= 1;
	},
	enableDefaultDrawSave:function(idL){
		this._tbidesact[idL]= 0;
	},
	a_getDataById:function(sb_data){
	 		
		if(typeof sb_data=="string"){
			function obj_data(sb_data){
				this.success = true;
				this.responseText = sb_data;
			}
			sb_data = new obj_data(sb_data);
		}
		var errMsgModmap='Impossible d\'ouvrir la fiche information. Veuillez desactiver le bloqueur de popup sur ce site';


		
		if (document.getElementById('DYNMAP_INFORMATION')){
			document.getElementById('DYNMAP_INFORMATION').innerHTML = sb_data.responseText;
			GestEvtDyn.lanceEvenement("FICHE_METIER",sb_data.responseText);

		}
		else
		{
			var msg = sb_data.responseText;
		
			var width  = 500;
			var height = 500;
			var left   = (screen.width-width)/2;
			var top	   = (screen.height-height)/2;

		
			if (msg.indexOf ('|') != -1) //Cas FICHE INFO EXTERNE
			{
				arrUrl     = msg.split('|');
				var url    = arrUrl[0];		
						
				//Car on peut appeler une fonction sur le click d'un objet
				if(url.indexOf("javascript")==-1)
				{
					if(url.indexOf("?")==-1)
					{
						url+='?';
					}else
					{
						url+='&';	
					}
					url += 'path_application='+ encodeURIComponent(this.path_application);
					
				}
				var target = arrUrl[1];
				if (target == "_blank" || !target) //Si la cible n'est pas prÃ©cisÃ© ou Ã©gale Ã  _blank
				{
			 
					try{
						if(url.indexOf("/dynmap/")==-1)
							{
								width = (parent.screen.width*0.65);
								height= (parent.screen.width*0.65);
								left  = 10;
								top   = 10;
							}
						
						  openWindow (url,'n','scrollbars=yes,resizable=yes,menubar=1,status=1,left='+left+', top='+top+',width='+width+',height='+height);
					}
					catch(e)
					{
						alert(errMsgModmap);
					}
				}
				else
				{
 

					//Si la cible est un div du document HTML parent
					if(document.getElementById(target)){
					
						try
						{

							var params = new Array();
							params[0] = url;
							params[1] = target;

							/*
							var myAjax = new Ajax.Updater
							(
							target,
							url,
							{method: 'POST', parameters: null}
							);

							*/
 
							GestEvtDyn.lanceEvenement("FICHE_METIER",params);
 
						}catch(e){

							alert("Aucun element de la page ne peut afficher les informations ("+target+" non trouve)");
						}

					}else{
						if (target == "_parent") //Si la cible est egale Ã  _parent
						{
							try
							{
								winInfo = changeLocation (url);
							}
							catch(e)
							{
								winInfo = parent.changeLocation (url);
							}
						}
						else // Sinon si il y a un jeu de frame
						{ 
							 
							if(parent.parent.frames.length>0 && parent.parent.frames[target])
							{ 
								parent.parent.frames[target].location.href = url;
							}
							else
							{
								if(parent.frames.length>0)
								{
									try
									{  
										parent.frames[target].changeLocation (url);
									}
									catch(e)
									{
										alert(errMsgFrame);
									}
								}
								else
								{
									try
									{
										openWindow (url,target,'scrollbars=yes,left='+left+', top='+top+',width='+width+',height='+height,target);
									}
									catch(e)
									{
										alert(errMsgModmap);
									}
								}
							}
						}
					}
				}
			}
			else
			{
				try
				{
					if(msg.indexOf("?")==-1)
					{
						msg+='?';
					}else
					{
						msg+='&';	
					}
					msg += 'path_application='+ encodeURIComponent(this.path_application);
					
					openWindow (msg,'n','scrollbars=yes,left='+left+', top='+top+',width='+width+',height='+height);

				}
				catch(e)
				{
					alert(errMsgModmap);
				}
			}

		}
	},
	addPersonalLayer:function(args,position){
		this.mapFlashWrapper.addPersonalLayer(args,position);
	},
	/**
	 * ajoute une couche personnelle de type raster
	 * @param args
	 * @param position
	 * @return
	 */
	addPersonalRaster:function(args,position){
		this.mapFlashWrapper.addPersonalRaster(args,position);
		
	},
	/**
	 * Enleve une couche de la carte
	 * @param id number
	 * @return void
	 */
	removeLayer:function(id){
		this.mapFlashWrapper.removeLayer(id);
	},
	/**
	 * Ouvre une popup en gerant les pb de focus, de droit etc
	 * @param p struct option de positionnnement(width,height, left, top)
	 * @return
	 */
	openWindow:function(p){
		var pe = {
			
			'width': 640,
			'height': 480,
			'left':200,
			'top':200
			
		}.extend(p || {});
		  openWindow (pe.url,'n','scrollbars=yes,resizable=yes,left='+pe.left+', top='+pe.top+',width='+pe.width+',height='+pe.height);
	},
	chgStateGroupe:function(strGroupes){
		this.mapFlashWrapper.chgStateGroupe(strGroupes);
	},
	/**
	 * ouvre la boite d'impression image
	 * @return void
	 */
	exportToImg:function(){
		var sURL='/dynmap/export_to_img.php?path_application='+this.path_application+'&method=PRINTER&args=RASTER,'+this.params.width+','+this.params.height
			+'&xmin='+this.xmin+'&ymin='+this.ymin+'&xmax='+(this.xmin+this.dx)+'&ymax='+(this.ymin+this.dy)+'&zoom='+this.dx+'&dynmapurl=/dynmap/class.dynmap.php?path_application='+this.path_application;
	//	var SMod=sURL.replace('class.dynmap.php','export_to_img.php');
		openWindow(sURL,'','width=600,height=300,scrollbars=no,resizeable=no');
	
	},
	/**
	 * CrÃ©e un nouvel objet sans gÃ©ometrie, utile pour un objet generÃ© par pk par exemple
	 * @param idLayer number
	 * @return void
	 */
	setNewObject:function(idLayer){
		idObject=idLayer+'.new';
		this.getDataById(idObject);
	},
	/**
	 * RÃ©cupere l'objet flash pour commniquer avec lui
	 * @return FLASH
	 */
	api:function(){
		return this.mapFlashWrapper;
	},
	refreshMapData:function(idLayer){
		if(idLayer==undefined){
			//sURL = dynmap_url+'method=UNSET_SESSION_VARS';
			//getURL(sURL,refresh_callback);
		}else{
			this.chgStateLayer(idLayer,1,1);
			
		}
	},
	
	
	localiseXY: function (X,Y,flag,newScale,params){
		var point={'x':X,'y':Y};
		var ob={'point':point,
	 	'coords':'real',
	 	'scaleMode':'number',
	 	'symbol':this.symboleLocalisation
			}.extend(params || {});
			
	 	if(flag!=undefined )
		{
			//Dessin type "Vous etes ici"

			ob.cible=flag;
		}
		if(newScale!=undefined&&newScale!=0){
			var b =mainCarte.getCurrentBBox();	
			ob.scaleFactor=newScale/b.zoom;
			
		}
 
		mainCarte.mapFlashWrapper.panTo(ob);
	},
	/**
	 * RecupÃ¨re la chaine svg d'un cercle autour du point considéré
	 * @param Xpt x en svg
	 * @param Ypt y en svg
	 * @param rayon en emtre
	 * @param funcRetour fonction de callback appelÃ©e (recoit un objet ajax )
	 * @return void
	 */
	createCircleDiscretise:function(Xpt,Ypt,rayon,funcRetour){
		
		
		var dynmap_urlpars = 'method=createCircleDiscretise&args='+Xpt+','+Ypt+','+rayon;
		this.appelServeur(dynmap_urlpars, funcRetour,'null');
	
			//getURL(dynmap_url+'method=createCircleDiscretise&args='+Xpt+','+Ypt+','+rayon,funcRetour);
	},
	/**
	 * Ajoute une geometrie (et sauvegarde cote serveur) dans dynmap	
	 * @param idLayer identifiant du layer (nb ou 'annotation' par exemple)
	 * @param svgString objet svg (ex <path id="1.115" d="... ) ou 'ajax' si cette fonction est utilisee en callback serveur 
	 * @param id id de l'objet a crerer , indiquer draw.new par dÃ©faut
	 * @param datas : struct tableau de donneres (@todo : implements params)
	 * @param objResponse si callback serveur objResponse est renseignerr automatiquement
	 * @return void
	 */
	addFeature:function(idLayer,svgString,id,objResponse,datas,saving){
		 mainCarte.getMapControl().endMsgWait('addFeature');
		
		if(svgString=='ajax'){
			svgString = objResponse.responseText;
		}
		if(saving==undefined){
			saving =true;
		}
		this.api().addFeature(idLayer,svgString,id,saving);

		
		
		//this.api().addFeature('annotation','<path d=""55455545454545 style="rferererre" />",'annotation.new')
	},
	/**
	 * demande a dynmap de creer une geometrie svg bufferisÃ©e a partir de l'ensemble des objets en parametres
	 * @param tabObjets array identifiant des objets a bufferise
	 * @param bufferObj taille du buffer en metre
	 * @param funcRetour fonction de retour appelÃ©
	 * @return void
	 */
	unionObjects:function(tabObjets,bufferObj,funcRetour){
		var dynmap_urlpars='unit='+bufferObj+'&args='+tabObjets+'&method=WKT_BUFFER';
		this.appelServeur(dynmap_urlpars, funcRetour,'null',false,'post');
	}


}
function rmCircleLoca(){
	mainCarte.layer('draw').reset();
}

function strSvgToAnnotation(res){
	
	//	var str = res.responseText;
		mainCarte.addFeature('annotation','ajax','draw.new',res);
		//jsStrSvgToAnnotation(str);
	
}
function objetsToAnnotation(tabObjets,bufferObj){
	if(bufferObj==undefined){
		bufferObj='0';
	}
	mainCarte.getMapControl().addMsgWait('Calcul du dessin en cours','addFeature');
	var functionRetour = mainCarte.addFeature.bind(mainCarte,'annotation','ajax','draw.new');
	mainCarte.unionObjects(tabObjets,bufferObj,functionRetour);

}

/********************function de wrappage**********************/
function mapZoom(k){
	mainCarte.scale(k);
}
function selectionToRecherche(limitationCouche,objects){
	mainCarte.selectionToRecherche(limitationCouche,objects);
}
function panMap(dx,dy)
{
	if(mainCarte==undefined){
		alert ('la carte flash n\'est pas initialisée');
	}

	mainCarte.panMap(dx,dy);

}
// Modifie l'etat d'une couche,
// si la couche est deja chargee la fct modifie l'attribut de visibilite
// sinon la fct charge la couche.
try{
	parent.chgStateLayer = chgStateLayer;
}catch( e ){
	window.chgStateLayer = chgStateLayer;
}
function chgStateLayer(layerid,etat,force_unload,analyseid)
{
	mainCarte.chgStateLayer(layerid,etat,force_unload,analyseid);

}
function chgStateGroupes(str){
	mainCarte.chgStateGroupe(str);
}
function chgStateLayerEtiquettes(layerid,etat)
{
	mainCarte.chgStateLayerEtiquettes(layerid,etat);

}

//Modifie l'etat  d'une analyse
try{
	parent.chgStateAnalyse = chgStateAnalyse;
}catch( e ){
	window.chgStateAnalyse = chgStateAnalyse;
}
function chgStateAnalyse(analyseid,etat,dynmapAnalyseParam)
{
	if(typeof dynmapAnalyseParam=="undefined")dynmapAnalyseParam=null;
	mainCarte.chgStateAnalyse(analyseid,etat,dynmapAnalyseParam);

}
function SetevenementCl(typeCl){
	if(typeCl==0){
		mainCarte.chgContexte('DEFAULT');
	}
	if(typeCl==1){
		mainCarte.chgContexte('SELECTION');
	}
	if(typeCl==2){
		mainCarte.chgContexte('NONE');
	}

}
//fonction de localisation
function findAll(liste,replace_selection,select_mode,modifZoom, url_mode){
	mainCarte.findAndSelect(liste,replace_selection,select_mode,modifZoom);
}
function findAllCheck(liste,replace_selection,select_mode,modifZoom, url_mode){
	mainCarte.findAndSelect(liste,replace_selection,select_mode,modifZoom);
}
function init_selection(){
	mainCarte.resetSelection();
}
function initZoom(){
	mainCarte.goToInitPosition();
}
function doZoom(xmin,ymin,dx,dy){
	mainCarte.goToBBox({'xmin':xmin,'ymin':ymin,'dx':dx,'dy':dy});
}

function export_selection(format)
{
	var width=640;
	var height=500;
	var left=(screen.width-width)/2;
	var top=(screen.height-height)/2;
	var str_id="";
	var msg = "/dynmap/selection.php?format="+format+'&path_application='+path_application;

	if(format=="HTML")
	{
		if (openWindow)
		{
			try
			{
				openWindow(msg,'n','menubar=yes,scrollbars=yes,left='+left+', top='+top+',width='+width+',height='+height);
			}
			catch (e)
			{
				alert('impossible d\'ouvroir la fenetre html de visualisation veuillez rÃ¯Â¿Â½gler votre bloqueur de pop up');
			}
		}
		else
		{
			alert('impossible d\'ouvroir la fenetre html de visualisation veuillez rÃ¯Â¿Â½gler votre bloqueur de pop up');
		}
	}
	if(format=="XLS")
	{
		//DebugD2(dynmap_url+pars);
		var myAjax = new Ajax.Request(
		msg,
		{method: 'POST', parameters: null, onComplete: function(res){
			//alert(res.responseText);
			//openWindow('../'+res.responseText);
			width=400;
			height=165;
			left=(screen.width-width)/2;
			top=(screen.height-height)/2;
			w=openWindow("/dynmap/getXlsFile.php?f="+path_application+res.responseText,'Xls','resizable=yes,scrollbars=yes,left='+left+', top='+top+',width='+width+',height='+height);
		}
		}
		);
	}
}

function drawCircleLoca(posXsvg,posYsvg,couleur){
	
	mainCarte.api().drawCible({'x':posXsvg,'y':posYsvg,'coords':'svg'});
}




function SVGFindComplete(){
	return mainCarte._findComplete;
}
//alert(SVGFindComplete);
function getDataById(objId){
	mainCarte.getDataById(objId);
}
function LoadInformation(obj){
	mainCarte.a_getDataById(obj);
}
function addFiltreByElements(chaine){
	mainCarte.addFiltreByElements(chaine);
}
function removeFiltreCouche(idcouche){
	mainCarte.removeFiltreCouche(idcouche);
}
function license(content){
	var arr = content.split("|");
	w = 450;
	h = 250;
	l = ((parent.screen.width-w)/2);
	t = ((parent.screen.height-h)/2);
	open(HTTP_PREFIX+arr[1]+"/dynmap/register.php?"+arr[2]+"path_application="+mainCarte.path_application,"","width="+w+",height="+h+",top="+t+",left="+l);
}
function logguer(content){
	var arr = content.split("|");
	w = 300;
	h = 200;
	l = ((parent.screen.width-w)/2);
	t = ((parent.screen.height-h)/2);
	GestEvtDyn.lanceEvenement('DATAINIT',"0");
	open(HTTP_PREFIX+arr[1]+"/dynmap/login.php?"+arr[2]+"path_application="+mainCarte.path_application,"","width="+w+",height="+h+",top="+t+",left="+l);
}
function printFlash(params)
{
	mainCarte.print(params);
}
function printSVG(params)
{
	mainCarte.print(params);
}
//Permet de changer le mode de representation pour la fonction de localisation
//mode = localisation,selection,localisationHilight
//flag = true|false
function SetTypeFind(mode,flag){
	mainCarte.setTypeFind(mode,flag);
}

function chgStateRasterUni(idRaster,state){
	mainCarte.changeStateRaster(idRaster,state);

}
function chgModeRasterUni(colorBool,idRaster){
	var color='';
	if (colorBool==1)
	{
		color = "rgb";
	}
	else
	{
		color = "grey-level";
	}
	mainCarte.changeColorRaster(idRaster,color);

}
function modOpacityRaster(opacity,idRaster){
	mainCarte.setOpacityLayer(idRaster,opacity,'raster');

}
function saveOpacityRaster(opacite,raster_map){
	mainCarte.saveOpacityLayer(raster_map,opacite,'raster');
}
function StartTimer(msg,key){
	mainCarte.getMapControl().addMsgWait(msg,key);
}
function StopTimer(key){
	mainCarte.getMapControl().endMsgWait(key);
}

//Ouvre la boite de recherche majic2
function majic2_search(){
 
	ArraySelectionMajic2 = getCurrentSelection();
 
	var selections = "0";

	if(ArraySelectionMajic2.length==0){
		alert("Aucune parcelle en selection");
	}else{
	
		flag = 0;
		for(var i=0;i<ArraySelectionMajic2.length;i++){
				selections += ","+ArraySelectionMajic2[i];
				flag = 1;
		}

		if(flag==1){

			try
			{
				var selection_mode = "parcelle";

				w=parent.openWindow("/dynmap/backoffice/majic/recherche_cadastre.php?selection_mode="+selection_mode+"&selections="+selections+"&path_application="+path_application,'','');
			}
			catch (e)
			{
			}
		}
	}
}
function getCurrentBBox(){
	return mainCarte.getCurrentBBox();	
}
function getViewBoxVars(){
	var b =mainCarte.getCurrentBBox();	

	var tabelems =  new Array();
	tabelems["Xmin"]= b.xmin;
	tabelems["Ymin"]= b.ymin;
	tabelems["YminREEL"]=b.yminReel;
	tabelems["Xmax"]= b.xmax;
	tabelems["Ymax"]= b.ymax;
	tabelems["winDX"]= b.dx;
	tabelems["winDY"]= b.dy;
	tabelems["icurZoom"]=b.zoom ;
	tabelems["E"]= mainCarte.getEchelle();
	tabelems["path_application"]= path_application;
	 
	return tabelems;

}

function chgStateAnnotations(){
	if(chgStateAnnotations._toogle==undefined){
		chgStateAnnotations._toogle=false;
	}
	if(chgStateAnnotations._toogle){
		mainCarte.chgStateLayer('annotation',1);
	}else{
		mainCarte.chgStateLayer('annotation',0);
	}
	chgStateAnnotations._toogle=!chgStateAnnotations._toogle;
}

 function localiseXY(X,Y,flag,newScale,params){
	 mainCarte.localiseXY(X,Y,flag,newScale,params);

}
function makeGeosignet(){
	mainCarte.makeGeosignet();
}
function getCurrentObject(vide,idobj){
	var datas=mainCarte.getObjectDescription(idobj);
	if(typeof(datas)!='undefined' && typeof(datas['dyn_desc'])!='undefined'){
		return datas['dyn_desc'];
	}else{
		return false;
	}
}
function refreshMapData (idLayer)
{

	mainCarte.refreshMapData(idLayer);
	

}
function NewFiche(idLayer){
	mainCarte.setNewObject(idLayer);
	
}

function initDraw(){
	//alert('demande de init');
	mainCarte.initDraw();
}
function dropElement(element_id){



	mainCarte.removeItem(element_id);
	//document.getElementById(document.getElementById(element_id).parentNode.getAttribute("id")).removeChild(document.getElementById(element_id));
}

function Debug(str){
	GestEvtDyn.lanceEvenement('DEBUG', [ str ] );
}
function switchDraw(layer,byMenu){
	if(layer=='close'){
		mainCarte.unloadModule('Draw');
	}else{
		mainCarte.loadModule('Draw',{'idLayer':layer,'showToolsBar':true});
	}
}
function getCurrentSelection(){
	return mainCarte.getSelectedItems();
}
function getSelArray(){
	return mainCarte.getSelectedItems();
}

function zoomPreced(){
	mainCarte.zoomPreced();
}
function inverseSelection(couche){
	mainCarte.inverseSelection(couche);
}
function createCircleDiscretise(Xpt,Ypt,rayon,funcRetour){

	mainCarte.createCircleDiscretise(Xpt,Ypt,rayon,funcRetour);
	
	
}
function 	resizeMap(w,h){
		mainCarte.resizeMap(w,h);
}
DynmapGeometry = Class.create();
DynmapGeometry.prototype={
		initialize:function(){
	
		},
		circle:function(x,y,rayon){
			this.type='circle';
			this.x=x;
			this.y=y;
			this.rayon=rayon;
			return this;
		}
		
}
function deleteAllAnnotations(){
	mainCarte.resetLayer('annotation');
}
function userMaps(mode)
{
	if(mode=="liste")
	{
		var width=700;
		var height=600;
		var left=(screen.width-width)/2;
		var top=(screen.height-height)/2;
	
		var msg = "/dynmap/extensions/indexcarte.php?cont=liste&mod=usermaps&event=prepare_liste&fullDisplay=1&path_application="+mainCarte.path_application;
	 
		if (openWindow)
		{
			try
			{
				openWindow(msg,'n','menubar=yes,scrollbars=yes,left='+left+', top='+top+',width='+width+',height='+height);
			}
			catch (e)
			{
				alert('Impossible d\'ouvrir la fenetre de visualisation. Veuillez paramétrer votre bloqueur de popup');
			}
		}
		else
		{
			window.open(msg,'n','menubar=yes,scrollbars=yes,left='+left+', top='+top+',width='+width+',height='+height);
		}
	}
	
	if(mode=="save")
	{
		
	 	var ajx= new Ajax.Request("/dynmap/extensions/indexcarte.php?cont=fiche&mod=usermaps&event=saveFiche&id=new&viewer=none&path_application="+mainCarte.path_application,
	 				{ 
	 					method: 'post',
	 					parameters: "&TITLE=AUTO",
	 					onComplete : function(r)
	 					{  
	 						//alert(r.responseText);
	 						alert('Enregistrement effectué');
	 					}
	 				}
	 			);
	}
	
	if(mode=="getMap")
	{
		
	 	var ajx= new Ajax.Request("/dynmap/extensions/indexcarte.php?cont=fiche&mod=usermaps&event=getFiche&id=lastFromUser&viewer=simpleJsonV2&path_application="+mainCarte.path_application,
	 				{  
	 					onComplete : function(r)
	 					{
	 						eval("var s="+r.responseText);
	 						var contexte = s["datasExtras"];   
	 						if(!isNaN(contexte))
	 						{
	 							location.href="index.php?CONTEXTMAP="+contexte;
	 						}else{
	 							alert("Aucune carte n'a Ã©tÃ© enregistrÃ©e au prÃ©alable");
	 						}
	 					}
	 				}
	 			);
	}
}
 
 
function echelleToZoom(echelle)
{
  var pixPerCm = 30; // 2,54 cm/inch et 96pix/inch
  
  return Math.round((echelle/100)*(mainCarte.params.width/pixPerCm));
  
}
function disableDefaultDrawSave(idL){
	mainCarte.disableDefaultDrawSave(idL);
}
function enableDefaultDrawSave(idL){
	mainCarte.enableDefaultDrawSave(idL);
}


function zoomEchelle (echelle)
{
	if(echelle > 0){
		//retourne un tableau d'elements
		var tabelems =  new Array();
		tabelems = getViewBoxVars();

		var temp_Xmin = tabelems["Xmin"];
		var temp_Ymin = tabelems["YminREEL"];
		var temp_winDX = tabelems["winDX"];
		var temp_winDY = tabelems["winDY"];

		var temp_largeur = tabelems["icurZoom"];
		//alert ("temp_winDX:" + temp_winDX + ",temp_winDY:" + temp_winDY+ ", temp_largeur:" +temp_largeur + ", temp_Xmin:"+temp_Xmin + ", temp_Ymin:"+temp_Ymin );

		var temp_X = temp_Xmin+((temp_winDX)/2);
		var temp_Y = temp_Ymin+((temp_winDY)/2);
	 
		localiseXY(temp_X,temp_Y,false,echelleToZoom(echelle));
	}
}
function dynmap_export_img(){
	mainCarte.exportToImg();
}
function selectionToMask(){
	var objs = mainCarte.getSelectedItems();
	var objStr = objs.join(',');
	mainCarte.mask(objStr,true,true);
}

