/**************************

MERCI DE COMMENTER TOUTES CES FONCTIONS, ON N'Y COMPREND RIEN !!!
MERCI DE COMMENTER TOUTES CES FONCTIONS, ON N'Y COMPREND RIEN !!!
MERCI DE COMMENTER TOUTES CES FONCTIONS, ON N'Y COMPREND RIEN !!!
MERCI DE COMMENTER TOUTES CES FONCTIONS, ON N'Y COMPREND RIEN !!!
MERCI DE COMMENTER TOUTES CES FONCTIONS, ON N'Y COMPREND RIEN !!!
MERCI DE COMMENTER TOUTES CES FONCTIONS, ON N'Y COMPREND RIEN !!!
MERCI DE COMMENTER TOUTES CES FONCTIONS, ON N'Y COMPREND RIEN !!!

**************************/


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){

		this.gestEvtDyn.lanceEvenement(nameE,arrParam);
	},
	
	onvueGlobalEnabled:function(nomVueGlobale){
		if(nomVueGlobale==this.nameObj){
			this.swfIsReady=true;
		}
		if(this.tmpBBox!=false){
			var fla=$(this.divVueGlobale+'flashVG');
			fla.onMapMoved(tmpBBox);
		}
	},
	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'	:2
			}
			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['strokeOpacity']=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 DynmapMap=Class.create();
DynmapMap.prototype={

	initialize:function(carteDynmap,params){
		this.params = {
			typeAccess:       'dynmap',
			bgColor: 'FFFFFF',
			parameters: '',
			echelle: 1,
			width: 640,
			height: 480,
			firstInfo:false,
			buffer:0,
			lT:300,
			anchor:false,
			anchorRayon:5,
			tT:300,
			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.typeFindSel='select';
		this.typeFindSelUn=false;
		this.lastTypeFind="";
		this._lastBBox=false;
		this.cr=true;
		//initialisation

	
		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);
	
	},
	resizeMap:function(w,h){
		//alert('resize');
			this.params.w=w;
			this.params.h=h;
				this.cr=false;
			setTimeout(
		               this.okR.bind(this)
		            , 100);
			this.mapFlashWrapper.width=w;
			this.mapFlashWrapper.height=h;
	
			this.mapFlashWrapper.resizeMap(w,h);
			
		
			
	},

	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});
	},
	inverseSelection:function(couche,typeD){
		
		if(typeD==undefined){
			typeD='intersect';
		}
		var tempParam = 'method=INVERSELECTION&typeD='+typeD+'&couche='+couche+'&buffer='+this.params.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){
		//alert('test');
		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;
	},
	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;
			
		}
		//alert(this.params.height);
		this.mapFlashWrapper.width=this.params.width;
		this.mapFlashWrapper.height=this.params.height;
		
		
		this.mapFlashWrapper.loadMap(this.params); 

	
	},
	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($('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(){
 		if(okInitFlash){
 			//sthis._lastBBox=false;
 			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;
	//	alert($('IEhackInnerHeight').offsetTop+' '+$('IEhackInnerHeight').offsetLeft );
		if(nW!=this.params.width||nH!=this.params.height){
			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;
	},
	getEchelle:function(){
		var bb=this.getCurrentBBox();
		return Math.round ((bb.dx/(this.params.width/38))*10);
	},
	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='';
}
			if (parent.openWindow)
			{
				parent.openWindow('/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=yes');
			}
			else
			{
				alert(errMsgModmap);
			}
		
	},
	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){
		if(limitationCouche==undefined){
			limitationCouche=0;
		}
		tempParam = 'method=selectionToRecherche&limitationCouche='+limitationCouche;
		this.appelServeur(tempParam, this.a_selectionToRecherche,this,this.recherche_url,'post');
	},
	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);
		}
	},
	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
				{
					//alert (myArguments[i].typeObj + ' ' + i + ' '+monObjet.typeObj+ ' '+monObjet.champ+' '+monObjet.valeur);
					valeurFiltrePost += '&find@@@'+monObjet.typeObj+'@@@'+monObjet.champ+'='+monObjet.valeur;
				}
			}
		}
		//alert (valeurFiltrePost);

		//var dynmap_urlpars = "path_application="+path_application+"&";
		dynmap_urlpars = valeurFiltrePost;
		dynmap_urlpars += '&method=FILTRECOUCHE&args=AJOUTEFILTRECOUCHE,afterFiltre';
		//alert(dynmap_urlpars);
		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;
		}
		//alert('ok2');
		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){
		optionsF = {
			'typeFindSel': this.typeFindSel


		}.extend(optionsP || {});
		
		this.mapFlashWrapper.findAndSelect(liste,replace_selection,select_mode,modifZoom,optionsF);
		if(this.typeFindSelUn){
			this.typeFindSel=this.lastTypeFind;
		}
	},
	setTypeFind:function(newval,unique){
		if(newval!='localisation'&&newval!='select'&&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);

			}
		
	},
	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);
		var myAjax = new Ajax.Request(
		urllink,
		{method: methodG, parameters: pars, onComplete: fonction,objetLie:objetaLier}
		);

	},
	/*****************Fonctions de raster *************/
	// JD : Permet de changer le fichier de conf d'une couche raster
	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 raster *************/

	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');
			}

		}
	},
	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,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].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);
	},
	addPersonalRaster:function(args,position){
		this.mapFlashWrapper.addPersonalRaster(args,position);
		
	},
	removeLayer:function(id){
		this.mapFlashWrapper.removeLayer(id);
	},
	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);
	},
	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');
	
	},
	setNewObject:function(idLayer){
		idObject=idLayer+'.new';
		this.getDataById(idObject);
	},
	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);
	}


}

/********************function de wrappage**********************/
function mapZoom(k){
	mainCarte.scale(k);
}
function selectionToRecherche(limitationCouche){
	mainCarte.selectionToRecherche(limitationCouche);
}
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 dï¿½ja chargï¿½e la fct modifie l'attribut de visibilit+ï¿½-ï¿½
// 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 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);

		}
		}
		);

	}
}
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.printFlash(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 zoomPreced(){
	mainCarte.zoomPreced();
}
function inverseSelection(couche){
	mainCarte.inverseSelection(couche);
}

function 	resizeMap(w,h){
		mainCarte.resizeMap(w,h);
}

