/*

  OpenLayers.js -- OpenLayers Map Viewer Library

  Copyright 2005-2008 MetaCarta, Inc., released under the Clear BSD license.
  Please see http://svn.openlayers.org/trunk/openlayers/license.txt
  for the full text of the license.

  Includes compressed code under the following licenses:

  (For uncompressed versions of the code used please see the
  OpenLayers SVN repository: <http://openlayers.org/>)

*/

/* Contains portions of Prototype.js:
 *
 * Prototype JavaScript framework, version 1.4.0
 *  (c) 2005 Sam Stephenson <sam@conio.net>
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://prototype.conio.net/
 *
 *--------------------------------------------------------------------------*/

/**  
*  
*  Contains portions of Rico <http://openrico.org/>
* 
*  Copyright 2005 Sabre Airline Solutions  
*  
*  Licensed under the Apache License, Version 2.0 (the "License"); you
*  may not use this file except in compliance with the License. You
*  may obtain a copy of the License at
*  
*         http://www.apache.org/licenses/LICENSE-2.0  
*  
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
*  implied. See the License for the specific language governing
*  permissions and limitations under the License. 
*
**/

/**
 * Contains XMLHttpRequest.js <http://code.google.com/p/xmlhttprequest/>
 * Copyright 2007 Sergey Ilinsky (http://www.ilinsky.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

/**
 * Contains portions of Gears <http://code.google.com/apis/gears/>
 *
 * Copyright 2007, Google Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  1. Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright notice,
 *     this list of conditions and the following disclaimer in the documentation
 *     and/or other materials provided with the distribution.
 *  3. Neither the name of Google Inc. nor the names of its contributors may be
 *     used to endorse or promote products derived from this software without
 *     specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Sets up google.gears.*, which is *the only* supported way to access Gears.
 *
 * Circumvent this file at your own risk!
 *
 * In the future, Gears may automatically define google.gears.* without this
 * file. Gears may use these objects to transparently fix bugs and compatibility
 * issues. Applications that use the code below will continue to work seamlessly
 * when that happens.
 */
(function(){var singleFile=(typeof Carmen=="object"&&Carmen.singleFile);window.Carmen={_scriptName:"Carmen.js",_getScriptLocation:function(){var scriptLocation="";var scriptName=Carmen._scriptName;var scripts=document.getElementsByTagName('script');for(var i=0,len=scripts.length;i<len;i++){var src=scripts[i].getAttribute('src');if(src){var index=src.lastIndexOf(scriptName);var pathLength=src.lastIndexOf('?');if(pathLength<0){pathLength=src.length;}
if((index>-1)&&(index+scriptName.length==pathLength)){scriptLocation=src.slice(0,pathLength-scriptName.length);break;}}}
return scriptLocation;}};if(CARMEN_DEBUG&&!singleFile){alert("Mode Debug (this alert enables firefox2 to fully load scripts...)");var jsfiles=new Array("Carmen/Application.js","consultation2.js","WMSGetFeatureInfo.js","Carmen/Ext/RowLayout.js","Carmen/Ext/BrowseButton.js","Carmen/Ext/FileUploadField.js","Carmen/Ext/SliderTip.js","Carmen/Util.js","Carmen/Layer.js","Carmen/Map.js","Carmen/Control.js","Carmen/Control/Annotation.js","Carmen/Control/AttributionCarmen.js","Carmen/Control/AddWMS.js","Carmen/Control/ContextManager.js","Carmen/Control/Coordinate.js","Carmen/Control/FavoriteAreas.js","Carmen/Control/Info.js","Carmen/Control/InfoURL.js","Carmen/Control/Inlay.js","Carmen/Control/LayerTreeManager.js","Carmen/Control/Legend.js","Carmen/Control/Measure.js","Carmen/Control/PanArrows.js","Carmen/Control/QueryAttributes.js","Carmen/Control/MapserverScale.js","Carmen/Control/ExportImg.js","Carmen/Control/ExportPdf.js","Carmen/Control/Print.js","Carmen/Control/ReferenceMap.js","Carmen/Control/Refresh.js","Carmen/Control/ScaleChooser.js","Carmen/Control/ToolTip.js","Carmen/Control/ZoomHistory.js","Carmen/Control/ZoomToPlace.js","Carmen/Layer/MapServerGroup.js","Carmen/Layer/WMSGroup.js","Carmen/Ext/TreeNodeUI.js","Carmen/Ext/TreeNodeInfoUI.js","Carmen/Ext/ApplicationUI.js");for(var i=0;i<tabEPSG.length;i++)
jsfiles.push("Carmen/proj4Defs/EPSG"+tabEPSG[i][0]+".js");var agent=navigator.userAgent;var docWrite=(agent.match("MSIE")||agent.match("Safari"));if(docWrite){var allScriptTags=new Array(jsfiles.length);}
var host=Carmen._getScriptLocation();for(var i=0,len=jsfiles.length;i<len;i++){if(docWrite){allScriptTags[i]="<script src='"+host+jsfiles[i]+"'></script>";}
else{var s=document.createElement("script");s.src=host+jsfiles[i];var h=document.getElementsByTagName("head").length?document.getElementsByTagName("head")[0]:document.body;h.appendChild(s);}}
if(docWrite){document.write(allScriptTags.join(""));}}})();Carmen.VERSION_NUMBER="0.1beta";Carmen.Util={};Carmen.DOTS_PER_INCH=96;Carmen.Mapserver_DOTS_PER_INCH=96;Carmen.CARMEN_ERROR=256;Carmen.CARMEN_ERROR_SESSION_EXPIRED=257;Carmen.Util.WMS_FULL_LEGEND_MIN_WIDTH=45;Carmen.Util.WMS_FULL_LEGEND_MIN_HEIGHT=40;Carmen.Util.WMSC_RESOLUTIONS=[2113.267326,1056.633663,528.3168317,264.1584158,132.0792079,66.03960396,26.41584158,13.229166668,6.614583334,4.630208105,2.645833334,1.322916667,0.661458333];Carmen.SpecialChars={"around":String.fromCharCode(0x02248)};Carmen.Util.INFO_TOOL_XY_TOLERANCE=5;Carmen.Util.initLegend=function(){this.context=new Carmen.JSONContext(jsOws);var ctx=this.context;var layerTreeManager=new Carmen.Control.LayerTreeManager();var jsonLayerTree=ctx.mdataMap.LayerTree;var jsonLayerList=ctx.layer;layerTreeManager.buildTree(jsonLayerTree,jsonLayerList);var legend=new Carmen.Control.Legend();legend.layerTreeManager=layerTreeManager;legend.renderHTMLto("legendDiv");submitForm();}
Carmen.Util.buildExt2olHandlerToggle=function(olControl){return function(extBtn,state){if(state)
olControl.activate();else
olControl.deactivate();olControl.active=extBtn.pressed;}};Carmen.Util.buildExt2olHandlerButton=function(olControl){return function(){olControl.trigger();}};Carmen.Util.handleAjaxFailure=function(response,callerName,skipExceptSession){callerName=Ext.value(callerName,"Carmen",false);skipExceptSession=Ext.value(skipExceptSession,false,false);if(response){var response=Ext.decode(response.responseText);if(response.errmsg){var failureType=Ext.value(response.failureType,0,false);if(failureType==Carmen.CARMEN_ERROR_SESSION_EXPIRED)
Ext.Msg.alert(callerName,response.errmsg,function(){top.window.location.reload();});else if(!skipExceptSession)
Ext.Msg.alert(callerName,response.errmsg+" ("+response.failureType+")");}
else if(!skipExceptSession)
Ext.Msg.alert(callerName,'Service indisponible');}
else if(!skipExceptSession)
Ext.Msg.alert(callerName,'Service indisponible');};Carmen.Util.olRegisterProfilerEvents=function(layer){layer.logEvent=function(event){}
layer.events.register("loadstart",layer,function(){this.logEvent("Load Start");});layer.events.register("tileloaded",layer,function(){this.logEvent("Tile loaded. "+this.numLoadingTiles
+" left.");});layer.events.register("loadend",layer,function(){this.logEvent("Load End. Grid:"+this.grid.length+"x"
+this.grid[0].length);});};Carmen.Util.getTimeStamp=function(){var date=new Date();var timeParts=[date.getHours(),date.getMinutes(),date.getSeconds()];var timeStamp=timeParts.join(":");return timeStamp;};Carmen.Util.openHelp=function(){window.open('http://carmen.ecologie.gouv.fr','Help',"location=no, toolbar=no, scrollbars=yes");}
Carmen.Util.openWindow=function(title,url){window.open(url,title,"location=no, toolbar=no, scrollbars=yes");};Carmen.Util.openWindowExt=function(title,url,autosize){var win=new Ext.Window({layout:'fit',width:autosize?'auto':550,height:autosize?'auto':500,plain:true,title:title,header:(title!=null)&&(title!=''),modal:false,autoDestroy:true,resizable:true,autoLoad:url});win.show();};Ext.ux.IFrameComponent=Ext.extend(Ext.BoxComponent,{onRender:function(ct,position){this.el=ct.createChild({tag:'iframe',id:'iframe-'+Ext.id(),name:this.name,width:'100%',height:'100%',frameBorder:0,src:this.url});}});Carmen.Util.openWindowIframe=function(title,url,autosize){var win=new Ext.Window({layout:'fit',width:autosize?'auto':550,height:autosize?'auto':500,plain:true,title:title,header:(title!=null)&&(title!=''),modal:false,autoDestroy:true,resizable:true,maximizable:true,items:[new Ext.ux.IFrameComponent({url:url})]});win.on('maximize',function(winElt){winElt.close();window.open(url);},win);win.show();};Carmen.Util.forceScrollOnToolbarInIE=function(tb){var scrollHeight=tb.getEl().dom.scrollHeight;var clientHeight=tb.getEl().dom.clientHeight;var viewWidth=tb.getEl().getComputedWidth();var tbWidth=tb.getEl().first().getComputedWidth();var style={paddingBottom:"2px",overflowX:"auto"};if(scrollHeight>clientHeight||tbWidth>viewWidth){style.overflowX="scroll";}
tb.getEl().applyStyles(style);};Carmen.Util.openDownloadData=function(){winDownloadData=new Ext.Window({layout:'fit',width:Ext.lib.Dom.getViewHeight()<1000?790:770,height:Ext.lib.Dom.getViewHeight()<1000?Ext.lib.Dom.getViewHeight()-10:'auto',autoScroll:true,plain:true,title:'Téléchargement',modal:false,x:150,y:Ext.lib.Dom.getViewHeight()<1000?5:100,id:'downloadWindow',autoDestroy:true,resizable:true,autoLoad:{url:'/services/GetDownloadData/getLicence.php',scripts:true}});winDownloadData.show();};function myEditFunction(){alert("ok");};Carmen.Util.doAjax=function(url,MsgBoxTitle,useClassicAlert){Ext.Ajax.request({url:url,method:"GET",params:{action:'getMsg'},success:function(result,request){response=Ext.decode(result.responseText);if(useClassicAlert)
alert(response.msg);else
Ext.MessageBox.alert(MsgBoxTitle,response.msg);},failure:function(result,request){if(useClassicAlert)
alert("Échec de la procédure");else
Ext.MessageBox.alert('Erreur','Échec de la procédure');}});}
Carmen.Util.encode_utf8=function(s){return unescape(encodeURIComponent(s));};Carmen.Util.decode_utf8=function(s){return decodeURIComponent(escape(s));};Carmen.Util.array_find=function(arr,value){var i=-1;while(i<arr.length&&arr[i]!=value){i++;}
return i;};Carmen.Util.json2xml=function(jsonObj,header){return json2xml(jsonObj,null,header);}
function json2xml(o,tab,header){var toXml=function(v,name,ind){var xml="";if(v instanceof Array){for(var i=0,n=v.length;i<n;i++)
xml+=ind+toXml(v[i],name,ind+"\t")+"\n";}else if(typeof(v)=="object"){var hasChild=false;xml+=ind+"<"+name;for(var m in v){if(m.charAt(0)=="@")
xml+=" "+m.substr(1)+"=\""+Carmen.Util.htmlspecialchars(v[m].toString())+"\"";else if(m=="attributes"){for(n in v[m]){xml+=" "+n.toString()+'="'+Carmen.Util.htmlspecialchars(v[m][n].toString())+'"';}}else
hasChild=true;}
xml+=hasChild?">":"/>";if(hasChild){for(var m in v){if(m=="#text")
xml+=v[m];else if(m=="#cdata")
xml+="<![CDATA["+v[m]+"]]>";else if(m.charAt(0)!="@"&&m!="attributes")
xml+=toXml(v[m],m,ind+"\t");}
xml+=(xml.charAt(xml.length-1)=="\n"?ind:"")+"</"
+name+">";}}else{xml+=ind+"<"+name+">"+Carmen.Util.htmlspecialchars(v.toString())+"</"+name+">";}
return xml;};var xml=header?header:"";for(var m in o)
xml+=toXml(o[m],m,"");return tab?xml.replace(/\t/g,tab):xml.replace(/\t|\n/g,"");}
Carmen.Util.htmlspecialchars=function(str){str=str.replace(/&/g,'&amp;');str=str.replace(/"/g,'&quot;');str=str.replace(/>/g,'&gt;');str=str.replace(/</g,'&lt;');return str;}
Carmen.Util.unhtmlspecialchars=function(str){str=str.replace(/&amp;/g,'&');str=str.replace(/&quot;/g,'"');str=str.replace(/&gt;/g,'>');str=str.replace(/&lt;/g,'<');return str;}
Carmen.Util.olInherits=function(daughter,mother){var res=(daugther.prototype.CLASS_NAME==mother.prototype.CLASS_NAME);if('parent'in daughter&&!res){res=Carmen.Util.olInherits(daughter.parent,mother);}
return res;};Carmen.Util.chompAndSplit=function(str,sep){if(str.length>0&&str.substr(str.length-1,1)==sep){str=str.substr(0,str.length-1);}
return str.split(sep);};Carmen.Util.decodeCarmenFieldDesc=function(fieldDesc,baseURL){var arrFieldDesc=Carmen.Util.chompAndSplit(fieldDesc,'|');if(!baseURL)
baseURL='';return arrFieldDesc.length>=3?{name:arrFieldDesc[0],alias:arrFieldDesc[1],type:arrFieldDesc[2],url:arrFieldDesc[2]!='URL'?null:(arrFieldDesc.length>3?baseURL+arrFieldDesc[3]:baseURL+'<'+arrFieldDesc[0]+'>')}:null;};Carmen.Util.carmenTypeToExtType=function(carmenStr){var res='auto';switch(carmenStr){case'TXT','IMG':res='string';break;case'URL':res='auto';break;case'AAAAMMJJ','AAAAJJMM','MMJJAAAA','JJMMAAAA':res='date';break;default:break;}
return res;};Carmen.Util.carmenDateTypeToExtDateFormat=function(carmenStr){var res='d-m-Y';switch(carmenStr){case'AAAAMMJJ':res='Y-m-d';break;case'AAAAJJMM':res='Y-d-m';break;case'MMJJAAAA':res='m-d-Y';break;case'JJMMAAAA':res='d-m-Y';break;default:break;}
return res;};Carmen.Util.URLRenderer=function(v){var html='<div class="cmnLayerTreeLayerNodeMetadata"><span onclick="javascript:Carmen.Util.openWindowIframe('+'\'Informations détaillées\', \''+
v.href+'\');" >'+v.text+'</span></div>';return html;};Carmen.Util.imgRenderer=function(src){var html='<div><span>Aucune image associée</span></div>'
if(src!=null&&src!='')
html='<div class="cmnImgRenderer"><img src="'+
src+'" onclick="javascript:Carmen.Util.openWindowIframe('+'\'\', \''+
src+'\', true);" /></div>';return html;};Carmen.Util.carmenTypeToExtRenderer=function(carmenStr){var res='';switch(carmenStr){case'AAAAMMJJ':case'AAAAJJMM':case'MMJJAAAA':case'JJMMAAAA':res=Ext.util.Format.dateRenderer('d/m/Y');break;case'URL':res=Carmen.Util.URLRenderer;break;case'IMG':res=Carmen.Util.imgRenderer;break;default:break;}
return res;};Carmen.Util.carmenFontDescToFontStyles=function(fontDesc){var desc={};desc.font=fontDesc;var t=fontDesc.match(/[^-]+/g);if(t!=null){desc.font=t[0];for(var i=1;i<t.length;i++){switch(t[i].toLowerCase()){case"gras":desc.fontWeight='bold'
break;case"italique":desc.fontStyle='italic'
break;}}}
return desc;}
Carmen.Util.clone=function(obj){var cloned={};for(a in obj){cloned[a]=obj[a];}
return cloned;};Carmen.Util.strExtentToOlBounds=function(extentStr,punctualBufferRadius){var tabExtent=extentStr.substr(1,extentStr.length-1).split(",");for(var i=0;i<4;i++)
tabExtent[i]=parseFloat(tabExtent[i]);if(punctualBufferRadius){if(tabExtent[1]==tabExtent[3]){tabExtent[1]=tabExtent[1]-punctualBufferRadius;tabExtent[3]=tabExtent[3]+punctualBufferRadius;}
if(tabExtent[2]==tabExtent[4]){tabExtent[2]=tabExtent[2]-punctualBufferRadius;tabExtent[4]=tabExtent[4]+punctualBufferRadius;}}
return new OpenLayers.Bounds(tabExtent[0],tabExtent[1],tabExtent[2],tabExtent[3]);};Carmen.Util.positionToStr=function(position){var str="";if(position instanceof OpenLayers.Bounds){str='('+position.left+','+position.bottom+','+position.right+','+position.top+')';}
else if(position instanceof OpenLayers.LonLat){str='('+position.lon+','+position.lat+')';}
else if(position instanceof OpenLayers.Pixel){str='('+position.x+','+position.y+')';}
return str;};Carmen.Util.emptyStore=new Ext.data.SimpleStore({fields:[],data:[]});Carmen.Util.emptyColumnModel=new Ext.grid.ColumnModel({columns:[]});Carmen.Util.convertContextBBtoolBounds=function(bb){var lc=bb.LowerCorner.split(' ');var uc=bb.UpperCorner.split(' ');return new OpenLayers.Bounds(lc[0],lc[1],uc[0],uc[1]);};Carmen.Util.array_filter=function(aray,filter){var res=[];for(var i=0;i<aray.length;i++){if(filter(aray[i])){res.push(aray[i]);}}
return res;}
Carmen.Util.array_map=function(aray,f){var res=[];for(var i=0;i<aray.length;i++){res.push(f(aray[i]));}
return res;}
Carmen.Util.set_add=function(aray,el,f_merge){var i=0;if(!f_merge)
f_merge=function(e1,e2){return e1===e2;};while(i<aray.length&&!(f_merge(aray[i],el)))
i++;if(i>=aray.length)
aray.push(el);return aray;}
Carmen.Util.set_from_array=function(aray){var set=[];for(var i=0;i<aray.length;i++){Carmen.Util.set_add(set,aray[i]);}
return set;}
Carmen.Util.set_member=function(aray,el){var i=0;while(i<aray.length&&(aray[i]!=el))
i++;return i<aray.length;}
Carmen.Util.loadPage=function(URL){if(URL)
top.window.location.replace(URL);else{top.window.location.reload();}}
Carmen.Util.loadXML=function(xmlStr){var xmlDoc={};if(document.implementation&&document.implementation.createDocument){xmlDoc=document.implementation.createDocument("","",null);}
else if(window.ActiveXObject){xmlDoc=new ActiveXObject("Microsoft.XMLDOM");xmlDoc.onreadystatechange=function(){if(xmlDoc.readyState==4){}};}
else{xmlDoc=xmlStr;alert('Your browser can\'t load the XML file: '+e.toString());}
xmlDoc.async="false";xmlDoc.load(xmlStr);return xmlDoc;}
Carmen.Util.bool2IntStr=function(bool){return bool?"1":"0";};Carmen.Util.descendingOrder=function(a,b){return b-a;};Carmen.Util.roundIntTo2Digits=function(n){var res=new Number(n).toFixed();var n_str=res.toString();if(n_str.length>2){var n_str_1=n_str.substr(0,2);var n_str_2=n_str.substr(2);var n2_str=n_str_1+'.'+n_str_2;var n_dec_digits=n_str_2.length;var n2=parseFloat(n2_str).toFixed();res=n2*Math.pow(10,n_dec_digits);}
return res;};Carmen.Util.roundIntToNdigits=function(n,d){var res=new Number(n).toFixed();var n_str=res.toString();if(n_str.length>d){var n_str_1=n_str.substr(0,d);var n_str_2=n_str.substr(d);var n2_str=n_str_1+'.'+n_str_2;var n_dec_digits=n_str_2.length;var n2=parseFloat(n2_str).toFixed();res=n2*Math.pow(10,n_dec_digits);}
return res;};Carmen.Util.roundIntToDigits=function(n){var res=new Number(n).toFixed();var n_str=res.toString();var n_digits=res>50000?2:3;res=Carmen.Util.roundIntToNdigits(n,n_digits);return res;};Carmen.Util.scaleTextFormater=function(scale){var denom=parseInt(scale).toString();var newDenom='';for(var i=0;i<denom.length;i++){newDenom=denom.charAt(denom.length-1-i)+newDenom;if((i+1)%3==0&&(i+1)<denom.length)
newDenom=' '+newDenom;}
return' 1 / '+newDenom;};Carmen.Util.isGeographicProjection=function(cs){var prj=null;if(typeof cs=="string")
prj=new OpenLayers.Projection(cs);else if(cs instanceof OpenLayers.Projection)
prj=cs;return(prj!=null)?(prj.getUnits()==null):false;};Carmen.Util.getProjectionUnits=function(cs){var prj=null;if(typeof cs=="string")
prj=new OpenLayers.Projection(cs);else if(cs instanceof OpenLayers.Projection)
prj=cs;return(prj==null)?'dd':prj.getUnits()==null?'dd':prj.getUnits();};Carmen.Util.resNearTester=function(r1,r2){var denom1=OpenLayers.Util.getScaleFromResolution(r1,"m");var denom2=OpenLayers.Util.getScaleFromResolution(r2,"m");var delta=Math.abs(denom1-denom2)/Math.max(denom1,denom2);return(delta<0.01);}
Carmen.Util.OLWMSGroup2CarmenOWSDesc=function(layer,nextLayerId,extraDesc){var descs=[];var layersInfo=(!layer.hasSubLayers())?[{name:layer.name,visible:layer.getVisibility(),wmsName:layer.params.LAYERS,index:0}]:layer.subLayers;for(var i=0;i<layersInfo.length;i++){var info=layersInfo[i];var desc={Server:{OnLineResource:{attributes:{url:layer.url}},attributes:{service:layer.params.SERVICE,version:layer.params.VERSION}},Title:info.name,attributes:{haslabel:Carmen.Util.bool2IntStr(false),hidden:Carmen.Util.bool2IntStr(!info.visible),name:info.name,queryable:Carmen.Util.bool2IntStr(true)},Extension:{wms_format:layer.params.FORMAT,wms_name:info.wmsName,wms_onlineresource:layer.url,wms_server_version:layer.params.VERSION,wms_srs:Ext.value(layer.params.SRS,extraDesc.projection,false),LAYER_TITLE:info.name,layerSettings_ActivThemes:"ON",layerSettings_Tiled:"OFF",layerSettings_download:"OFF",layerSettings_group:Ext.value(extraDesc.group,"",true),layerSettings_order:nextLayerId.toString()}};nextLayerId++;descs.push(desc);};return descs};Ext.lib.Ajax.isCrossDomain=function(u){var match=/(?:(\w*:)\/\/)?([\w\.]*(?::\d*)?)/.exec(u);if(!match[1])
return false;return(match[1]!=location.protocol)||(match[2]!=location.host);};Ext.override(Ext.data.Connection,{request:function(o){if(this.fireEvent("beforerequest",this,o)!==false){var p=o.params;if(typeof p=="function"){p=p.call(o.scope||window,o);}
if(typeof p=="object"){p=Ext.urlEncode(p);}
if(this.extraParams){var extras=Ext.urlEncode(this.extraParams);p=p?(p+'&'+extras):extras;}
var url=o.url||this.url;if(typeof url=='function'){url=url.call(o.scope||window,o);}
if(o.form){var form=Ext.getDom(o.form);url=url||form.action;var enctype=form.getAttribute("enctype");if(o.isUpload||(enctype&&enctype.toLowerCase()=='multipart/form-data')){return this.doFormUpload(o,p,url);}
var f=Ext.lib.Ajax.serializeForm(form);p=p?(p+'&'+f):f;}
var hs=o.headers;if(this.defaultHeaders){hs=Ext.apply(hs||{},this.defaultHeaders);if(!o.headers){o.headers=hs;}}
var cb={success:this.handleResponse,failure:this.handleFailure,scope:this,argument:{options:o},timeout:this.timeout};var method=o.method||this.method||(p?"POST":"GET");if(method=='GET'&&(this.disableCaching&&o.disableCaching!==false)||o.disableCaching===true){url+=(url.indexOf('?')!=-1?'&':'?')
+'_dc='+(new Date().getTime());}
if(typeof o.autoAbort=='boolean'){if(o.autoAbort){this.abort();}}else if(this.autoAbort!==false){this.abort();}
if((method=='GET'&&p)||o.xmlData||o.jsonData){url+=(url.indexOf('?')!=-1?'&':'?')+p;p='';}
if(o.scriptTag||this.scriptTag||Ext.lib.Ajax.isCrossDomain(url)){this.transId=this.scriptRequest(method,url,cb,p,o);}else{this.transId=Ext.lib.Ajax.request(method,url,cb,p,o);}
return this.transId;}else{Ext.callback(o.callback,o.scope,[o,null,null]);return null;}},scriptRequest:function(method,url,cb,data,options){var transId=++Ext.data.ScriptTagProxy.TRANS_ID;var trans={id:transId,cb:options.callbackName||"stcCallback"+transId,scriptId:"stcScript"+transId,options:options};url+=(url.indexOf("?")!=-1?"&":"?")
+data
+String.format("&{0}={1}",options.callbackParam||this.callbackParam||'callback',trans.cb);var conn=this;window[trans.cb]=function(o){conn.handleScriptResponse(o,trans);};trans.timeoutId=this.handleScriptFailure.defer(cb.timeout,this,[trans]);var script=document.createElement("script");script.setAttribute("src",url);script.setAttribute("type","text/javascript");script.setAttribute("id",trans.scriptId);document.getElementsByTagName("head")[0].appendChild(script);return trans;},handleScriptResponse:function(o,trans){this.transId=false;this.destroyScriptTrans(trans,true);var options=trans.options;var doc;if(typeof o=='string'){if(window.ActiveXObject){doc=new ActiveXObject("Microsoft.XMLDOM");doc.async="false";doc.loadXML(o);}else{doc=new DOMParser().parseFromString(o,"text/xml");}}
response={responseObject:o,responseText:(typeof o=="object")?Ext.util.JSON.encode(o):String(o),responseXML:doc,argument:options.argument}
this.fireEvent("requestcomplete",this,response,options);Ext.callback(options.success,options.scope,[response,options]);Ext.callback(options.callback,options.scope,[options,true,response]);},handleScriptFailure:function(trans){this.transId=false;this.destroyScriptTrans(trans,false);var options=trans.options;response={argument:options.argument,status:500,statusText:'Server failed to respond',responseText:''};this.fireEvent("requestexception",this,response,options,{status:-1,statusText:'communication failure'});Ext.callback(options.failure,options.scope,[response,options]);Ext.callback(options.callback,options.scope,[options,false,response]);},destroyScriptTrans:function(trans,isLoaded){document.getElementsByTagName("head")[0].removeChild(document.getElementById(trans.scriptId));clearTimeout(trans.timeoutId);if(isLoaded){window[trans.cb]=undefined;try{delete window[trans.cb];}catch(e){}}else{window[trans.cb]=function(){window[trans.cb]=undefined;try{delete window[trans.cb];}catch(e){}};}}});var Url={encode:function(string){return escape(this._utf8_encode(string));},decode:function(string){return this._utf8_decode(unescape(string));},_utf8_encode:function(string){string=string.replace(/\r\n/g,"\n");var utftext="";for(var n=0;n<string.length;n++){var c=string.charCodeAt(n);if(c<128){utftext+=String.fromCharCode(c);}else if((c>127)&&(c<2048)){utftext+=String.fromCharCode((c>>6)|192);utftext+=String.fromCharCode((c&63)|128);}else{utftext+=String.fromCharCode((c>>12)|224);utftext+=String.fromCharCode(((c>>6)&63)|128);utftext+=String.fromCharCode((c&63)|128);}}
return utftext;},_utf8_decode:function(utftext){var string="";var i=0;var c=c1=c2=0;while(i<utftext.length){c=utftext.charCodeAt(i);if(c<128){string+=String.fromCharCode(c);i++;}else if((c>191)&&(c<224)){c2=utftext.charCodeAt(i+1);string+=String.fromCharCode(((c&31)<<6)|(c2&63));i+=2;}else{c2=utftext.charCodeAt(i+1);c3=utftext.charCodeAt(i+2);string+=String.fromCharCode(((c&15)<<12)|((c2&63)<<6)|(c3&63));i+=3;}}
return string;}};Carmen.Util.addCssSheet=function(windowElt,filename,firstPos){var css_style=windowElt.document.createElement("link");css_style.setAttribute("rel","stylesheet");css_style.setAttribute("type","text/css");css_style.setAttribute("href",filename);var head=windowElt.document.getElementsByTagName("head")[0];if(firstPos)
head.insertBefore(css_style,head.firstChild);else
head.appendChild(css_style);}
Carmen.Util.addCssClass=function(elt,className){elt.className=elt.className+" "+className;}
initBanner=function(){var frame=window.frames["banner"];if(typeof(frame!="undefined")&&frame!=null&&frame.document.getElementById("CARTE_NOM")!=null){frame.document.getElementById("CARTE_NOM").innerHTML=Url.decode(jsOws.OWSContext.General.Title);Carmen.Util.addCssSheet(frame,overloadExtTheme,true);Carmen.Util.addCssClass(frame.document.body,"x-window-mc");}};Carmen.Control={}
Carmen.Control.wrapper=function(olControl,carmenControlName,btnConfig){return new OpenLayers.Class(olControl,{btnConfig:(btnConfig!=null)?btnConfig:{tooltip:'Button',tooltipType:'title',icon:'/IHM/images/defaultTool.gif',cls:'x-btn-icon',enableToggle:'true',toggleGroup:'mainMapControl'},btn:new Ext.Toolbar.Button(btnConfig),initialize:function(options){olControl.prototype.initialize.apply(this,arguments);if(this.btn.initialConfig.enableToggle)
this.btn.addListener('toggle',Carmen.Util.buildExt2olHandlerToggle(this));else
this.btn.addListener('click',Carmen.Util.buildExt2olHandlerButton(this));},setMap:function(map){olControl.prototype.setMap.apply(this,arguments);var tb=this.map.app.ui.getTopToolBar();tb.addItem(this.btn);this.map.app.ui.doLayout();},CLASS_NAME:"Carmen.Control."+carmenControlName,displayClass:("CmnControl"+carmenControlName).replace(/\./g,"")})};Carmen.Control.ZoomIn=Carmen.Control.wrapper(OpenLayers.Control.ZoomBox,"ZoomIn",{tooltip:'Zoom avant',tooltipType:'title',cls:'x-btn-icon cmn-tool-zoomin',enableToggle:true,toggleGroup:'mainMapControl'});Carmen.Control.ZoomOut=Carmen.Control.wrapper(OpenLayers.Control.ZoomOut,"ZoomOut",{tooltip:'Zoom arrière',tooltipType:'title',cls:'x-btn-icon cmn-tool-zoomout',enableToggle:false});Carmen.Control.DragPan=Carmen.Control.wrapper(OpenLayers.Control.DragPan,"DragPan",{tooltip:'Déplacement',tooltipType:'title',cls:'x-btn-icon cmn-tool-pan',enableToggle:true,toggleGroup:'mainMapControl'});Carmen.Control.ZoomFitAll=Carmen.Control.wrapper(OpenLayers.Control.ZoomToMaxExtent,"ZoomFitAll",{tooltip:'Zoom global',tooltipType:'title',cls:'x-btn-icon cmn-tool-fitall',enableToggle:false});Carmen.Control.Help=Carmen.Control.wrapper(OpenLayers.Class(OpenLayers.Control,{trigger:function(){Carmen.Util.openWindow('Help','http://carmen.ecologie.gouv.fr');}}),"Help",{tooltip:'Aide',tooltipType:'title',cls:'x-btn-icon cmn-tool-help',enableToggle:false});Carmen.Control.DataDownload=Carmen.Control.wrapper(OpenLayers.Class(OpenLayers.Control,{trigger:Carmen.Util.openDownloadData}),"DataDownload",{tooltip:'Téléchargement',tooltipType:'title',cls:'x-btn-icon cmn-tool-dnload',enableToggle:false,disabled:false});Carmen.Layer=OpenLayers.Util.extend(Carmen.Layer,OpenLayers.Layer);Carmen.Layer.CLASS_NAME="Carmen.Layer";Carmen.Layer.LEGEND_GRAPHIC_HEIGHT=10;Carmen.Layer.LEGEND_GRAPHIC_WIDTH=20;Carmen.Map=new OpenLayers.Class(OpenLayers.Map,{app:null,layerTreeManager:null,labelLayer:null,legend:null,toolTipControl:null,zoomOutsideMaxExtent:false,initialize:function(options){OpenLayers.Map.prototype.initialize.apply(this,arguments);},addLayer:function(layer,idx){var topLayer=null;for(var i=0,len=this.layers.length;i<len;i++){if(this.layers[i]==layer){var msg=OpenLayers.i18n('layerAlreadyAdded',{'layerName':layer.name});return false;}
if(this.layers[i].alwaysOnTop)
topLayer=this.layers[i];}
this.events.triggerEvent("preaddlayer",{layer:layer});layer.div.className="olLayerDiv";layer.div.style.overflow="";if(topLayer!=null){if(layer.alwaysOnTop){this.setLayerZIndex(layer,this.layers.length);topLayer.alwaysOnTop=false;}
else{this.setLayerZIndex(topLayer,this.layers.length);this.setLayerZIndex(layer,this.layers.length-1);}}
else{this.setLayerZIndex(layer,this.layers.length);}
if(layer.isFixed){this.viewPortDiv.appendChild(layer.div);}else{this.layerContainerDiv.appendChild(layer.div);}
topLayer=null;if(this.layers.length>0&&this.layers[this.layers.length-1].alwaysOnTop){topLayer=this.layers.pop();}
this.layers.push(layer);if(topLayer!=null)
this.layers.push(topLayer);layer.setMap(this);if(layer.isBaseLayer){if(this.baseLayer==null){this.setBaseLayer(layer);}else{layer.setVisibility(false);}}else{layer.redraw();}
this.events.triggerEvent("addlayer",{layer:layer});if(idx!=null){this.setLayerIndex(layer,idx)}},addControl:function(control,px){this.controls.push(control);this.addControlToMap(control,px);},addControlToMap:function(control,px){if(control.CLASS_NAME.indexOf("OpenLayers")>-1){OpenLayers.Map.prototype.addControlToMap.apply(this,arguments);}
else
control.setMap(this);if(this.displayProjection&&!control.displayProjection){control.displayProjection=this.displayProjection;}
control.draw();},getControl:function(id){var returnControl=null;for(var i=0,len=this.controls.length;i<len;i++){var control=this.controls[i];if(control.id==id){returnControl=control;break;}}
return returnControl;},removeControl:function(control){if((control)&&(control==this.getControl(control.id))){if(control.div&&(control.div.parentNode==this.viewPortDiv)){this.viewPortDiv.removeChild(control.div);}
OpenLayers.Util.removeItem(this.controls,control);}},isValidLonLat:function(lonlat){var valid=(lonlat!=null)&&this.zoomOutsideMaxExtent;if(lonlat!=null&&!this.zoomOutsideMaxExtent){var maxExtent=this.getMaxExtent();valid=maxExtent.containsLonLat(lonlat);}
return valid;},getLayerTreeManager:function(){if(this.layertreeManager==null){var controls=this.getControlsByClass('Carmen.Control.LayerTreeManager');this.layerTreeManager=controls.length==0?null:controls[0];}
return this.layerTreeManager;},getLegend:function(){if(this.legend==null){var legendControls=this.getControlsByClass("Carmen.Control.Legend");if(legendControls.length>0)
this.legend=legendControls[0];}
return this.legend;},clearSelection:function(){for(var i=0;i<this.layers.length;i++){layer=this.layers[i];if(layer instanceof Carmen.Layer.MapServerGroup&&layer.displayMode!=Carmen.Layer.MapServerGroup.DISPLAY_MAP){layer.setDisplayMode(Carmen.Layer.MapServerGroup.DISPLAY_MAP);}}},zoomToSuitableExtent:function(bounds,minScale,maxScale){var center=bounds.getCenterLonLat();var zoom=this.getZoomForExtent(bounds);if(minScale&&maxScale){var resolution=this.getResolutionForZoom(zoom);var scale=OpenLayers.Util.getScaleFromResolution(resolution,this.units);var newScale=scale<minScale?minScale:(scale>maxScale?maxScale:scale);if(newScale!=scale){resolution=OpenLayers.Util.getResolutionFromScale(newScale,this.units);zoom=this.getZoomForResolution(resolution);}}
this.setCenter(center,zoom);},getUniqueLayerName:function(prefix){var pre=(prefix&&prefix.length>0)?prefix:'layer';var i=layers.length;var n=pre+i;while(this.getLayersByName(n).length>0){i++;n=pre+i;}
return n;},setLabelLayer:function(layer){this.labelLayer=layer;},getLabelLayer:function(){return this.labelLayer;},_getTooltipControl:function(){if(this.toolTipControl==null){var toolTipControls=this.getControlsByClass("Carmen.Control.ToolTip");if(toolTipControls.length>0)
this.toolTipControl=toolTipControls[0];}
return this.toolTipControl;},toolTipActivate:function(){this._getTooltipControl();if(this.toolTipControl)
this.toolTipControl.activate();},toolTipDeactivate:function(){this._getTooltipControl();if(this.toolTipControl)
this.toolTipControl.deactivate();},CLASS_NAME:"Carmen.Map"});Ext.form.FileUploadField=Ext.extend(Ext.form.TextField,{buttonText:'Browse...',buttonOnly:false,buttonOffset:3,readOnly:true,autoSize:Ext.emptyFn,initComponent:function(){Ext.form.FileUploadField.superclass.initComponent.call(this);this.addEvents('fileselected');},onRender:function(ct,position){Ext.form.FileUploadField.superclass.onRender.call(this,ct,position);this.wrap=this.el.wrap({cls:'x-form-field-wrap x-form-file-wrap'});this.el.addClass('x-form-file-text');this.el.dom.removeAttribute('name');this.fileInput=this.wrap.createChild({id:this.getFileInputId(),name:this.name||this.getId(),cls:'x-form-file',tag:'input',type:'file',size:1});var btnCfg=Ext.applyIf(this.buttonCfg||{},{text:this.buttonText});this.button=new Ext.Button(Ext.apply(btnCfg,{renderTo:this.wrap,cls:'x-form-file-btn'+(btnCfg.iconCls?' x-btn-icon':'')}));if(this.buttonOnly){this.el.hide();this.wrap.setWidth(this.button.getEl().getWidth());}
this.fileInput.on('change',function(){var v=this.fileInput.dom.value;this.setValue(v);this.fireEvent('fileselected',this,v);},this);},getFileInputId:function(){return this.id+'-file';},onResize:function(w,h){Ext.form.FileUploadField.superclass.onResize.call(this,w,h);this.wrap.setWidth(w);if(!this.buttonOnly){var w=this.wrap.getWidth()-this.button.getEl().getWidth()-this.buttonOffset;this.el.setWidth(w);}},preFocus:Ext.emptyFn,getResizeEl:function(){return this.wrap;},getPositionEl:function(){return this.wrap;},alignErrorIcon:function(){this.errorIcon.alignTo(this.wrap,'tl-tr',[2,0]);}});Ext.reg('fileuploadfield',Ext.form.FileUploadField);Ext.namespace('Ext.ux.form');Ext.ux.form.BrowseButton=Ext.extend(Ext.Button,{inputFileName:'file',debug:false,FLOAT_EL_WIDTH:60,FLOAT_EL_HEIGHT:18,buttonCt:null,clipEl:null,floatEl:null,inputFileEl:null,originalHandler:null,originalScope:null,initComponent:function(){Ext.ux.form.BrowseButton.superclass.initComponent.call(this);this.originalHandler=this.handler;this.originalScope=this.scope;this.handler=null;this.scope=null;},onRender:function(ct,position){Ext.ux.form.BrowseButton.superclass.onRender.call(this,ct,position);this.buttonCt=this.el.child('.x-btn-center em');this.buttonCt.position('relative');var styleCfg={position:'absolute',overflow:'hidden',top:'0px',left:'0px'};if(Ext.isIE){Ext.apply(styleCfg,{left:'-3px',top:'-3px'});}else if(Ext.isGecko){Ext.apply(styleCfg,{left:'-3px',top:'-3px'});}else if(Ext.isSafari){Ext.apply(styleCfg,{left:'-4px',top:'-2px'});}
this.clipEl=this.buttonCt.createChild({tag:'div',style:styleCfg});this.setClipSize();this.clipEl.on({'mousemove':this.onButtonMouseMove,'mouseover':this.onButtonMouseMove,scope:this});this.floatEl=this.clipEl.createChild({tag:'div',style:{position:'absolute',width:this.FLOAT_EL_WIDTH+'px',height:this.FLOAT_EL_HEIGHT+'px',overflow:'hidden'}});if(this.debug){this.clipEl.applyStyles({'background-color':'green'});this.floatEl.applyStyles({'background-color':'red'});}else{this.floatEl.setOpacity(0.0);}
var buttonEl=this.el.child(this.buttonSelector);buttonEl.on('focus',this.onButtonFocus,this);if(Ext.isIE){this.el.on('keydown',this.onButtonKeyDown,this);}
this.createInputFile();},setClipSize:function(){if(this.clipEl){var width=this.buttonCt.getWidth();var height=this.buttonCt.getHeight();if(width===0||height===0){this.setClipSize.defer(100,this);}else{if(Ext.isIE){width=width+5;height=height+5;}else if(Ext.isGecko){width=width+6;height=height+6;}else if(Ext.isSafari){width=width+6;height=height+6;}
this.clipEl.setSize(width,height);}}},createInputFile:function(){this.floatEl.select('em').each(function(el){el.remove();});this.inputFileEl=this.floatEl.createChild({tag:'input',type:'file',size:1,name:this.inputFileName||Ext.id(this.el),tabindex:this.tabIndex,style:{position:'absolute',cursor:'pointer',right:'0px',top:'0px'}});this.inputFileEl=this.inputFileEl.child('input')||this.inputFileEl;this.inputFileEl.on({'click':this.onInputFileClick,'change':this.onInputFileChange,'focus':this.onInputFileFocus,'select':this.onInputFileFocus,'blur':this.onInputFileBlur,scope:this});if(this.tooltip){if(typeof this.tooltip=='object'){Ext.QuickTips.register(Ext.apply({target:this.inputFileEl},this.tooltip));}else{this.inputFileEl.dom[this.tooltipType]=this.tooltip;}}},onButtonFocus:function(e){if(this.inputFileEl){this.inputFileEl.focus();e.stopEvent();}},onButtonKeyDown:function(e){if(this.inputFileEl&&e.getKey()==Ext.EventObject.SPACE){this.inputFileEl.dom.click();e.stopEvent();}},onButtonMouseMove:function(e){var xy=e.getXY();xy[0]-=this.FLOAT_EL_WIDTH/2;xy[1]-=this.FLOAT_EL_HEIGHT/2;this.floatEl.setXY(xy);},onInputFileFocus:function(e){if(!this.isDisabled){this.el.addClass("x-btn-over");}},onInputFileBlur:function(e){this.el.removeClass("x-btn-over");},onInputFileClick:function(e){e.stopPropagation();},onInputFileChange:function(){if(this.originalHandler){this.originalHandler.call(this.originalScope,this);}},detachInputFile:function(noCreate){var result=this.inputFileEl;if(typeof this.tooltip=='object'){Ext.QuickTips.unregister(this.inputFileEl);}else{this.inputFileEl.dom[this.tooltipType]=null;}
this.inputFileEl.removeAllListeners();this.inputFileEl=null;if(!noCreate){this.createInputFile();}
return result;},getInputFile:function(){return this.inputFileEl;},disable:function(){Ext.ux.form.BrowseButton.superclass.disable.call(this);this.inputFileEl.dom.disabled=true;},enable:function(){Ext.ux.form.BrowseButton.superclass.enable.call(this);this.inputFileEl.dom.disabled=false;}});Ext.reg('browsebutton',Ext.ux.form.BrowseButton);Ext.ns('Ext.ux.layout');Ext.ux.layout.RowLayout=Ext.extend(Ext.layout.ContainerLayout,{monitorResize:true,isValidParent:function(c,target){return c.getEl().dom.parentNode==this.innerCt.dom;},onLayout:function(ct,target){var rs=ct.items.items,len=rs.length,r,i;if(!this.innerCt){target.addClass('ux-row-layout-ct');this.innerCt=target.createChild({cls:'x-row-inner'});}
this.renderAll(ct,this.innerCt);var size=target.getViewSize();if(size.width<1&&size.height<1){return;}
var h=size.height-target.getPadding('tb'),ph=h;this.innerCt.setSize({height:h});for(i=0;i<len;i++){r=rs[i];if(!r.rowHeight){ph-=(r.getSize().height+r.getEl().getMargins('tb'));}}
ph=ph<0?0:ph;for(i=0;i<len;i++){r=rs[i];if(r.rowHeight){r.setSize({height:Math.floor(r.rowHeight*ph)-r.getEl().getMargins('tb')});}}}});Ext.Container.LAYOUTS['ux.row']=Ext.ux.layout.RowLayout;Carmen.Control.ContextManager=new OpenLayers.Class(OpenLayers.Control,{btn:new Ext.Toolbar.Button({tooltip:'Sauvegarde et restauration de contextes de carte',tooltipType:'title',cls:'x-btn-icon cmn-tool-context',enableToggle:true,toggleGroup:'mainMapControl',disabled:false}),mainPanel:new Ext.TabPanel({activeItem:0}),savePanel:new Ext.FormPanel({id:'saveContextPanel',autoScroll:true,header:true,title:'Sauvegarde',height:120,bodyStyle:'padding:5px 5px 0; color: #000000;',labelStyle:'color: #000000;',items:[{xtype:'radiogroup',fieldLabel:'Mode de sauvegarde',name:'rb-mode',itemCls:'x-check-group-alt',columns:1,items:[{boxLabel:'sur&nbsp;le&nbsp;serveur',name:'rb-mode',inputValue:0,checked:true},{boxLabel:'sur&nbsp;votre&nbsp;machine',name:'rb-mode',inputValue:1}]}],buttons:[{id:'saveContextButton',text:'Enregistrer le contexte'}]}),loadPanel:new Ext.FormPanel({id:'loadContextPanel',autoScroll:true,header:true,title:'Chargement',height:120,fileUpload:true,bodyStyle:'padding:5px 5px 5px 5px; color: #000000;',labelStyle:'color: #000000;',buttons:[{xtype:'button',labelStyle:'',id:'loadContextButton',text:'Charger le contexte'}]}),fileField:new Ext.form.FileUploadField({id:'loadContextFileField',emptyText:'Sélectionner un fichier',fieldLabel:'Fichier OWS',allowBlank:false,name:'uploadedfile',buttonText:'Parcourir',vtype:'owsContext'}),win:new Ext.Window({id:'saveContextWindow',width:400,height:180,plain:true,title:'Sauvegarde et chargement de contextes',modal:false,autoDestroy:true,resizable:true,closeAction:'hide',shadow:false}),mapfile:null,serviceUrl:null,initialize:function(serviceUrl,mapfile,options){OpenLayers.Control.prototype.initialize.apply(this,arguments);this.mapfile=mapfile;this.serviceurl=serviceUrl;},setMap:function(map){OpenLayers.Control.prototype.setMap.apply(this,arguments);this.btn.addListener('toggle',Carmen.Util.buildExt2olHandlerToggle(this));var tb=this.map.app.ui.getTopToolBar();tb.addItem(this.btn);var control=this;this.win.on('hide',function(w){control.btn.toggle(false);},this.win);this.map.app.ui.doLayout();},activate:function(){OpenLayers.Control.prototype.activate.apply(this,arguments);this.map.toolTipDeactivate();this.showWindow();},deactivate:function(){OpenLayers.Control.prototype.deactivate.apply(this,arguments);if(this.win.rendered)
this.win.hide();this.map.toolTipActivate();},showWindow:function(){if(!this.win.rendered){this.mainPanel.add(this.savePanel);this.loadPanel.add(this.fileField);this.mainPanel.add(this.loadPanel);this.win.add(this.mainPanel);}
this.win.doLayout();if(!this.win.isVisible()){this.win.show();}
var saveBtn=Ext.getCmp('saveContextButton');saveBtn.on('click',this.onSave,this);var loadBtn=Ext.getCmp('loadContextButton');loadBtn.on('click',this.onLoad,this);},onSave:function(btn,evt){var queryParams=this.buildParams();var form=this.savePanel.getForm();switch(parseInt(form.getValues()['rb-mode'])){case this.SAVE_SERVER:this.performQueryServer(queryParams);break;default:this.performQueryLocal(queryParams);};this.win.hide();},onLoad:function(btn,evt){var filePath=this.fileField.getValue();var form=this.loadPanel.getForm();form.waitTitle='Chargement de contexte';if(form.isValid()){form.submit({url:'/services/LoadContext/index.php',waitMsg:'Transmission du fichier contexte',success:function(fp,o){Ext.Msg.confirm("Chargement de contexte","Mettre à jour la carte courante avec le contexte "+filePath+".",function(buttonId){if(buttonId=='yes'){Carmen.Util.loadPage(Carmen.Util.unhtmlspecialchars(o.result.contextURL));}});},failure:function(form,action){var msg=action.result.errmsg?action.result.errmsg:'Problème lors de l\'accès au serveur.';switch(action.result.failureType){case Carmen.CARMEN_ERROR_SESSION_EXPIRED:Ext.Msg.alert("Echec",msg);Carmen.Util.loadPage();break;default:Ext.Msg.alert("Echec",msg);break;}}});this.win.hide();}},buildParams:function(){var jsonContext=this.map.app.updateContext(false);var xmlContext=Carmen.Util.json2xml(jsonContext,this.XML_HEADER);var params={owsContext:xmlContext,map:this.mapfile};return params;},performQueryLocal:function(queryParams){var control=this;var form=this.savePanel.getForm().getEl().dom;form.enctype=form.encoding='multipart/form-data';Ext.Ajax.request({url:'/services/SaveContext/getBack.php',form:control.savePanel.getForm().getEl(),isUpLoad:true,failure:function(response){Carmen.Util.handleAjaxFailure(response,"Sauvegarde de contexte");},params:queryParams});},performQueryServer:function(queryParams){var control=this;var received=function(response){response=Ext.decode(response.responseText);Ext.MessageBox.show({title:'Sauvegarde de contexte sur le serveur',buttons:Ext.MessageBox.OK,msg:"Le contexte de la carte courante sera disponible pour une durée de "
+control.SAVE_SERVER_LIFE+" à l'url : <br/><br/>"
+response.contextURL+" <br/><br/>"+"Vous pouvez revenir au contexte courant de cette carte, en saisissant cette URL dans la barre d\'adresse de votre navigateur."});}
Ext.Ajax.request({url:'/services/SaveContext/index.php',success:function(response){received(response);},failure:function(response){Carmen.Util.handleAjaxFailure(response,"Sauvegarde de contexte");},params:queryParams});},SAVE_SERVER_LIFE:'7 jours',SAVE_SERVER:0,SAVE_LOCAL:1,XML_HEADER:'<?xml version="1.0" encoding="UTF-8"?>',CLASS_NAME:"Carmen.Control.ContextManager"});Carmen.Control.ContextManager.SAVE_SERVER=0;Carmen.Control.ContextManager.SAVE_LOCAL=1;Proj4js.defs["EPSG:2980"]="+proj=utm +zone=38 +south +ellps=intl +towgs84=-382,-59,-262,0,0,0,0 +units=m +no_defs";Proj4js.defs["EPSG:4326"]="+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs";Proj4js.defs["EPSG:2154"]="+proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3 +x_0=700000 +y_0=6600000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs";Proj4js.defs["EPSG:4258"]="+proj=longlat +ellps=GRS80 +no_defs";Carmen.Control.Inlay=new OpenLayers.Class(OpenLayers.Control,{font:null,fontFamily:'tahoma,arial,helvetica,sans-serif',color:'#000000',fontSize:'12px',fontWeight:'normal',fontStyle:'normal',backgroundColor:null,opacity:1.0,initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,arguments);this.fontFamily=this.font?this.font+','+this.fontFamily:this.fontFamily;if(this.color&&this.color.charAt(0)!='#')
this.color='#'+this.color;if(this.backgroundColor&&this.backgroundColor.charAt(0)!='#')
this.backgroundColor='#'+this.backgroundColor;if(this.backgroundColor&&this.backgroundColor.length==9){this.backgroundColor=this.backgroundColor.substring(0,6);this.opacity=parseInt(this.backgroundColor.substring(7,8),16)/255;}},setMap:function(map){OpenLayers.Control.prototype.setMap.apply(this,arguments);},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);this.div.style.display="block";this.div.style.position="absolute";this.div.style.backgroundColor=this.backgroundColor;this.div.style.fontFamily=this.fontFamily;this.div.style.fontWeight=this.fontWeight;this.div.style.color=this.color;this.div.style.fontSize=this.fontSize;this.div.style.fontStyle=this.fontStyle;OpenLayers.Util.modifyDOMElement(this.div,null,null,null,null,null,null,this.opacity);this.update();return this.div;},update:function(){},CLASS_NAME:"Carmen.Control.Inlay"});Proj4js.defs["EPSG:2971"]="+proj=utm +zone=22 +ellps=intl +towgs84=-186,230,110,0,0,0,0 +units=m +no_defs";Proj4js.defs["EPSG:2975"]="+proj=utm +zone=40 +south +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs";Carmen.TreeNodeInfoUI=Ext.extend(Ext.tree.TreeNodeUI,{constructor:function(config){Ext.apply(this,{});Carmen.TreeNodeInfoUI.superclass.constructor.apply(this,arguments);},renderElements_aux:function(e,j,i,k){this.indentMarkup=e.parentNode?e.parentNode.ui.getChildIndent():"";var f=typeof j.checked=="boolean";var c=j.href?j.href:Ext.isGecko?"":"#";var d=['<li class="x-tree-node"><div ext:tree-node-id="',e.id,'" class="x-tree-node-el x-tree-node-leaf x-unselectable ',j.cls,'" unselectable="on">','<span class="x-tree-node-indent">',this.indentMarkup,"</span>",'<img src="',this.emptyIcon,'" class="x-tree-ec-icon x-tree-elbow" />','<img src="',j.icon||this.emptyIcon,'" class="x-tree-node-icon cmnLayerTreeNodeIcon',(j.icon?" x-tree-node-inline-icon":""),(j.iconCls?" "+j.iconCls:""),'" unselectable="on" />','<a hidefocus="on" class="x-tree-node-anchor" href="',c,'" tabIndex="1" ',j.hrefTarget?' target="'+j.hrefTarget+'"':"",'><span unselectable="on">',e.text,"</span></a>","</div>",'<ul class="x-tree-node-ct" style="display:none;"></ul>',"</li>"].join("");var b;if(k!==true&&e.nextSibling&&(b=e.nextSibling.ui.getEl())){this.wrap=Ext.DomHelper.insertHtml("beforeBegin",b,d)}else{this.wrap=Ext.DomHelper.insertHtml("beforeEnd",i,d)}
this.elNode=this.wrap.childNodes[0];this.ctNode=this.wrap.childNodes[1];var h=this.elNode.childNodes;this.indentNode=h[0];this.ecNode=h[1];this.iconNode=h[2];var g=3;this.anchor=h[g];this.textNode=h[g].firstChild;},renderElements:function(e,j,i,k){this.renderElements_aux(e,j,i,k);}});Carmen.RootTreeNodeInfoUI=Ext.extend(Carmen.TreeNodeInfoUI,{render:function(){if(!this.rendered){var targetNode=this.node.ownerTree.innerCt.dom;this.node.expanded=true;targetNode.innerHTML='<div class="x-tree-root-node"></div>';this.wrap=this.ctNode=targetNode.firstChild;}},collapse:Ext.emptyFn,expand:Ext.emptyFn});Carmen.Control.ExportPdf=new OpenLayers.Class(OpenLayers.Control,{layoutModelsData:[['modele1.tpl','Légende et carte de situation à droite'],['modele2.tpl','Légende, carte de situation et copyright à gauche'],['modele3.tpl','Grandes légendes'],['modele4.tpl','Légende à gauche, carte de siuation au dessus']],btn:new Ext.Toolbar.Button({tooltip:'Export pdf',tooltipType:'title',cls:'x-btn-icon cmn-tool-printpdf',enableToggle:true,toggleGroup:'mainMapControl',disabled:false}),win:new Ext.Window({layout:'anchor',width:400,autoHeight:true,plain:true,id:"winPdf",title:'Export PDF',modal:false,autoDestroy:true,resizable:true,closeAction:'hide',shadow:false}),pdfPanel:new Ext.FormPanel({id:'generatepdf',autoScroll:true,fitToFrame:true,labelWidth:75,bodyStyle:'padding:5px 5px 0; color: #000000;',labelStyle:'color: #000000;',url:'/services/GetPDF/getPdf.php',items:[{xtype:"field",fieldLabel:'Titre',name:'title',value:"",width:'270'},{xtype:"textarea",fieldLabel:'Commentaire',name:'comment',width:'270'},{xtype:'radiogroup',columns:1,fieldLabel:'Format',name:'format',items:[{boxLabel:'A4 (petit format)',name:'format',inputValue:'A4',checked:true},{boxLabel:'A3 (grand format)',inputValue:'A3',name:'format'}]},{xtype:'radiogroup',columns:1,fieldLabel:'Qualité',name:'quality',items:[{boxLabel:'Moyenne (Firefox 2.x)',name:'quality',inputValue:'medium',id:'quality_medium_pdf'},{boxLabel:'Bonne (Autres navigateurs)',inputValue:'high',id:'quality_high_pdf',name:'quality',checked:true}]},{xtype:'radiogroup',columns:1,autoHeight:true,fieldLabel:'Traitement de la carte',name:'typeExport',items:[{boxLabel:'Echelle conservée',name:'typeExport',inputValue:'0',checked:true},{boxLabel:'Emprise conservée',name:'typeExport',inputValue:'1'}]},{xtype:"hidden",id:"legend",name:"legend",value:"",hidden:true,hiddenLabel:true},{xtype:"hidden",name:"contextJs",value:"",hidden:true,hiddenLabel:true},{xtype:"hidden",name:"mapWidth",value:"",hidden:true,hiddenLabel:true}],buttons:[{id:'submitPdf',text:'Générer'}]}),initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,arguments);},initLayoutCombo:function(context){if(context.mdataMap.layoutModels!="undefined"&&context.mdataMap.layoutModels!=""){var tabModels=(Url.decode(context.mdataMap.layoutModels)).split(";");if(tabModels.length>0){this.layoutModelsData=[];for(var i=0;i<tabModels.length;i++){var tabInfoModel=tabModels[i].split("@");this.layoutModelsData.push([tabInfoModel[0],tabInfoModel[1]]);}}}
var layoutCombo=new Ext.form.ComboBox({tpl:'<tpl for="."><div ext:qtip="{desc}" class="x-combo-list-item">{desc}</div></tpl>',typeAhead:true,editable:false,mode:'local',triggerAction:'all',emptyText:'Modèles de mise en page',selectOnFocus:true,width:280,displayField:'desc',loadingText:'Chargement',valueField:'modele',name:'modeleLayout',hiddenName:'modele',fieldLabel:'Modèle',store:new Ext.data.SimpleStore({fields:['modele','desc'],data:[]})});this.pdfPanel.add(layoutCombo);layoutCombo.getStore().loadData(this.layoutModelsData);layoutCombo.setValue(this.layoutModelsData[0][0]);},setMap:function(map){OpenLayers.Control.prototype.setMap.apply(this,arguments);this.initLayoutCombo(this.map.app.context);this.btn.addListener('toggle',Carmen.Util.buildExt2olHandlerToggle(this));var tb=this.map.app.ui.getTopToolBar();tb.addItem(this.btn);var control=this;this.win.on('hide',function(w){control.btn.toggle(false);},this.win);this.map.app.ui.doLayout();},activate:function(){OpenLayers.Control.prototype.activate.apply(this,arguments);this.map.toolTipDeactivate();this.showWindow();},deactivate:function(){OpenLayers.Control.prototype.deactivate.apply(this,arguments);if(this.win.rendered)
this.win.hide();this.map.toolTipActivate();},trigger:function(){this.showWindow();},showWindow:function(){if(!this.win.rendered){this.win.add(this.pdfPanel);var submitBtn=Ext.getCmp('submitPdf');submitBtn.on('click',function(btn,evt){var form=Ext.getCmp("generatepdf").getForm();form.getEl().dom.target='iFramePdf';form.getEl().dom.action='/services/GetPDF/getPdf.php';if(!form.isValid())
Ext.Msg.alert('Export PDF','Erreur');else{var winPDF=new Ext.Window({layout:'anchor',plain:true,title:'Prévisualisation',modal:false,width:Math.min(document.body.clientWidth-100,1220),height:Math.min(document.body.clientHeight-100,700),autoDestroy:true,resizable:true,closeAction:'close',id:'pdf_view',shadow:false,items:[{xtype:'progress',id:'pProgress',autoWidth:true,text:'Génération du pdf(0%)'},new Ext.ux.IFrameComponent({url:"/blank.html",name:"iFramePdf",width:Math.min(document.body.clientWidth-100,1220)-20,height:Math.min(document.body.clientHeight-100,790)-25})]});winPDF.show();form.getEl().dom.submit();var progressBar1=Ext.getCmp("pProgress");progressBar1.reset();progressBar1.show();progressBar1.wait({duration:20000,interval:1000,increment:30,fn:function(){progressBar1.hide();},scope:progressBar1});}},submitBtn);this.win.doLayout();}
if(!this.win.isVisible()){var form=this.pdfPanel.getForm();this.win.show();var app=this.map.app;var ctx=app.context;form.setValues({"title":(ctx.getTitle()),"mapWidth":app.map.size.w,"legend":app.map.getLegend().toHTML(true).innerHTML,"contextJs":Ext.util.JSON.encode(app.updateContext(true))});}},CLASS_NAME:"Carmen.Control.ExportPdf"});Proj4js.defs["EPSG:27563"]="+proj=lcc +lat_1=44.10000000000001 +lat_0=44.10000000000001 +lon_0=0 +k_0=0.999877499 +x_0=600000 +y_0=200000 +a=6378249.2 +b=6356515 +towgs84=-168,-60,320,0,0,0,0 +pm=paris +units=m +no_defs";Proj4js.defs["EPSG:27574"]="+proj=lcc +lat_1=42.16500000000001 +lat_0=42.16500000000001 +lon_0=0 +k_0=0.99994471 +x_0=234.358 +y_0=4185861.369 +a=6378249.2 +b=6356515 +towgs84=-168,-60,320,0,0,0,0 +pm=paris +units=m +no_defs";Carmen.Control.Refresh=new OpenLayers.Class(OpenLayers.Control,{btn:new Ext.Toolbar.Button({tooltip:'Actualiser',tooltipType:'title',cls:'x-btn-icon cmn-tool-reload',enableToggle:false,disabled:false}),initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,arguments);},setMap:function(map){OpenLayers.Control.prototype.setMap.apply(this,arguments);this.btn.addListener('click',Carmen.Util.buildExt2olHandlerButton(this));var tb=this.map.app.ui.getTopToolBar();tb.addItem(this.btn);this.map.app.ui.doLayout();},trigger:function(){Ext.MessageBox.confirm("Rechargement de la carte","Vous êtes sur le point de recharger la carte courante "+"dans son contexte initial. Toutes les annotations et les "+"configurations que vous n'aurez pas enregistrées dans un "+"contexte seront définitivement perdues. Voulez-vous poursuivre ?",this.handleConfirmResponse,this);},handleConfirmResponse:function(btnId,msg,obj){if(btnId=='yes')
Carmen.Util.loadPage();},CLASS_NAME:"Carmen.Control.Refresh"});Proj4js.defs["EPSG:32620"]="+proj=utm +zone=20 +ellps=WGS84 +datum=WGS84 +units=m +no_defs";Proj4js.defs["EPSG:3727"]="+proj=tmerc +lat_0=-21.11666666666667 +lon_0=55.53333333333333 +k=1 +x_0=160000 +y_0=50000 +ellps=intl +units=m +no_defs";OpenLayers.Format.WMSGetFeatureInfo=OpenLayers.Class(OpenLayers.Format.XML,{layerIdentifier:'_layer',featureIdentifier:'_feature',regExes:{trimSpace:(/^\s*|\s*$/g),removeSpace:(/\s*/g),splitSpace:(/\s+/),trimComma:(/\s*,\s*/g)},gmlFormat:null,initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,arguments);OpenLayers.Util.extend(this,options);this.options=options;},read:function(data){var result;if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
var root=data.documentElement;if(root){var scope=this;var read=this["read_"+root.nodeName];if(read){result=read.call(this,root);}else{result=new OpenLayers.Format.GML((this.options?this.options:{})).read(data);}}else{result=data;}
return result;},read_msGMLOutput:function(data){var response=[];var layerNodes=this.getSiblingNodesByTagCriteria(data,this.layerIdentifier);if(layerNodes){for(var i=0,len=layerNodes.length;i<len;++i){var node=layerNodes[i];var layerName=node.nodeName;if(node.prefix){layerName=layerName.split(':')[1];}
var layerName=layerName.replace(this.layerIdentifier,'');var featureNodes=this.getSiblingNodesByTagCriteria(node,this.featureIdentifier);if(featureNodes){for(var j=0;j<featureNodes.length;j++){var featureNode=featureNodes[j];var geom=this.parseGeometry(featureNode);var attributes=this.parseAttributes(featureNode);var feature=new OpenLayers.Feature.Vector(geom,attributes,null);feature.type=layerName;response.push(feature);}}}}
return response;},read_FeatureInfoResponse:function(data){var response=[];var featureNodes=this.getElementsByTagNameNS(data,'*','FIELDS');for(var i=0,len=featureNodes.length;i<len;i++){var featureNode=featureNodes[i];var geom=null;var attributes={};for(var j=0,jlen=featureNode.attributes.length;j<jlen;j++){var attribute=featureNode.attributes[j];attributes[attribute.nodeName]=attribute.nodeValue;}
response.push(new OpenLayers.Feature.Vector(geom,attributes,null));}
return response;},getSiblingNodesByTagCriteria:function(node,criteria){var nodes=[];var children,tagName,n,matchNodes,child;if(node&&node.hasChildNodes()){children=node.childNodes;n=children.length;for(var k=0;k<n;k++){child=children[k];while(child&&child.nodeType!=1){child=child.nextSibling;k++;}
tagName=(child?child.nodeName:'');if(tagName.length>0&&tagName.indexOf(criteria)>-1){nodes.push(child);}else{matchNodes=this.getSiblingNodesByTagCriteria(child,criteria);if(matchNodes.length>0){(nodes.length==0)?nodes=matchNodes:nodes.push(matchNodes);}}}}
return nodes;},parseAttributes:function(node){var attributes={};if(node.nodeType==1){var children=node.childNodes;n=children.length;for(var i=0;i<n;++i){var child=children[i];if(child.nodeType==1){var grandchildren=child.childNodes;if(grandchildren.length==1){var grandchild=grandchildren[0];if(grandchild.nodeType==3||grandchild.nodeType==4){var name=(child.prefix)?child.nodeName.split(":")[1]:child.nodeName;var value=grandchild.nodeValue.replace(this.regExes.trimSpace,"");attributes[name]=value;}}}}}
return attributes;},parseGeometry:function(node){if(!this.gmlFormat){this.gmlFormat=new OpenLayers.Format.GML();}
var feature=this.gmlFormat.parseFeature(node);var geometry=null;if(feature&&feature.geometry){geometry=feature.geometry.clone();feature.destroy();}
return geometry;},CLASS_NAME:"OpenLayers.Format.WMSGetFeatureInfo"});Carmen.Control.LayerTreeManager=new OpenLayers.Class(OpenLayers.Control,{layerTreePanel:new Ext.tree.TreePanel({id:'treePanel',margins:'5 0 5 5',useArrows:true,animate:true,enableDD:true,border:false,autoScroll:true,fitToFrame:true,rootVisible:true,autoWidth:true,root:{text:'legende'}}),layerManagerPanel:new Ext.Panel({title:'L&eacute;gende',hideMode:'offsets',hidden:true,collapsible:true,margins:'0 0 0 0',fitToFrame:true,layout:'fit',rowHeight:1.0,layoutConfig:{border:false}}),layerTree:null,visible:true,initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,arguments);Ext.override(Ext.tree.TreeNode,{removeChild:function(node){if(this.ownerTree)this.ownerTree.getSelectionModel().unselect(node);Ext.tree.TreeNode.superclass.removeChild.apply(this,arguments);if(this.rendered){if(this.childrenRendered){node.ui.remove();}
if(this.childNodes.length<1){this.collapse(false,false);}else{this.ui.updateExpandIcon();}
if(!this.firstChild&&!this.isHiddenRoot()){this.childrenRendered=false;}}
return node;},clone:function(transform){var atts=this.attributes;if(transform)
atts=transform(atts);atts.id=Ext.id(null,"ynode-");var clone=new Ext.tree.TreeNode(Ext.apply({},atts));clone.text=this.text;for(var i=0;i<this.childNodes.length;i++){clone.appendChild(this.childNodes[i].clone(transform));}
return clone;},filter:function(test){var res=false;var i=0;while(i<this.childNodes.length){var child=this.childNodes[i];if(!child.filter(test))
i++;}
if(!test(this)&&this.getDepth()>0){res=true;this.remove();}
return res;},collect:function(attributeName,onlyLeaf){var collected=new Array();if((onlyLeaf&&this.isLeaf())||!onlyLeaf){if(attributeName in this)
collected.push(this[attributeName]);else if(attributeName in this.attributes)
collected.push(this.attributes[attributeName]);}
for(var i=0;i<this.childNodes.length;i++){var childCollected=this.childNodes[i].collect(attributeName,onlyLeaf);collected=collected.concat(childCollected);}
return collected;},collectChildNodes:function(test){var collected=new Array();for(var i=0;i<this.childNodes.length;i++){if(test(this.childNodes[i]))
collected.push(this.childNodes[i]);collected=collected.concat(this.childNodes[i].collectChildNodes(test));}
return collected;},findChildByAttribute:function(att,value){var res=null;if(this.hasChildNodes()){var i=0;while(i<this.childNodes.length&&res==null){var child=this.childNodes[i];if(att in child&&child[att]==value)
res=child;else if(att in child.attributes&&child.attributes[att]==value)
res=child;else
res=child.findChildByAttribute(att,value);i++;}
return res;}},updateIndex:function(applyToChildNodes){this.attributes.index=this.parentNode==null?0:this.parentNode.indexOf(this);if(applyToChildNodes){for(var i=0;i<this.childNodes.length;i++){this.childNodes[i].updateIndex(applyToChildNodes);}}}});},setMap:function(map){OpenLayers.Control.prototype.setMap.apply(this,arguments);this.layerManagerPanel.add(this.layerTreePanel);var navPanel=this.map.app.ui.getNavigationPanel();navPanel.add(this.layerManagerPanel);this.layerTreePanel.expand();this.map.app.ui.doLayout();this.layerTree.expand(true);},treeLayoutInit:function(){this.layerTreePanel.dropZone=new Carmen.Control.LayerTreeManager.TreeDropZone(this.layerTreePanel,this.layerTreePanel.dropConfig||{ddGroup:this.layerTreePanel.ddGroup||"TreeDD",appendOnly:this.layerTreePanel.ddAppendOnly===true,containerScroll:true});this.updateTreeNodes(this.layerTree,function(n){this._updateWMSNodeIcon(n);this._updateNodeCollapse(n);this._updateNodeVisibilityFromScale(n);n.updateIndex(false);this._addNodeTransparencySlider(n);},this,this._groupNodeFilter);if(this.visible)
this.layerManagerPanel.show();},buildTree:function(jsonLayerTree,jsonLayerList){this.layerTree=this._buildLayerTree(jsonLayerTree.LayerTreeNode,jsonLayerList);this.layerTreePanel.setRootNode(this.layerTree);},getLayerTree:function(){return this.layerTree;},getSubLayerTreeBy:function(filter){var tree=this.getLayerTree().clone();tree.filterChildNodes(this._filterVisibleNode);return tree;},_collectVisibilityInfo:function(node){var collector=[];if('type'in node.attributes&&node.attributes.type==Carmen.Control.LayerTreeManager.NODE_LAYER){collector.push({layerName:node.attributes.layerName,layerIdx:node.attributes.layerIdx,visible:node.attributes.OlLayer.getVisibility(node.attributes.layerName)});}
else if('type'in node.attributes&&node.attributes.type==Carmen.Control.LayerTreeManager.NODE_GROUP){for(var i=0;i<node.childNodes.length;i++){var infos=this._collectVisibilityInfo(node.childNodes[i]);collector=collector.concat(infos);}}
return collector;},getLayersVisibility:function(){return this._collectVisibilityInfo(this.layerTree);},_filterVisibleNode:function(node){var res=true;res=('type'in node.attributes)&&((node.attributes.type==this.NODE_GROUP&&node.hasChildNodes())||(node.attributes.type==this.NODE_LAYER&&node.attributes.OlLayer.getSubLayerVisibility(node.attributes.jsonLayerDesc.Title)));return res;},_filterWMSLayerNodes:function(n){var type=Ext.value(n.attributes.type,-1,false);var res=(type==Carmen.Control.LayerTreeManager.NODE_LAYER&&n.attributes.OlLayer instanceof Carmen.Layer.WMSGroup);return res;},_groupNodeFilter:function(n){var type=Ext.value(n.attributes.type,-1,false);return(type==Carmen.Control.LayerTreeManager.NODE_GROUP);},_updateWMSNodeIcon:function(n){if(this._filterWMSLayerNodes(n)){var domIconEl=n.getUI().getIconEl();var layer=n.attributes.OlLayer;var layerName=n.attributes.layerName;var info=layer.getSubLayerInfo(layerName);if(info){var iconElt=Ext.fly(n.getUI().getIconEl());var domIconEl=iconElt.dom;var wmsName=info.wmsName;domIconEl.src=layer.getLegendGraphicURL(wmsName);}}},_filterOpacityHandlingNodes:function(n){return n.attributes.forceOpacityControl;},_addNodeTransparencySlider:function(n){if(this._filterOpacityHandlingNodes(n)){var val=n.attributes.opacity;Carmen.Control.LayerTreeManager.addTransparencySliderToNode(n,val);}},updateNodeOpacityValues:function(){var nodesWOpacityCtl=this.layerTree.collectChildNodes(this._filterOpacityHandlingNodes);for(var i=0;i<nodesWOpacityCtl.length;i++){var n=nodesWOpacityCtl[i];var slider=Ext.getCmp(n.id+'_slider');var val=slider.getValue();n.attributes.opacity=1.0-(val/100.0);}},CLASS_NAME:"Carmen.Control.LayerTreeManager",NODE_LAYER:0,NODE_GROUP:1,NODE_CLASS:2,NODE_FEATURE:3,_getLayer:function(jsonLayerList,layerName){var layer=null;if(jsonLayerList instanceof Array){var i=0;while(i<jsonLayerList.length&&jsonLayerList[i].attributes.name!=layerName){i++;}
if(i<jsonLayerList.length){layer=jsonLayerList[i];}}
else{if(jsonLayerList.attributes.name!=layerName){layer=jsonLayerList;}}
return layer;},_getSingleClassLegendUrl:function(jsonLayerDesc){var url='/none';if('StyleList'in jsonLayerDesc){if('Style'in jsonLayerDesc.StyleList&&!(jsonLayerDesc.StyleList.Style instanceof Array)&&'LegendURL'in jsonLayerDesc.StyleList.Style){var legendUrl=jsonLayerDesc.StyleList.Style.LegendURL.attributes;var url=legendUrl.server+legendUrl.mapfile+'_'+
legendUrl.layer+'_class'+legendUrl.classIdx+'.jpeg';}}
return url;},_buildMutliClassLegend:function(jsonLayerDesc,displayClass){var classeNodes=[];for(var i=0;i<jsonLayerDesc.StyleList.Style.length;i++){if(displayClass!=null&&displayClass[i]!="OFF"){var style=jsonLayerDesc.StyleList.Style[i];var legendUrl=style.LegendURL.attributes;var url=legendUrl.server+legendUrl.mapfile+'_'+
legendUrl.layer+'_class'+legendUrl.classIdx+'.jpeg';if(style.Name!=""){var classNode=new Ext.tree.TreeNode({text:style.Name,leaf:true,icon:url,draggable:false,uiProvider:Carmen.TreeNodeUI});classNode.attributes.type=this.NODE_CLASS;classeNodes.push(classNode);}}}
return classeNodes;},_buildLayerTree:function(jsonNode,jsonLayerList){var tree=this._buildLayerTree_aux(jsonNode,jsonLayerList);var nodesWOpacityCtl=tree.collectChildNodes(this._filterOpacityHandlingNodes);for(var i=0;i<nodesWOpacityCtl.length;i++){nodesWOpacityCtl[i].attributes.hasBottomElt=true;}
return tree;},_buildLayerTree_aux:function(jsonNode,jsonLayerList){var att=jsonNode.attributes;var groupNode=(att.type=="group");var jsonLayerDesc=jsonLayerList[att.layerIdx];var multiClass=!groupNode&&('StyleList'in jsonLayerDesc)&&('Style'in jsonLayerDesc.StyleList)&&(jsonLayerDesc.StyleList.Style instanceof Array);var mdata_url=(jsonLayerDesc&&'layerSettings_Metadata'in jsonLayerDesc.Extension&&jsonLayerDesc.Extension.layerSettings_Metadata.length>0)?Url.decode(jsonLayerDesc.Extension.layerSettings_Metadata):null;var node=new Ext.tree.TreeNode({text:att.name=="root"?Carmen.Control.LayerTreeManager.TREE_NODE_ROOT_LABEL:att.name,leaf:!groupNode,expanded:(groupNode&&att.open=="1")||multiClass,checked:(groupNode?true:jsonLayerDesc.attributes.hidden=="0"),cls:(!groupNode&&mdata_url!=null)?'cmnLayerTreeLayerNodeMetadata':'',icon:groupNode||multiClass?'/IHM/images/empty.gif':this._getSingleClassLegendUrl(jsonLayerDesc),iconCls:groupNode?'cmnLayerTreeGroupNodeIcon':'cmnLayerTreeLayerNodeIcon',allowDrop:groupNode,uiProvider:Carmen.TreeNodeUI,iconDisplayStrategy:!groupNode&&!multiClass,listeners:{'beforemove':{fn:function(tree,node,oldParent,newParent,index){switch(node.attributes.type){case(this.NODE_GROUP):this.moveGroupNode(tree,node,oldParent,newParent,index);break;case(this.NODE_LAYER):this.moveLayerNode(tree,node,oldParent,newParent,index);break;default:break;}},scope:this,delay:100}}});node.attributes.visible=true;node.attributes.opacity=parseFloat(Ext.value(att.opacity,"1.0",false));node.attributes.forceOpacityControl=parseInt(Ext.value(att.forceOpacityControl,"0",false))==1;if(groupNode){node.attributes.type=this.NODE_GROUP;if('LayerTreeNode'in jsonNode){if(jsonNode.LayerTreeNode instanceof Array){for(var i=0;i<jsonNode.LayerTreeNode.length;i++){node.appendChild(this._buildLayerTree_aux(jsonNode.LayerTreeNode[i],jsonLayerList));}}
else
node.appendChild(this._buildLayerTree_aux(jsonNode.LayerTreeNode,jsonLayerList));}
node.attributes.expanded=(att.open=="1");node.attributes.checked=this._countChildNodesChecked(node)>0;}
else{if(mdata_url!=null){node.attributes.mdata_url=mdata_url;node.on('click',function(n,evt){Carmen.Util.openWindowIframe("Métadonnées de la couche",n.attributes.mdata_url);},node);}
var displayClassLegend=Ext.value(Url.decode(jsonLayerDesc.Extension.layerSettings_ActivThemes),'ON',false);if(displayClassLegend=="OFF"){node.getUI().hide();node.attributes.visible=false;}
else if(multiClass){var displayClass=displayClassLegend.split('|');displayClass=displayClass.length>0?displayClass:null;var classLegend=this._buildMutliClassLegend(jsonLayerDesc,displayClass);if(classLegend!=null)
node.appendChild(classLegend);}
node.attributes.jsonLayerDesc=this._getLayer(jsonLayerList,att.mapName);node.attributes.jsonLayerDesc=jsonLayerList[att.layerIdx];node.attributes.layerIdx=att.layerIdx;node.attributes.layerName=node.attributes.jsonLayerDesc.Title;if(node.attributes.jsonLayerDesc.Extension.layerSettings_infoFields)
node.attributes.infoFields=decodeURIComponent(node.attributes.jsonLayerDesc.Extension.layerSettings_infoFields);if(node.attributes.jsonLayerDesc.Extension.layerSettings_briefFields)
node.attributes.briefFields=decodeURIComponent(node.attributes.jsonLayerDesc.Extension.layerSettings_briefFields);if(node.attributes.jsonLayerDesc.Extension.layerSettings_ToolTipFields)
node.attributes.toolTipFields=decodeURIComponent(node.attributes.jsonLayerDesc.Extension.layerSettings_ToolTipFields);node.attributes.infoData=null;node.attributes.baseQueryURL=decodeURIComponent(node.attributes.jsonLayerDesc.Extension.layerSettings_queryURL);var minScale=Ext.value(node.attributes.jsonLayerDesc.MinScaleDenominator,null,false);minScale=minScale!=null?parseFloat(minScale):minScale;if(!isNaN(minScale))
node.attributes.minScale=minScale;var maxScale=Ext.value(node.attributes.jsonLayerDesc.MaxScaleDenominator,null,false);maxScale=maxScale!=null?parseFloat(maxScale):maxScale;if(!isNaN(maxScale))
node.attributes.maxScale=maxScale;node.attributes.type=this.NODE_LAYER;node.attributes.providerId=att.providerGrpId;node.attributes.initialChecked=jsonLayerDesc.attributes.hidden=="0";node.getUI().toggleCheck(node.attributes.jsonLayerDesc.hidden!="0");}
node.attributes.open=(groupNode&&att.open=="1")||multiClass;node.addListener('checkchange',this.onNodeCheck,node);return node;},onNodeCheck:function(n,state){if(n.ascending){var c=0;for(var i=0;i<n.childNodes.length;i++){c=(n.childNodes[i].attributes.checked===true)?c+1:c;}
var cb=n.getUI().checkbox;if(cb){cb.checked=(c>0);cb.readOnly=(c<n.childNodes.length);n.attributes.checked=cb.checked;}
if(n.getDepth()>0){n.parentNode.ascending=true
n.parentNode.fireEvent('checkchange',n.parentNode,state);}
n.ascending=false;}
else{if(!n.descending){n.descending=true;if(n.attributes.type==Carmen.Control.LayerTreeManager.NODE_GROUP){for(i=0;i<n.childNodes.length;i++){var cb=n.childNodes[i].getUI().checkbox;if(cb){cb.checked=state;cb.defaultChecked=state;n.childNodes[i].attributes.checked=state;}
n.childNodes[i].fireEvent('checkchange',n.childNodes[i],state);}}
n.descending=false;if(n.getDepth()>0&&!n.parentNode.descending){n.parentNode.ascending=true;n.parentNode.fireEvent('checkchange',n.parentNode,state);var cb=n.getUI().checkbox;if(cb)cb.readOnly=false;}}}},updateTreeNodes:function(node,f,ctx,applyToChildrenFilter){ctx=Ext.value(ctx,null,false);if(ctx==null)
f(node);else
f.call(this,node);if(applyToChildrenFilter!=null&&!applyToChildrenFilter(node))
return;for(var i=0;i<node.childNodes.length;i++){this.updateTreeNodes(node.childNodes[i],f,ctx,applyToChildrenFilter);}},_updateNodeVisibilityFromScale:function(node){if(node.attributes.type==this.NODE_LAYER){if(node.attributes.minScale&&node.attributes.maxScale){this.map.events.register('zoomend',node,this.updateNodeFromScale);this.updateNodeFromScale.apply(node);}}},_updateNodeCollapse:function(node){if(node.attributes.open)
node.expand();else
node.collapse();},_countChildNodesChecked:function(node){var c=0;for(var i=0;i<node.childNodes.length;i++){c=(node.childNodes[i].attributes.checked===true)?c+1:c;}
return c;},updateNodeFromScale:function(){var desc=this.attributes.jsonLayerDesc;var olLayer=this.attributes.OlLayer;var scaleDependant=(desc.Extension.layerSettings_legendScaleDisplay&&desc.Extension.layerSettings_legendScaleDisplay=='ON');if(olLayer!=null&&olLayer.map!=null){var scale=olLayer.map.getScale();scale=scale>0?Math.round(scale):scale;var outOfScale=(scale>desc.MaxScaleDenominator||scale<desc.MinScaleDenominator);var layerVisible=(this.attributes.checked===true)&&!outOfScale;olLayer.setSubLayerVisibility(this.attributes.layerName,layerVisible);if(outOfScale){if(scaleDependant){this.getUI().hide();}
else{this.disable();this.cascade(function(){this.disable()});}}
else
if(scaleDependant)
this.getUI().show();else{this.enable();this.cascade(function(){this.enable()});}}},findPreviousLayer:function(groupNode,index){var res=null;if(index==0){res=groupNode.getDepth()==0?null:this.findPreviousLayer(groupNode.parentNode,groupNode.parentNode.indexOf(groupNode));}
else{var brother=groupNode.childNodes[index-1];var layers=brother.collect("OlLayer",true);res=layers[layers.length-1];}
return res;},linkLayerToNode:function(OLlayer,parentNode){var layerNames=[];for(var i=0;i<OLlayer.subLayers.length;i++){layerNames.push(OLlayer.subLayers[i].name);}
var layerNodesToUpdate=parentNode.collectChildNodes(function(n){return('layerName'in n.attributes&&Carmen.Util.set_member(layerNames,n.attributes.layerName));});for(var i=0;i<layerNodesToUpdate.length;i++){var n=layerNodesToUpdate[i];n.attributes.OlLayer=OLlayer;}},moveGroupNode:function(tree,node,oldParent,newParent,indexNode){listNodes=oldParent.childNodes;var prevIndex=node.attributes.index;var bb=node.previousSibling;var ba=node.nextSibling;if(bb!=null&&ba!=null&&bb.attributes.type==this.NODE_LAYER&&ba.attributes.type==this.NODE_LAYER&&bb.attributes.OlLayer==ba.attributes.OlLayer){var index=ba.attributes.OlLayer.getSubLayerInfo(ba.attributes.layerName).index-1;var newLayers=ba.attributes.OlLayer.split(index);this.linkLayerToNode(newLayers[1],newParent);var pos=this.map.getLayerIndex(bb.attributes.OlLayer);this.map.addLayer(newLayers[1],pos);newLayers[0].redraw();newLayers[1].setVisibility(true);}
var layerBefore=this.findPreviousLayer(newParent,indexNode);var startIndex=layerBefore==null?this.map.layers.length:this.map.getLayerIndex(layerBefore);layersToMove=Carmen.Util.set_from_array(node.collect('OlLayer',true));for(var i=0;i<layersToMove.length;i++){this.map.setLayerIndex(layersToMove[i],(startIndex-1)-i);}
newParent.updateIndex(true);},getLastLayerFromGroupNode:function(node){var res=node;if(node.hasChildNodes()){var lastChild=node.childNodes[node.childNodes.length-1];if('type'in lastChild.attributes){switch(lastChild.attributes.type){case this.NODE_GROUP:res=this.getLastLayerFromGroupNode(lastChild);break;case this.NODE_LAYER:res=lastChild.attributes.OlLayer;break;default:res=null;break;}}}
return res;},getFirstLayerFromGroupNode:function(node){var res=null;if(node.hasChildNodes()){var firstChild=node.childNodes[0];if('type'in firstChild.attributes){switch(firstChild.attributes.type){case this.NODE_GROUP:res=this.getFirstLayerFromGroupNode(firstChild);break;case this.NODE_LAYER:res=firstChild.attributes.OlLayer;break;default:res=null;break;}}}
return res;},updateNodeLayerControl:function(node){var layer=node.attributes.OlLayer;},moveLayerNode:function(tree,node,oldParent,newParent,indexNode){listNodes=oldParent.childNodes;var prevIndex=node.attributes.index;var descending=prevIndex<indexNode;indexNode=descending?indexNode-1:indexNode;var bb=node.previousSibling;var ba=node.nextSibling;var pbb=null;var pba=null;var i=0;while(i<listNodes.length&&(pba==null||pbb==null)){if(listNodes[i].attributes.index==prevIndex-1){pbb=listNodes[i];}
else{if(listNodes[i].attributes.index==prevIndex+1)
pba=listNodes[i];}
i++;}
var Lpos_node=node.attributes.layerIdx;if((pbb!=null)&&(pbb.attributes.type==this.NODE_LAYER)&&(pbb.attributes.OlLayer==node.attributes.OlLayer)&&((!descending&&(ba!=null)&&((ba.attributes.type==this.NODE_LAYER&&ba.attributes.OlLayer!=node.attributes.OlLayer)||ba.attributes.type==this.NODE_GROUP))||(descending&&(bb!=null)&&((bb.attributes.type==this.NODE_LAYER&&bb.attributes.OlLayer!=node.attributes.OlLayer)||bb.attributes.type==this.NODE_GROUP)))){var indexSLn=node.attributes.OlLayer.getSubLayerInfo(node.attributes.layerName).index-1;var newLayers=pbb.attributes.OlLayer.split(indexSLn);this.linkLayerToNode(newLayers[1],newParent);var indexLpbb=this.map.getLayerIndex(pbb.attributes.OlLayer);this.map.addLayer(newLayers[1],indexLpbb);newLayers[0].redraw();newLayers[1].setVisibility(true);}
if((pba!=null)&&(pba.attributes.type==this.NODE_LAYER)&&(pba.attributes.OlLayer==node.attributes.OlLayer)&&((!descending&&(ba!=null)&&((ba.attributes.type==this.NODE_LAYER&&ba.attributes.OlLayer!=node.attributes.OlLayer)||ba.attributes.type==this.NODE_GROUP))||(descending&&(bb!=null)&&((bb.attributes.type==this.NODE_LAYER&&bb.attributes.OlLayer!=node.attributes.OlLayer)||bb.attributes.type==this.NODE_GROUP)))){var indexSLn=node.attributes.OlLayer.getSubLayerInfo(node.attributes.layerName).index;var newLayers=node.attributes.OlLayer.split(indexSLn);this.linkLayerToNode(newLayers[1],newParent);var indexLn=this.map.getLayerIndex(node.attributes.OlLayer);this.map.addLayer(newLayers[1],indexLn);newLayers[0].redraw();newLayers[1].setVisibility(true);}
if(bb!=null){var Lpos_bb=bb.attributes.layerIdx;if(bb.attributes.type==this.NODE_LAYER){if(bb.attributes.OlLayer==node.attributes.OlLayer){var indexSLbb=bb.attributes.OlLayer.getSubLayerInfo(bb.attributes.layerName).index;indexSLn=descending?indexSLbb:indexSLbb+1;node.attributes.OlLayer.moveSubLayer(node.attributes.layerName,indexSLn);}
else{if(ba!=null){if(ba.attributes.type==this.NODE_LAYER){if(ba.attributes.OlLayer==bb.attributes.OlLayer){var indexSLba=ba.attributes.OlLayer.getSubLayerInfo(ba.attributes.layerName).index;var newLayers=ba.attributes.OlLayer.split(indexSLba-1);this.linkLayerToNode(newLayers[1],newParent);var indexLbb=this.map.getLayerIndex(bb.attributes.OlLayer);this.map.addLayer(newLayers[1],indexLbb);newLayers[0].redraw();newLayers[1].setVisibility(true);var indexLbb=this.map.getLayerIndex(bb.attributes.OlLayer);var indexLn=descending?indexLbb:indexLbb-1;this.map.setLayerIndex(node.attributes.OlLayer,indexLn);}
else{if(ba.attributes.OlLayer==node.attributes.OlLayer){var indexSLba=ba.attributes.OlLayer.getSubLayerInfo(ba.attributes.layerName).index;var indexSLn=descending?indexSLba-1:indexSLba;node.attributes.OlLayer.moveSubLayer(node.attributes.layerName,indexSLn);}
else{var indexLbb=this.map.getLayerIndex(bb.attributes.OlLayer);var indexLn=descending?indexLbb:indexLbb-1;this.map.setLayerIndex(node.attributes.OlLayer,indexLn);}}}
else{var indexLbb=this.map.getLayerIndex(bb.attributes.OlLayer);var indexLn=descending?indexLbb:indexLbb-1;this.map.setLayerIndex(node.attributes.OlLayer,indexLn);}}
else{var indexLbb=this.map.getLayerIndex(bb.attributes.OlLayer);var indexLn=descending?indexLbb:indexLbb-1;this.map.setLayerIndex(node.attributes.OlLayer,indexLn);}}}
else{if(ba!=null){if(ba.attributes.type==this.NODE_LAYER){if(ba.attributes.OlLayer==node.attributes.OlLayer){var indexSLba=ba.attributes.OlLayer.getSubLayerInfo(ba.attributes.layerName).index;var indexSLn=descending?indexSLba-1:indexSLba;node.attributes.OlLayer.moveSubLayer(node.attributes.layerName,indexSLn);}
else{var indexLba=this.map.getLayerIndex(ba.attributes.OlLayer);var indexLn=descending?indexLba+1:indexLba;this.map.setLayerIndex(node.attributes.OlLayer,indexLn);}}
else{var indexLbb=this.map.getLayerIndex(this.getLastLayerFromGroupNode(bb));var indexLn=descending?indexLbb:indexLbb-1;this.map.setLayerIndex(node.attributes.OlLayer,indexLn);}}
else{var indexSLbb=this.map.getLayerIndex(this.getLastLayerFromGroupNode(bb));var indexLn=descending?indexLbb:indexLbb-1;this.map.setLayerIndex(node.attributes.OlLayer,indexLn);}}}
else{if(ba!=null){if(ba.attributes.type==this.NODE_LAYER){if(ba.attributes.OlLayer==node.attributes.OlLayer){var indexSLba=ba.attributes.OlLayer.getSubLayerInfo(ba.attributes.layerName).index;node.attributes.OlLayer.moveSubLayer(node.attributes.layerName,indexSLba);}
else{var indexLba=this.map.getLayerIndex(ba.attributes.OlLayer);var indexLn=descending?indexLba+1:indexLba;this.map.setLayerIndex(node.attributes.OlLayer,indexLn);}}
else{var indexLba=this.map.getLayerIndex(this.getFirstLayerFromGroupNode(ba));var indexLn=descending?indexLba+1:indexLba;this.map.setLayerIndex(node.attributes.OlLayer,indexLn);}}
else{}}
if(bb!=null&&bb.attributes.type==this.NODE_LAYER&&bb.attributes.OlLayer==node.attributes.OlLayer&&bb.attributes.layerIdx<node.attributes.layerIdx){var indexSLbb=bb.attributes.OlLayer.getSubLayerInfo(bb.attributes.layerName).index;var newLayers=node.attributes.OlLayer.split(indexSLbb);this.linkLayerToNode(newLayers[1],newParent);var indexLb=this.map.getLayerIndex(bb.attributes.OlLayer);this.map.addLayer(newLayers[1],indexLb);newLayers[0].redraw();newLayers[1].setVisibility(true);}
if(ba!=null&&ba.attributes.type==this.NODE_LAYER&&ba.attributes.OlLayer==node.attributes.OlLayer&&ba.attributes.layerIdx>node.attributes.layerIdx){var indexSLba=ba.attributes.OlLayer.getSubLayerInfo(node.attributes.layerName).index;var newLayers=ba.attributes.OlLayer.split(indexSLba);this.linkLayerToNode(newLayers[1],newParent);var indexLba=this.map.getLayerIndex(node.attributes.OlLayer);this.map.addLayer(newLayers[1],indexLba);newLayers[0].redraw();newLayers[1].setVisibility(true);}
newParent.updateIndex(true);},serializeForContext:function(){this.updateNodeOpacityValues();var res={LayerTree:{LayerTreeNode:this.serializeNodeForContext(this.layerTree)}};return res;},serializeNodeForContext:function(node){var layerTreeNode={};switch(node.attributes.type){case(this.NODE_GROUP):layerTreeNode.attributes={name:node.attributes.text,open:Carmen.Util.bool2IntStr(node.isExpanded()),depth:node.getDepth().toString(),type:"group",opacity:node.attributes.opacity.toString(),forceOpacityControl:node.attributes.forceOpacityControl?"1":"0"};var subNodes=[];for(var i=0;i<node.childNodes.length;i++){child=node.childNodes[i];subNodes.push(this.serializeNodeForContext(child));}
if(subNodes.length>0)
layerTreeNode.LayerTreeNode=subNodes;break;case(this.NODE_LAYER):layerTreeNode.attributes={name:node.attributes.text,mapName:node.attributes.layerName,depth:node.getDepth().toString(),type:'layer',visible:Carmen.Util.bool2IntStr(node.attributes.visible),displayClass:Carmen.Util.bool2IntStr(node.hasChildNodes()),providerGrpId:(this.map.getNumLayers()-this.map.getLayerIndex(node.attributes.OlLayer)).toString(),layerId:node.attributes.layerIdx.toString(),layerIdx:node.attributes.layerIdx.toString(),opacity:node.attributes.opacity.toString(),forceOpacityControl:node.attributes.forceOpacityControl?"1":"0"};break;default:break;};return layerTreeNode;}});Carmen.Control.LayerTreeManager.TreeDropZone=Ext.extend(Ext.tree.TreeDropZone,{isValidDropPoint:function(n,pt,dd,e,data){var result=Ext.tree.TreeDropZone.prototype.isValidDropPoint.apply(this,arguments);if(result){var indexSrc=data.node.parentNode.indexOf(data.node);var indexTarget=n.node.parentNode.indexOf(n.node);var result=(n.node.parentNode==data.node.parentNode)&&((pt=='above'&&(indexTarget-indexSrc)!=1)||(pt=='below'&&(indexTarget-indexSrc)!=-1));}
return result;}});Carmen.Control.LayerTreeManager.addTransparencySliderToNode=function(node,initialOpacity){var transparencySlider=new Ext.Slider({id:node.id+'_slider',renderTo:node.id+'_ext',width:75,minValue:0,maxValue:100,plugins:new Ext.ux.SliderTip()});transparencySlider.on('change',function(slider,newVal){var opacity=1.0-(newVal/100);var olLayers=Carmen.Util.set_from_array(this.collect('OlLayer',false));for(var i=0;i<olLayers.length;i++){olLayers[i].setOpacity(opacity);}
var layerOrClassNodes=this.collectChildNodes(function(n){return('type'in n.attributes&&(n.attributes.type==Carmen.Control.LayerTreeManager.NODE_LAYER||n.attributes.type==Carmen.Control.LayerTreeManager.NODE_CLASS));});var sliderNodes=this.collectChildNodes(function(n){return n.attributes.forceOpacityControl;});for(var i=0;i<layerOrClassNodes.length;i++){var icon=layerOrClassNodes[i].getUI().getIconEl();OpenLayers.Util.modifyDOMElement(icon,null,null,null,null,null,null,opacity);}
for(var i=0;i<sliderNodes.length;i++){var gSlider=Ext.getCmp(sliderNodes[i].id+'_slider');gSlider.setValue(newVal,true);}},node);if(initialOpacity){var val=100-(initialOpacity*100);transparencySlider.setValue(val,true);}};Carmen.Control.LayerTreeManager.NODE_LAYER=0;Carmen.Control.LayerTreeManager.NODE_GROUP=1;Carmen.Control.LayerTreeManager.NODE_CLASS=2;Carmen.Control.LayerTreeManager.NODE_FEATURE=3;Carmen.Control.LayerTreeManager.TREE_NODE_ROOT_LABEL="Tous les thèmes";Proj4js.defs["EPSG:27584"]="+proj=lcc +lat_1=42.16500000000001 +lat_0=42.16500000000001 +lon_0=0 +k_0=0.99994471 +x_0=234.358 +y_0=4185861.369 +a=6378249.2 +b=6356515 +towgs84=-168,-60,320,0,0,0,0 +pm=paris +units=m +no_defs";Proj4js.defs["EPSG:32631"]="+proj=utm +zone=31 +ellps=WGS84 +datum=WGS84 +units=m +no_defs";OpenLayers.Control.AttributionCarmen=new OpenLayers.Class(OpenLayers.Control,{separator:", ",displayLogo:true,logoPath:null,font:null,fontFamily:'tahoma,arial,helvetica,sans-serif',color:'#000000',fontSize:'12px',fontWeight:'normal',fontStyle:'normal',backgroundColor:null,opacity:1.0,initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,arguments);this.fontFamily=this.font?this.font+','+this.fontFamily:this.fontFamily;if(this.fontSize&&this.fontSize.search(/^\d+$/g)!=-1)
this.fontSize=this.fontSize+'px';if(this.color&&this.color.charAt(0)!='#')
this.color='#'+this.color;if(this.backgroundColor&&this.backgroundColor.charAt(0)!='#')
this.backgroundColor='#'+this.backgroundColor;if(this.backgroundColor&&this.backgroundColor.length==9){this.opacity=1.0-(parseInt(this.backgroundColor.substring(7,9),16)/255);this.backgroundColor=this.backgroundColor.substring(0,7);}},destroy:function(){this.map.events.un({"removelayer":this.updateAttribution,"addlayer":this.updateAttribution,"changelayer":this.updateAttribution,"changebaselayer":this.updateAttribution,scope:this});Carmen.Control.Inlay.prototype.destroy.apply(this,arguments);},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);this.div.style.display="block";this.div.style.position="absolute";this.div.style.backgroundColor=this.backgroundColor;this.div.style.fontFamily=this.fontFamily;this.div.style.fontWeight=this.fontWeight;this.div.style.color=this.color;this.div.style.fontSize=this.fontSize;this.div.style.fontStyle=this.fontStyle;this.div.style.textAlign='center';OpenLayers.Util.modifyDOMElement(this.div,null,null,null,null,null,null,this.opacity);if(!this.logo&&this.displayLogo&&this.logoPath){this.logo=document.createElement("img");this.logo.style.verticalAlign='top';this.logo.src=this.logoPath;this.div.appendChild(this.logo);}
if(!this.txt){this.txt=document.createElement("span");this.txt.style.verticalAlign='bottom';this.txt.style.marginRight='10px';this.txt.style.display='block';this.div.appendChild(this.txt);}
this.map.events.on({'changebaselayer':this.update,'changelayer':this.update,'addlayer':this.update,'removelayer':this.update,scope:this});this.update();return this.div;},update:function(){var attributions=[];if(this.map&&this.map.layers){for(var i=0,len=this.map.layers.length;i<len;i++){var layer=this.map.layers[i];if(layer.attribution&&layer.getVisibility()){attributions.push(layer.attribution);}}
this.txt.innerHTML=attributions.join(this.separator);}},CLASS_NAME:"OpenLayers.Control.AttributionCarmen"});Carmen.Control.ReferenceMap=new OpenLayers.Class(OpenLayers.Control.OverviewMap,{referencePanel:new Ext.Panel({title:'Situation',collapsible:true,margins:'5 0 5 5',fitToFrame:true,autoHeight:true,listeners:{collapse:function(p){p.ownerCt.doLayout();},expand:function(p){p.ownerCt.doLayout();}}}),initialize:function(layerRef,options){OpenLayers.Control.OverviewMap.prototype.initialize.apply(this,[options]);this.displayClass=this.CLASS_NAME.replace("Carmen.","cmn").replace(/\./g,"");},setMap:function(map){this.map=map;var navPanel=this.map.app.ui.getNavigationPanel();navPanel.add(this.referencePanel);this.map.app.ui.doLayout();this.div=this.referencePanel.body.dom;this.outsideViewport=true;OpenLayers.Control.OverviewMap.prototype.setMap.apply(this,arguments);},draw:function(){OpenLayers.Control.OverviewMap.prototype.draw.apply(this,arguments);var h=Math.min(this.size.h+10,140);this.mapDiv.style.height=h.toString()+'px';var eltMapDiv=Ext.get(this.mapDiv);eltMapDiv.replaceClass('olMap','cmnControlOverviewMap');return this.div;},update:function(){OpenLayers.Control.OverviewMap.prototype.update.apply(this,arguments);var eltMapDiv=Ext.get(this.mapDiv);eltMapDiv.replaceClass('olMap','cmnControlOverviewMap');},CLASS_NAME:"Carmen.Control.OverviewMap"});Carmen.Control.Annotation=new OpenLayers.Class(OpenLayers.Control,{vectorLayer:null,controls:{},btns:{},displayConfig:['point','polyline','polygon','move','modify','style'],currentStyle:0,panel:new Ext.Panel({border:false,hideBorders:true,margins:'5 5 5 5',floating:true,autoHeight:true,autoWidth:true,hidden:true,x:5,y:5,xtype:'panel'}),panelBtn:new Ext.Toolbar.Button({tooltip:'Ajouter une annotation',tooltipType:'title',cls:'x-btn-icon cmn-tool-annotate',enableToggle:true,toggleGroup:'mainMapControl'}),colorPanel:new Ext.Panel({border:true,margins:'5 5 5 5',floating:true,autoHeight:true,autoWidth:true,hidden:true,x:35,y:5,xtype:'panel',items:[{id:'annot_colorPalette',fieldLabel:"Couleur des annotations",value:'993300',xtype:'colorpalette'}]}),initialize:function(contextInit,options){OpenLayers.Control.prototype.initialize.apply(this,arguments);OpenLayers.Feature.Vector.style['default']['strokeWidth']='2';this.vectorLayer=new OpenLayers.Layer.Vector("Vector Layer",{alwaysOnTop:true});this.controls['point']=new OpenLayers.Control.DrawFeature(this.vectorLayer,OpenLayers.Handler.Point);this.controls['polyline']=new OpenLayers.Control.DrawFeature(this.vectorLayer,OpenLayers.Handler.Path);this.controls['polygon']=new OpenLayers.Control.DrawFeature(this.vectorLayer,OpenLayers.Handler.Polygon);var modifyFeatureControl=new OpenLayers.Control.ModifyFeature(this.vectorLayer,{handleKeypress:function(evt){var code=evt.keyCode;if(this.feature&&OpenLayers.Util.indexOf(this.deleteCodes,code)!=-1){var vertex=this.dragControl.feature;if(vertex&&OpenLayers.Util.indexOf(this.vertices,vertex)!=-1&&!this.dragControl.handlers.drag.dragging&&vertex.geometry.parent){vertex.geometry.parent.removeComponent(vertex.geometry);this.layer.drawFeature(this.feature,this.selectControl.renderIntent);this.resetVertices();this.onModification(this.feature);this.layer.events.triggerEvent("featuremodified",{feature:this.feature});}
else if(this.mode==OpenLayers.Control.ModifyFeature.RESHAPE||this.mode==OpenLayers.Control.ModifyFeature.DRAG){this.layer.removeFeatures(this.feature);this.feature=null;this.resetVertices();}}}});this.controls['move']=modifyFeatureControl;this.controls['modify']=modifyFeatureControl;this.controls['style']=new OpenLayers.Control();this.btns['point']=Carmen.Control.Annotation.buildBtn('point','/IHM/images/Annotate_point_OFF.gif','Dessin de point');this.btns['polyline']=Carmen.Control.Annotation.buildBtn('polyline','/IHM/images/Annotate_polyline_OFF.gif','Dessin de polylignes');this.btns['polygon']=Carmen.Control.Annotation.buildBtn('polygon','/IHM/images/Annotate_polygon_OFF.gif','Dessin de polygones');this.btns['modify']=Carmen.Control.Annotation.buildBtn('modify','/IHM/images/Annotate_modify_OFF.gif','Modification d\'annotations');this.btns['move']=Carmen.Control.Annotation.buildBtn('move','/IHM/images/Annotate_move_OFF.gif','Déplacement d\'annotations');this.btns['style']=Carmen.Control.Annotation.buildBtn('style','/IHM/images/Annotate_style_OFF.gif','Modifier le style des annotations');if(contextInit!=null)
this.initFromContext(contextInit);},activate:function(){var state=OpenLayers.Control.prototype.activate.apply(this,arguments);if(state){this.panel.show();this.panel.setPosition(5,5);if(this.map)
this.map.toolTipDeactivate();}
return state;},deactivate:function(){var state=OpenLayers.Control.prototype.deactivate.apply(this,arguments);if(state){for(var i=0;i<this.displayConfig.length;i++){var key=this.displayConfig[i];this.btns[key].toggle(false);}
this.panel.hide();if(this.map)
this.map.toolTipActivate();}
return state;},exportFeatures:function(){var KMLattributes=new OpenLayers.Class(OpenLayers.Format.KML,{createPlacemarkXML:function(feature){var placemarkNode=OpenLayers.Format.KML.prototype.createPlacemarkXML.apply(this,arguments);for(var att in feature.attributes){if(att!='name'&&att!='description'){value=att;var attDesc=this.createElementNS(this.kmlns,att);attDesc.appendChild(this.createTextNode(feature.attributes[att]));placemarkNode.appendChild(attDesc);}}
return placemarkNode;}});var out_options={'internalProjection':new OpenLayers.Projection(mapProjection),'externalProjection':new OpenLayers.Projection(mapProjection)};var kml=new KMLattributes(out_options);var strPolygonKml="";var strLineStringKml="";var strPointKml="";tabFeaturesPolygon=new Array();tabFeaturesLineString=new Array();tabFeaturesPoint=new Array();for(var i=0;i<this.vectorLayer.features.length;i++){switch(this.vectorLayer.features[i].geometry.CLASS_NAME){case"OpenLayers.Geometry.Polygon":tabFeaturesPolygon.push(this.vectorLayer.features[i]);break;case"OpenLayers.Geometry.LineString":tabFeaturesLineString.push(this.vectorLayer.features[i]);break;case"OpenLayers.Geometry.Point":tabFeaturesPoint.push(this.vectorLayer.features[i]);break;}}
if(tabFeaturesPolygon.length>0)
strPolygonKml=kml.write(tabFeaturesPolygon);if(tabFeaturesLineString.length>0)
strLineStringKml=kml.write(tabFeaturesLineString);if(tabFeaturesPoint.length>0)
strPointKml=kml.write(tabFeaturesPoint);var annotationStyle=this._serializeStyleMap(this.vectorLayer.styleMap);return(new Array(strPolygonKml,strLineStringKml,strPointKml,annotationStyle));},setMap:function(map){OpenLayers.Control.prototype.setMap.apply(this,arguments);this.map.addLayer(this.vectorLayer);var mainPanel=this.map.app.ui.getMainPanel();var ui=this.map.app.ui;mainPanel.add(this.panel);this.panel.setPosition(5,5);mainPanel.add(this.colorPanel);this.colorPanel.setPosition(25,5);this.panelBtn.addListener('toggle',Carmen.Util.buildExt2olHandlerToggle(this));var tb=this.map.app.ui.getTopToolBar();tb.addItem(this.panelBtn);ui.doLayout();for(var i=0;i<this.displayConfig.length;i++){var key=this.displayConfig[i];this.panel.add(this.btns[key]);this.panel.doLayout();}
for(var i=0;i<this.displayConfig.length;i++){var key=this.displayConfig[i];this.btns[key].olControl=this.controls[key];this.btns[key].getEl().on('mousedown',function(evt){evt.stopEvent();},this.btns[key]);this.btns[key].defaultHandler=Carmen.Util.buildExt2olHandlerToggle(this.controls[key]);switch(key){case'modify':this.btns[key].addListener('toggle',function(extBtn,state){extBtn.olControl.mode=OpenLayers.Control.ModifyFeature.RESHAPE;extBtn.defaultHandler(extBtn,state);});break;case'move':this.btns[key].addListener('toggle',function(extBtn,state){extBtn.olControl.mode=OpenLayers.Control.ModifyFeature.DRAG;extBtn.defaultHandler(extBtn,state);});break
case'style':this.btns[key].colorPanel=this.colorPanel;this.btns[key].addListener('toggle',function(extBtn,state){extBtn.colorPanel.setVisible(state);extBtn.colorPanel.setPosition(extBtn.colorPanel.initialConfig.x,extBtn.colorPanel.initialConfig.y);});palet=this.colorPanel.getComponent('annot_colorPalette');palet.layer=this.vectorLayer;palet.addListener('select',this.changeDrawingColor,this);break
default:this.btns[key].addListener('toggle',this.btns[key].defaultHandler);}
this.map.addControl(this.controls[key]);}
this.vectorLayer.styleMap.styles['default'].addRules(new OpenLayers.Rule({elseFilter:true}));this.vectorLayer.styleMap.addUniqueValueRules('default','description',{0:OpenLayers.Util.extend({},OpenLayers.Feature.Vector.style['default'])});this.vectorLayer.styleMap.styles['default'].defaultStyle=OpenLayers.Util.extend({},OpenLayers.Feature.Vector.style['default']);this.vectorLayer.events.register('featureadded',this,this.updateFeatureStyle);},updateFeatureStyle:function(evt){var feature=evt.feature;feature.attributes['description']=this.currentStyle;feature.layer.redraw();},changeDrawingColor:function(palette,selColor){this.currentStyle++;var styleConfig=OpenLayers.Util.extend({},OpenLayers.Feature.Vector.style['default']);styleConfig.fillColor='#'+selColor;styleConfig.strokeColor='#'+selColor;var symboliser={};symboliser[this.currentStyle]=styleConfig;this.vectorLayer.styleMap.addUniqueValueRules('default','description',symboliser);OpenLayers.Feature.Vector.style['default'].fillColor='#'+selColor;OpenLayers.Feature.Vector.style['default'].strokeColor='#'+selColor;},serializeForContext:function(){var out_options={'internalProjection':new OpenLayers.Projection(mapProjection),'externalProjection':new OpenLayers.Projection(mapProjection)};var KMLattributes=new OpenLayers.Class(OpenLayers.Format.KML,{createPlacemarkXML:function(feature){var placemarkNode=OpenLayers.Format.KML.prototype.createPlacemarkXML.apply(this,arguments);for(var att in feature.attributes){if(att!='name'&&att!='description'){value=att;var attDesc=this.createElementNS(this.kmlns,att);attDesc.appendChild(this.createTextNode(feature.attributes[att]));placemarkNode.appendChild(attDesc);}}
return placemarkNode;}});var kml=new KMLattributes(out_options)
var strKml=kml.write(this.vectorLayer.features);var annotationStyle=this._serializeStyleMap(this.vectorLayer.styleMap);return{Annotation:{data:{"#text":strKml},style:annotationStyle}};},_serializeStyleMap:function(){var stl=this.vectorLayer.styleMap.styles['default'];var attMap=[];var elseSymbolizer={};var filterProperty='';for(var i=0;i<stl.rules.length;i++){var r=stl.rules[i];if(r.elseFilter)
elseSymbolizer={color:stl.defaultStyle.fillColor};else{attMap[r.filter.value]={color:r.symbolizer.fillColor};filterProperty=r.filter.property;}};var serializeMap={defaultStyle:{color:stl.defaultStyle.fillColor},filterRules:{elseSymbolizer:elseSymbolizer,filterProperty:filterProperty,map:attMap}};return serializeMap},_initStyleMap:function(serializedMap){var symboliser={};var attMap=serializedMap.filterRules.map;for(var k in attMap){var styleConfig=OpenLayers.Util.extend({},this.vectorLayer.styleMap.styles['default']);styleConfig.fillColor=attMap[k].color;styleConfig.strokeColor=attMap[k].color;symboliser[k]=styleConfig;}
this.vectorLayer.styleMap.styles['default'].addRules(new OpenLayers.Rule({elseFilter:true}));var stl=OpenLayers.Util.extend({},this.vectorLayer.styleMap.styles['default'].defaultStyle);stl.fillColor=serializedMap.defaultStyle.color;stl.strokeColor=serializedMap.defaultStyle.color;this.vectorLayer.styleMap.styles['default'].defaultStyle=stl;this.vectorLayer.styleMap.styles['default'].rules=[];this.vectorLayer.styleMap.addUniqueValueRules('default',serializedMap.filterRules.filterProperty,symboliser);},initFromContext:function(annotationConfig){var kml=new OpenLayers.Format.KML({extractStyles:true,extractAttributes:true});this.vectorLayer.removeFeatures(this.vectorLayer.features);var data=annotationConfig.data;if(!('attributes'in data.kml)){data.kml.attributes={}
data.kml.attributes.xmlns="http://earth.google.com/kml/2.0";}
var kmlStr=Carmen.Util.json2xml(data);this.vectorLayer.addFeatures(kml.read(kmlStr));this.vectorLayer.redraw();var smap=Ext.value(annotationConfig.style,null);if(smap)
this._initStyleMap(smap);},CLASS_NAME:"Carmen.Control.Annotation"});Carmen.Control.Annotation.buildBtn=function(suffix,iconPath,toolTip){var btn=new Ext.Button({tooltip:toolTip,tooltipType:'title',id:'annot_'+suffix,icon:iconPath,cls:'x-btn-icon',enableToggle:'true',toggleGroup:'annotationControl',xtype:'button'});return btn;};tabStoreProj=new Array();for(var i=0;i<tabEPSG.length;i++){data=new Array("EPSG:"+tabEPSG[i][0],tabEPSG[i][1]);tabStoreProj.push(data);}
Carmen.Control.Coordinate=new OpenLayers.Class(OpenLayers.Control.MousePosition,{coordinateSysBox:new Ext.form.ComboBox({typeAhead:true,mode:'local',triggerAction:'all',emptyText:'Sélectionnez un sytème de coordonnées',selectOnFocus:true,editable:false,width:240,valueField:'projName',displayField:'projPrettyName',store:new Ext.data.SimpleStore({fields:['projName','projPrettyName'],data:tabStoreProj})}),projName:'unknown',coordinateLabel:new Ext.form.Label({width:200,id:'coordLabel'}),initialize:function(options){options=OpenLayers.Util.extend(options,{prefix:" Position : ",separator:', '});OpenLayers.Control.MousePosition.prototype.initialize.apply(this,[options]);},setMap:function(map){this.map=map;var tb=this.map.app.ui.getBottomToolBar();var currentProjIdx=this.initializeCombo(this.map.projection);if(currentProjIdx!=-1){tb.addItem(this.coordinateSysBox);tb.addItem(new Ext.Toolbar.Spacer());this.map.app.ui.doLayout();this.coordinateSysBox.setValue(this.projName);this.displayProjection=new OpenLayers.Projection(this.projName);this.coordinateSysBox.on('select',this.comboSelect,this);}
else{Ext.Msg.alert("Projection inconnue","Le système de coordonnées de la carte n'est pas connu. "+"Les informations fournies par les outils de mesure et de lecture de "+"coordonnées ne sont pas garanties.");}
tb.addItem(this.coordinateLabel);this.div=this.coordinateLabel.getEl().dom;OpenLayers.Control.MousePosition.prototype.setMap.apply(this,arguments);},comboSelect:function(combo,rec,idx){var newProjName=combo.getValue();if(newProjName!=this.projName){this.projName=newProjName;this.displayProjection=new OpenLayers.Projection(this.projName);this.redraw();}},initializeCombo:function(strProj){var projName=strProj.toLocaleUpperCase();var projIndex=this.coordinateSysBox.getStore().find('projName',projName);this.projName=projIndex==-1?'unknown':projName;return projIndex;},formatOutput:function(lonLat){var isGeoProj=(this.displayProjection.getUnits()==null);var digits=isGeoProj?parseInt(this.numDigits):2;var newHtml=this.prefix+
lonLat.lon.toFixed(digits)+
this.separator+
lonLat.lat.toFixed(digits)+
this.suffix;return newHtml;},CLASS_NAME:"Carmen.Control.Coordinate"});Carmen.Control.Measure=new OpenLayers.Class(OpenLayers.Control,{LENGTH_BTN:1,AREA_BTN:2,BOTH_BTN:3,displayConfig:3,win:new Ext.Window({id:'measure'+'_'+'window',width:200,autoHeight:true,closeAction:'hide',plain:true,title:'',hidden:true}),sketchSymbolizers:{"Point":{pointRadius:4,graphicName:"square",fillColor:"white",fillOpacity:1,strokeWidth:1,strokeOpacity:1,strokeColor:"#333333"},"Line":{strokeWidth:3,strokeOpacity:1,strokeColor:"#666666",strokeDashstyle:"dash"},"Polygon":{strokeWidth:2,strokeOpacity:1,strokeColor:"#666666",fillColor:"white",fillOpacity:0.3}},msrLength:null,msrArea:null,btnLength:new Ext.Toolbar.Button({tooltip:'Mesure de distance',tooltipType:'title',cls:'x-btn-icon cmn-tool-mesure',enableToggle:true,toggleGroup:'mainMapControl'}),btnArea:new Ext.Toolbar.Button({tooltip:'Mesure de surface',tooltipType:'title',cls:'x-btn-icon cmn-tool-surface',enableToggle:true,toggleGroup:'mainMapControl'}),initialize:function(options){var style=new OpenLayers.Style();style.addRules([new OpenLayers.Rule({symbolizer:this.sketchSymbolizers})]);var styleMap=new OpenLayers.StyleMap({"default":style});msrOptions={handlerOptions:{style:"default",layerOptions:{styleMap:styleMap},persist:true}};OpenLayers.Control.prototype.initialize.apply(this,arguments);this.msrLength=new OpenLayers.Control.Measure(OpenLayers.Handler.Path,msrOptions);this.msrArea=new OpenLayers.Control.Measure(OpenLayers.Handler.Polygon,msrOptions);},setMap:function(map){OpenLayers.Control.prototype.setMap.apply(this,arguments);OpenLayers.Control.Measure.prototype.setMap.apply(this.msrArea,arguments);OpenLayers.Control.Measure.prototype.setMap.apply(this.msrLength,arguments);var control=this;var tb=this.map.app.ui.getTopToolBar();if((this.displayConfig&this.LENGTH_BTN)>0){tb.addItem(this.btnLength);this.btnLength.addListener('toggle',Carmen.Util.buildExt2olHandlerToggle(this.msrLength));this.msrLength.events.on({"measure":control.measureHandler,"measurepartial":control.measureHandler,"deactivate":function(evt){control.win.hide();},scope:control});}
if((this.displayConfig&this.AREA_BTN)>0){tb.addItem(this.btnArea);this.btnArea.addListener('toggle',Carmen.Util.buildExt2olHandlerToggle(this.msrArea));this.msrArea.events.on({"measurepartial":control.measureHandler,"measure":control.measureHandler,"deactivate":function(evt){control.win.hide();},scope:control});}
var mainPanelXY=this.map.app.ui.getMainPanel().getPosition();this.win.setPagePosition(mainPanelXY[0]+10,mainPanelXY[1]+35);this.win.show();this.win.hide();this.map.app.ui.doLayout();},measureFormatter:function(n){return(new Number(n)).toString();},measureHandler:function(event){var geometry=event.geometry;var units=event.units;var order=event.order;var measure=event.measure;var out="";var status="";if(order==1){status="Mesure de distance";out+="<b>&nbsp;Distance:&nbsp;"+this.measureFormatter(measure.toFixed(3))+"&nbsp;"+units+"</b>";}
else{var a=this.map.getControlsByClass('Carmen.Control.Measure');var ctrl=a[0].msrArea;var length_m=ctrl.getLength(event.geometry,'m');var area_m2=ctrl.getArea(event.geometry,'m');out+='<table height="auto" width="200" style="text-align: right; margin-right: 0px; '+'height: 200px; width: 200px; overflow: auto;" '+'border="0" cellpadding="1" cellspacing="1">';out+='<tbody>';out+='<tr>';out+='<td colspan="2" rowspan="1" style="width: 50px;text-align: left;">'+'P&eacute;rim&egrave;tre</td>';out+='</tr>';out+='<tr style="vertical-align:baseline;"><td style="width: 150px;"><b>'+this.measureFormatter(length_m.toFixed())+'</b></td>'+'<td style="text-align: left;"><b>&nbsp;&nbsp;m</b></td>';out+='<tr style="vertical-align:baseline;"><td style="width: 150px;"><b>'+this.measureFormatter((length_m/100.0).toFixed(2))+'</b></td>'+'<td style="text-align: left;"><b>&nbsp;&nbsp;hm</b></td>';out+='<tr style="vertical-align:baseline;"><td style="width: 150px;"><b>'+this.measureFormatter((length_m/1000.0).toFixed(3))+'</b></td>'+'<td style="text-align: left;"><b>&nbsp;&nbsp;km</b></td>';out+='<tr>';out+='<td colspan="2" rowspan="1" style="width: 50px;text-align: left;">'+'Surface</td>';out+='</tr>';out+='<tr style="vertical-align:baseline;"><td style="width: 150px;"><b>'+this.measureFormatter(area_m2.toFixed())+'</b></td>'+'<td style="text-align: left;"><b>&nbsp;&nbsp;m²</b></td>';out+='<tr style="vertical-align:baseline;"><td style="width: 150px;"><b>'+this.measureFormatter((area_m2/10000.0).toFixed(2))+'</b></td>'+'<td style="text-align: left;"><b>&nbsp;&nbsp;ha </b></td>';out+='<tr style="vertical-align:baseline;"><td style="width: 150px;"><b>'+this.measureFormatter((area_m2/1000000.0).toFixed(3))+'</b></td>'+'<td style="text-align: left;"><b>&nbsp;&nbsp;km²</b></td>';out+='</tbody>';out+='</table>';status="Mesure";}
this.win.setTitle(status);this.win.body.dom.innerHTML=out;this.win.show();},CLASS_NAME:"Carmen.Control.Measure"});Carmen.Control.Measure.LENGTH_BTN=1;Carmen.Control.Measure.AREA_BTN=2;Carmen.Control.Measure.BOTH_BTN=3;Carmen.Control.ToolTip=new OpenLayers.Class(OpenLayers.Control,{toolTipPanel:new Ext.form.FormPanel({id:'cmnToolTipPanel',border:true,margins:'5 5 5 5',frame:true,layout:'form',floating:true,hidden:true}),timer:null,mapfile:null,serviceUrl:null,windowTitle:"Outil Infobulle",showGraphicalSelection:false,element:null,prefix:'',separator:', ',suffix:'',numDigits:5,granularity:10,lastXy:null,displayProjection:null,onMap:false,initialize:function(serviceUrl,mapfile,options){OpenLayers.Control.prototype.initialize.apply(this,arguments);this.mapfile=mapfile;this.serviceurl=serviceUrl;},destroy:function(){if(this.map){this.map.events.unregister('mousemove',this,this.redraw);}
OpenLayers.Control.prototype.destroy.apply(this,arguments);},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);if(!this.element){this.div.left="";this.div.top="";this.element=this.div;}
this.redraw();return this.div;},redraw:function(evt){this.toolTipPanel.hide();if(evt!=null){var control=this;if(this.timer)
clearTimeout(this.timer);this.timer=setTimeout(function(){if(control.onMap)
control.updateToolTip(evt.xy)},Carmen.Control.ToolTip.DELAY);}},updateToolTip:function(pos){this.toolTipPanel.setPosition(pos.x,pos.y);this.layerTree=this.map.getLayerTreeManager().getLayerTree().clone();this.layerTree.filter(this.filterToolTipNode);var isLayerNode=function(n){return('type'in n.attributes&&(n.attributes.type==Carmen.Control.LayerTreeManager.NODE_LAYER));};var nodes=this.layerTree.collectChildNodes(isLayerNode);var queryParams=this.buildParams(nodes,pos);this.performQuery(queryParams,pos);},updateToolTipPanel:function(fields,data,pos){if(data.length==0||fields.length==0||!this.onMap)
return;var bdy=this.toolTipPanel.body.dom;bdy.innerHTML='';var panelWidth=250;if(this.map)
panelWidth=this.map.app.ui.getMainPanel().getSize().width;this.toolTipPanel.setWidth(panelWidth);var anchor=document.createElement('a');var linesMaxCount=10;var recordsCount=Math.max(1,Math.min(data.length,Math.floor(linesMaxCount/fields.length)));for(var i=0;i<recordsCount;i++){var list=document.createElement("ul");for(var j=0;j<fields.length-2;j++){var line=document.createElement("li");var span_field=document.createElement("span");span_field.style.fontWeight='bold';var span_data=document.createElement("span");span_data.className='cmnToolTipData';span_field.innerHTML=fields[j]+' : ';span_data.innerHTML=data[i][j];line.appendChild(span_field);line.appendChild(span_data);list.appendChild(line);}
bdy.appendChild(list);}
bdy.appendChild(anchor);this.toolTipPanel.render();lineWidth=0;for(var i=0;i<bdy.childNodes.length-1;i++){list=bdy.childNodes[i];for(var j=0;j<list.childNodes.length;j++){lineWidth=Math.max(lineWidth,Ext.fly(list.childNodes[j].childNodes[0]).getWidth()+Ext.fly(list.childNodes[j].childNodes[1]).getWidth());}}
var width=lineWidth+30;var height=Ext.fly(list).getHeight()*recordsCount+15;this.toolTipPanel.setWidth(width);this.toolTipPanel.setHeight(height);var mapPanel=this.map.app.ui.getMainPanel();var mousePosX=pos.x;var mousePosY=pos.y;var posX=(mousePosX-width)<0?mousePosX:mousePosX-width;var posY=(mousePosY-height)<0?mousePosY:mousePosY-height;posX=Math.max(posX,0);posY=Math.max(posY,0);var mapPanelHeight=mapPanel.getInnerHeight();var mapPanelWidth=mapPanel.getInnerWidth();var readjustH=height>(mapPanelHeight-posY);height=readjustH?mapPanelHeight-posY:height;var readjustW=width>(mapPanelWidth-posX);width=readjustW?mapPanelWidth-posX:width;this.toolTipPanel.setHeight(height);this.toolTipPanel.setWidth(width);this.toolTipPanel.setPosition(posX,posY);this.toolTipPanel.show();},fieldFilter_TXT:function(field){return field.type=='TXT';},buildParams:function(nodes,position,fieldsFilter){var layerNames=[];var fieldsList=[];var briefFieldsList=[];var baseQueryURLList=[];for(var i=0;i<nodes.length;i++){layerNames.push(nodes[i].attributes.layerName);fieldsList.push(nodes[i].attributes.toolTipFields);baseQueryURLList.push(nodes[i].attributes.baseQueryURL);}
var fieldsDesc=new Array();for(var i=0;i<fieldsList.length;i++){var list=Carmen.Util.chompAndSplit(fieldsList[i],';');fieldsDesc[i]=new Array();for(var j=0;j<list.length;j++){var desc=Carmen.Util.decodeCarmenFieldDesc(list[j],baseQueryURLList[i]);desc.type='TXT';fieldsDesc[i][j]=desc;}
if(fieldsFilter)
fieldsDesc[i]=Carmen.Util.array_filter(fieldsDesc[i],fieldsFilter);}
for(var i=0;i<nodes.length;i++){nodes[i].attributes.infoFieldsDesc=fieldsDesc[i];}
var params=layerNames.length>0?{layers:Ext.util.JSON.encode(layerNames),fields:Ext.util.JSON.encode(fieldsDesc),briefFields:Ext.util.JSON.encode(fieldsDesc),shape:Carmen.Util.positionToStr(this.positionToBounds(position)),map:this.mapfile,showGraphicalSelection:this.showGraphicalSelection,maxCountPerLayer:5}:null;return params;},performQuery:function(queryParams,position){var received=function(response){response=Ext.decode(response.responseText);var fields=[];var data=[];var lname='';for(l in response.results){fields=response.results[l].fields
data=response.results[l].data
lname=l;break;}
if(data.length>0){var node=this.control.layerTree.findChildByAttribute('layerName',lname);var alias=[].concat(fields);var infoFieldsDesc=node.attributes.infoFieldsDesc;for(var i=0;i<alias.length;i++){for(var j=0;j<infoFieldsDesc.length;j++){infoFieldsDesc[j]
if(infoFieldsDesc[j].name==alias[i])
alias[i]=infoFieldsDesc[j].alias;}}
this.control.updateToolTipPanel(alias,data,this.pos);}}
var url='/services/GetInformation/index.php';if(queryParams!=null)
{Ext.Ajax.request({url:url,success:received,failure:function(response){Carmen.Util.handleAjaxFailure(response,control.windowTitle,true);},params:queryParams,scope:{control:this,pos:position}});}},positionToBounds:function(position){var bounds=null;if(position instanceof OpenLayers.Bounds){var minXY=this.map.getLonLatFromPixel(new OpenLayers.Pixel(position.left,position.bottom));var maxXY=this.map.getLonLatFromPixel(new OpenLayers.Pixel(position.right,position.top));bounds=new OpenLayers.Bounds(minXY.lon,minXY.lat,maxXY.lon,maxXY.lat);}
else{var tol=Carmen.Util.INFO_TOOL_XY_TOLERANCE;var minXY=this.map.getLonLatFromPixel(new OpenLayers.Pixel(position.x-tol,position.y-tol));var maxXY=this.map.getLonLatFromPixel(new OpenLayers.Pixel(position.x+tol,position.y+tol));bounds=new OpenLayers.Bounds(minXY.lon,minXY.lat,maxXY.lon,maxXY.lat);}
return bounds;},formatOutput:function(lonLat){var digits=parseInt(this.numDigits);var newHtml=this.prefix+
lonLat.lon.toFixed(digits)+
this.separator+
lonLat.lat.toFixed(digits)+
this.suffix;return newHtml;},filterToolTipNode:function(node){var res=true;res=('type'in node.attributes)&&((node.attributes.type==Carmen.Control.LayerTreeManager.NODE_GROUP&&node.hasChildNodes()&&node.getDepth()>0)||(node.attributes.type==Carmen.Control.LayerTreeManager.NODE_LAYER&&node.attributes.OlLayer.getVisibility(node.attributes.layerName)&&(node.attributes.toolTipFields&&node.attributes.toolTipFields.length>0)));return res;},setMap:function(){OpenLayers.Control.prototype.setMap.apply(this,arguments);this.activate();var mainPanel=this.map.app.ui.getMainPanel();mainPanel.add(this.toolTipPanel);control=this;mainPanel.body.on('mouseout',function(){control.onMap=false;});mainPanel.body.on('mouseover',function(){control.onMap=true;});this.map.app.ui.doLayout();},activate:function(){var state=OpenLayers.Control.prototype.activate.apply(this,arguments);if(state){this.map.events.register('mousemove',this,this.redraw);}
return state;},deactivate:function(){var state=OpenLayers.Control.prototype.deactivate.apply(this,arguments);if(state){if(this.toolTipPanel.rendered)
this.toolTipPanel.hide();if(this.map)
this.map.events.unregister('mousemove',this,this.redraw);}
return state;},CLASS_NAME:"Carmen.Control.ToolTip"});Carmen.Control.ToolTip.DELAY=1000;Proj4js.defs["EPSG:27572"]="+proj=lcc +lat_1=46.8 +lat_0=46.8 +lon_0=0 +k_0=0.99987742 +x_0=600000 +y_0=2200000 +a=6378249.2 +b=6356515 +towgs84=-168,-60,320,0,0,0,0 +pm=paris +units=m +no_defs";Carmen.Control.ZoomHistory={};Carmen.Control.ZoomHistory=new OpenLayers.Class(OpenLayers.Control.NavigationHistory,{PREV_BTN:1,NEXT_BTN:2,BOTH_BTN:3,displayConfig:3,btnPrevious:new Ext.Toolbar.Button({tooltip:'Zoom Précédent',tooltipType:'title',cls:'x-btn-icon cmn-tool-zoomprev',enableToggle:false,disabled:true}),btnNext:new Ext.Toolbar.Button({tooltip:'Zoom Suivant',tooltipType:'title',icon:'/IHM/images/ZoomSuiv_OFF.gif',cls:'x-btn-icon',enableToggle:false,disabled:true}),initialize:function(options){OpenLayers.Control.NavigationHistory.prototype.initialize.apply(this,arguments);var btnP=this.btnPrevious;var olControlP=this.previous;this.previous=OpenLayers.Util.extend(olControlP,{activate:function(){OpenLayers.Control.prototype.activate.apply(this,arguments);btnP.setDisabled(!olControlP.active);}});var btnN=this.btnNext;var olControlN=this.next;this.next=OpenLayers.Util.extend(olControlN,{activate:function(){OpenLayers.Control.prototype.activate.apply(this,arguments);btnN.setDisabled(!olControlN.active);}});},setMap:function(map){OpenLayers.Control.NavigationHistory.prototype.setMap.apply(this,arguments);var tb=this.map.app.ui.getTopToolBar();if((this.displayConfig&this.PREV_BTN)>0){tb.addItem(this.btnPrevious);this.btnPrevious.addListener('click',Carmen.Util.buildExt2olHandlerButton(this.previous));}
if((this.displayConfig&this.NEXT_BTN)>0){tb.addItem(this.btnNext);this.btnNext.addListener('click',Carmen.Util.buildExt2olHandlerButton(this.next));}
this.map.app.ui.doLayout();},CLASS_NAME:"Carmen.Control.ZoomHistory"});Carmen.Control.ZoomHistory.PREV_BTN=1;Carmen.Control.ZoomHistory.NEXT_BTN=2;Carmen.Control.ZoomHistory.BOTH_BTN=3;Proj4js.defs["EPSG:3163"]="+proj=lcc +lat_1=-20.66666666666667 +lat_2=-22.33333333333333 +lat_0=-21.5 +lon_0=166 +x_0=400000 +y_0=300000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs";Carmen.Control.Info=new OpenLayers.Class(OpenLayers.Control,{btn:new Ext.Toolbar.Button({tooltip:'Information',tooltipType:'title',cls:'x-btn-icon cmn-tool-info',enableToggle:true,toggleGroup:'mainMapControl',disabled:false}),win:null,headerPanel:null,layerTreeInfoPanel:null,gridInfoPanel:null,type:OpenLayers.Control.TYPE_TOOL,layerTreeManager:null,layerTree:null,mapfile:null,serviceUrl:null,windowTitle:'Information',showGraphicalSelection:true,queriesSent:0,totalCount:0,fullExtent:null,WMSResponseFormats:{'text/plain':new OpenLayers.Format.Text(),'application/vnd.ogc.gml':new OpenLayers.Format.WMSGetFeatureInfo()},initialize:function(serviceUrl,mapfile,options){OpenLayers.Control.prototype.initialize.apply(this,arguments);this.mapfile=mapfile;this.serviceurl=serviceUrl;this.initializeUIComponents();},initializeUIComponents:function(){this.win=new Ext.Window({id:this.displayClass+'_'+'window',layout:'anchor',width:400,height:400,plain:true,title:'',modal:false,autoDestroy:true,resizable:true,closeAction:'hide',shadow:false});this.headerPanel=new Ext.Panel({id:this.displayClass+'_'+'headerPanel',autoScroll:true,fitToFrame:true,iconCls:'cmnInfoGridZoomIcon',header:true,title:'Interrogation des couches...',anchor:'100% 50%'});this.layerTreeInfoPanel=new Ext.tree.TreePanel({id:this.displayClass+'_'+'layerTreeInfoPanel',margins:'5 0 5 5',useArrows:false,animate:false,border:false,fitToFrame:true,rootVisible:false,root:{text:'root'},viewConfig:{autoFill:true,forceFit:false}});this.gridInfoPanel=new Ext.grid.GridPanel({id:this.displayClass+'_'+'gridInfoPanel',store:new Ext.data.SimpleStore({fields:[],data:[]}),columns:[],title:'Résultats sélectionnés',hidden:true,autoScroll:true,collapsible:true,border:false,anchor:'100% 50%'});},setMap:function(map){OpenLayers.Control.prototype.setMap.apply(this,arguments);this.btn.addListener('toggle',Carmen.Util.buildExt2olHandlerToggle(this));var tb=this.map.app.ui.getTopToolBar();tb.addItem(this.btn);this.map.app.ui.doLayout();},draw:function(){this.handler=new OpenLayers.Handler.Box(this,{done:this.info},{keyMask:this.keyMask});},activate:function(){if(this.getLayerTreeManager==null){Ext.MessageBox.alert("Warning","The control "+
this.CLASS_NAME+" requires the LayerTreeManager control to work.");return null;}
OpenLayers.Control.prototype.activate.apply(this,arguments);this.map.toolTipDeactivate();},deactivate:function(){this.map.clearSelection();OpenLayers.Control.prototype.deactivate.apply(this,arguments);if(this.win.rendered)
this.win.hide();this.map.toolTipActivate();},info:function(position){this.showInfoWindow(position);},showInfoWindow:function(position){this.layerTree=this.getLayerTreeManager().getLayerTree().clone(this.transformNodeInfo);if(!this.win.rendered){this.headerPanel.add(this.layerTreeInfoPanel);this.win.add(this.headerPanel);this.layerTreeInfoPanel.setRootNode(this.layerTree);this.win.add(this.gridInfoPanel);this.win.setTitle(this.windowTitle);this.win.doLayout();this.win.show();}
else{this.gridInfoPanel.hide();this.layerTreeInfoPanel.getRootNode().destroy();this.layerTreeInfoPanel.setRootNode(this.layerTree);this.layerTreeInfoPanel.getRootNode().render();}
if(!this.win.isVisible()){this.win.show();}
this.headerPanel.setTitle('Interrogation des couches...');if(this.showGraphicalSelection)
this.map.clearSelection();this.performQueries(position);},getLayerTreeManager:function(){if(this.layertreeManager==null){var controls=this.map.getControlsByClass('Carmen.Control.LayerTreeManager');this.layerTreeManager=controls.length==0?null:controls[0];}
return this.layerTreeManager;},performQueries:function(position){var control=this;this.layerTree.filter(this.filterNodeLayerQueryable);var isLayerNode=function(n){return('type'in n.attributes&&(n.attributes.type==Carmen.Control.LayerTreeManager.NODE_LAYER));};var nodes=this.layerTree.collectChildNodes(isLayerNode);if(nodes.length==0){this.headerPanel.setTitle('Aucun résultat');this.gridInfoPanel.hide();}
else{var ms_nodes=[];var wms_nodes=[];var wms_layers=[];for(var i=0;i<nodes.length;i++){var layer=nodes[i].attributes.OlLayer;if(layer instanceof Carmen.Layer.WMSGroup){wms_nodes.push(nodes[i]);Carmen.Util.set_add(wms_layers,layer);}
else
ms_nodes.push(nodes[i]);}
Ext.Ajax.abort();this.queriesSent=0;this.totalCount=0;this.fullExtent=null;if(ms_nodes.length>0)
this.performQuery(this.buildParams(ms_nodes,position));if(position instanceof OpenLayers.Pixel){for(var i=0;i<wms_nodes.length;i++){this.performWMSQuery(wms_nodes[i],position);}}}},registerResults:function(response,queryType){var control=this;this.queriesSent--;this.totalCount=this.totalCount+parseInt(response.totalCount);var headerPanel=Ext.getCmp(control.displayClass+'_'+'headerPanel');headerPanel.setTitle(this.totalCount+' résultats');if(queryType==Carmen.Control.Info.SRC_MS){var currentExtent=Carmen.Util.strExtentToOlBounds(response.extent,Carmen.Control.Info.PUNCTUAL_RADIUS);this.fullExtent=this.fullExtent==null?currentExtent:this.fullExtent.extend(currentExtent);headerPanel.header.removeAllListeners();headerPanel.header.on('click',function(){control.map.zoomToSuitableExtent(control.fullExtent);if(control.showGraphicalSelection){control.map.clearSelection();for(lname in response.results){var node=control.layerTree.findChildByAttribute('layerName',lname);if(node!=null){node.attributes.OlLayer.setDisplayMode(Carmen.Layer.MapServerGroup.DISPLAY_NQUERYMAP,node.attributes.layerName,null,response.queryfile);}}}});for(lname in response.results){var node=control.layerTree.findChildByAttribute('layerName',lname);if(node!=null&&control.showGraphicalSelection){node.attributes.OlLayer.setDisplayMode(Carmen.Layer.MapServerGroup.DISPLAY_NQUERYMAP,node.attributes.layerName,null,response.queryfile);}}}
control.attachResultsToTree(control.layerTree,response.results,queryType);if(this.queriesSent==0)
control.layerTree.filter(control.filterNodeLayerWithResults);},performQuery:function(queryParams){var control=this;var received=function(response){response=Ext.decode(response.responseText);control.registerResults(response,Carmen.Control.Info.SRC_MS);}
this.queriesSent++;var url='/services/GetInformation/index.php';Ext.Ajax.request({url:url,success:received,failure:function(response){Carmen.Util.handleAjaxFailure(response,control.windowTitle,true);},headers:{'my-header':'foo'},params:queryParams});},buildParams:function(nodes,position,fieldsFilter){var layerNames=[];var fieldsList=[];var briefFieldsList=[];var baseQueryURLList=[];for(var i=0;i<nodes.length;i++){layerNames.push(nodes[i].attributes.layerName);fieldsList.push(nodes[i].attributes.infoFields);briefFieldsList.push(nodes[i].attributes.briefFields);baseQueryURLList.push(nodes[i].attributes.baseQueryURL);}
var fieldsDesc=new Array();for(var i=0;i<fieldsList.length;i++){var list=Carmen.Util.chompAndSplit(fieldsList[i],';');fieldsDesc[i]=new Array();for(var j=0;j<list.length;j++){var desc=Carmen.Util.decodeCarmenFieldDesc(list[j],baseQueryURLList[i]);fieldsDesc[i][j]=desc;}
if(fieldsFilter)
fieldsDesc[i]=Carmen.Util.array_filter(fieldsDesc[i],fieldsFilter);}
var briefFieldsDesc=new Array();for(var i=0;i<briefFieldsList.length;i++){var list=Carmen.Util.chompAndSplit(briefFieldsList[i],';');briefFieldsDesc[i]=new Array();for(var j=0;j<list.length;j++){var desc=Carmen.Util.decodeCarmenFieldDesc(list[j],baseQueryURLList[i]);briefFieldsDesc[i][j]=desc;}
briefFieldsDesc[i]=Carmen.Util.array_filter(briefFieldsDesc[i],this.fieldFilter_TXT);}
for(var i=0;i<nodes.length;i++){nodes[i].attributes.infoFieldsDesc=fieldsDesc[i];nodes[i].attributes.briefFieldsDesc=briefFieldsDesc[i];}
var params={layers:Ext.util.JSON.encode(layerNames),fields:Ext.util.JSON.encode(fieldsDesc),briefFields:Ext.util.JSON.encode(briefFieldsDesc),shape:Carmen.Util.positionToStr(this.positionToBounds(position)),map:this.mapfile,showGraphicalSelection:this.showGraphicalSelection}
return params;},performWMSQuery:function(node,position){var control=this;var received=function(response){var features=[];var contentStr=response.getResponseHeader["Content-Type"]||response.getResponseHeader["Content-type"];if(contentStr!=null){contentStr=(contentStr.split(";")[0]).trim();var fmt=control.WMSResponseFormats[contentStr];if(fmt){var rep=response.responseXml||response.responseText;features=fmt.read(response.responseXml||response.responseText);}}
var results={};var extentStr=Carmen.Util.positionToStr(control.map.getExtent());var lName=node.attributes.layerName;for(var i=0;i<features.length;i++){if(!(lName in results)){results[lName]={"fields":[],"briefFields":[],"data":[],"briefData":[]}
for(var f in features[i].attributes){results[lName].fields.push(f);results[lName].briefFields.push(f);}}
var featureData=[];for(var f in features[i].data)
featureData.push(features[i].data[f]);results[lName].briefData.push(featureData);results[lName].data.push(featureData);}
var responseJS={"totalCount":features.length,"results":results};control.registerResults(responseJS,Carmen.Control.Info.SRC_WMS);};this.queriesSent++;Ext.Ajax.request({url:'/services/GetInformation/proxy.php',method:'GET',success:function(response){received(response);},failure:function(response){control.registerResults(Carmen.Control.Info.noResultsResponse,Carmen.Control.Info.SRC_WMS);},headers:{'my-header':'foo'},params:{"proxy_url":node.attributes.OlLayer.getFeatureInfoURL('',position,this.map.size,this.map.getExtent()),"force_utf8_output":1},scope:node});},attachResultsToTree:function(tree,results,queryType){var nodesToUpdate=[];for(lname in results){var node=tree.findChildByAttribute('layerName',lname);if(node!=null){var data=results[lname].data;node.setText(node.text+'  ('+results[lname].data.length+' résultats)');node.attributes.infoData=results[lname];node.attributes.queryType=queryType;node.attributes.queryfile=results[lname].queryfile;var control=this;var gPanel=this.gridInfoPanel;node.addListener('click',function(){if(this.attributes.queryType==Carmen.Control.Info.SRC_MS){var minScale=this.attributes.minScale;var maxScale=this.attributes.maxScale;if(control.showGraphicalSelection){control.map.clearSelection();this.attributes.OlLayer.setDisplayMode(Carmen.Layer.MapServerGroup.DISPLAY_NQUERYMAP,this.attributes.layerName,null,this.attributes.queryfile);}}
else if(this.attributes.queryType==Carmen.Control.Info.SRC_WMS){var infoFieldsDesc=[];for(var i=0;i<this.attributes.infoData.fields.length;i++){var fld=this.attributes.infoData.fields[i];infoFieldsDesc.push({name:fld,alias:fld,type:'TXT'});}
this.attributes.infoFieldsDesc=infoFieldsDesc;}
var gConfig=control.buildGridConfig(this.attributes.infoFieldsDesc,this.attributes.infoData,this.attributes.layerName,this.attributes.olLayer,this.attributes.queryType);gPanel.reconfigure(gConfig.store,gConfig.columnModel)
gPanel.purgeListeners();gPanel.setTitle(this.text);gPanel.node=node;if(this.attributes.queryType==Carmen.Control.Info.SRC_MS){var minScale=this.attributes.minScale;var maxScale=this.attributes.maxScale;gPanel.on('rowclick',function(grid,rowIndex,e){var rec=grid.store.getAt(rowIndex);if(control.showGraphicalSelection){var fid=rec.get('fid');var layerName=rec.get('layerName');var n=control.layerTree.findChildByAttribute('layerName',layerName);var olLayer=n.attributes.OlLayer;control.map.clearSelection();olLayer.setDisplayMode(Carmen.Layer.MapServerGroup.DISPLAY_QUERYMAP,layerName,fid);}});gPanel.on('cellclick',function(grid,rowIndex,columnIndex,e){if(columnIndex==1){var rec=grid.getStore().getAt(rowIndex);var extentStr=rec.get('extent');var bounds=Carmen.Util.strExtentToOlBounds(extentStr,Carmen.Control.Info.PUNCTUAL_RADIUS);control.map.zoomToSuitableExtent(bounds,minScale,maxScale);}});}
if(!gPanel.isVisible()){gPanel.show();control.win.setSize(control.win.getSize().width,control.win.getSize().height+1);}},node);for(var i=0;i<data.length;i++){var child=this.buildResNode(results[lname].briefFields,results[lname].briefData[i],i,node.attributes.queryType);node.appendChild(child);}
nodesToUpdate.push(node);}}
tree.expand(true);for(var i=0;i<nodesToUpdate.length;i++){var node=nodesToUpdate[i];if(node!=null){var iconEl=Ext.fly(node.ui.getIconEl());iconEl.addListener('click',function(){if(this.attributes.queryType==Carmen.Control.Info.SRC_MS){var extentStr=this.attributes.infoData.extent;var minScale=this.attributes.minScale;var maxScale=this.attributes.maxScale;var bounds=Carmen.Util.strExtentToOlBounds(extentStr,Carmen.Control.Info.PUNCTUAL_RADIUS);if(control.showGraphicalSelection){control.map.clearSelection();this.attributes.OlLayer.setDisplayMode(Carmen.Layer.MapServerGroup.DISPLAY_NQUERYMAP,this.attributes.layerName,null,this.attributes.queryfile);}
control.map.zoomToSuitableExtent(bounds,minScale,maxScale);}},node);}};tree.collapse(true);},buildResNode:function(fields,data,nodeIndex,queryType){var control=this;var name=data.length>2?data[0]:data[data.length-1];;if(fields.length>3){name=name+' (';for(var i=1;i<fields.length-2;i++){name=name+fields[i]+' : '+data[i]+', ';}
name=name.substr(0,name.length-2)+')';}
var node=new Ext.tree.TreeNode({text:name,leaf:true,uiProvider:Carmen.TreeNodeInfoUI,listeners:{'click':{fn:function(n,evt){n.parentNode.fireEvent('click',n);var index=n.parentNode.indexOf(n);control.gridInfoPanel.getView().focusRow(index);control.gridInfoPanel.getSelectionModel().selectRow(index);if(queryType==Carmen.Control.Info.SRC_MS&&control.showGraphicalSelection){control.map.clearSelection();n.parentNode.attributes.OlLayer.setDisplayMode(Carmen.Layer.MapServerGroup.DISPLAY_QUERYMAP,n.parentNode.attributes.layerName,n.attributes.fid);}}}}});node.attributes.type=Carmen.Control.LayerTreeManager.NODE_FEATURE;if(queryType==Carmen.Control.Info.SRC_MS)
node.attributes.fid=data[data.length-1];return node;},extentRenderer:function(v){return'<div class="cmnInfoGridZoomIcon"> </div>';},buildGridConfig:function(fieldsDesc,result,layerName,olLayer,queryType){var fields=new Array();var columns=new Array();columns.push(new Ext.grid.RowNumberer());if(queryType==Carmen.Control.Info.SRC_MS){columns.push({id:'extent',header:'',width:20,resizable:true,renderer:this.extentRenderer,dataIndex:'extent'});}
for(var i=0;i<fieldsDesc.length;i++){var desc=fieldsDesc[i];var fDesc={name:desc.name+i.toString(),type:Carmen.Util.carmenTypeToExtType(desc.type)};switch(desc.type){case'date':fDesc['dateFormat']=Carmen.Util.carmenDateTypeToExtDateFormat(desc.type);break;default:break;}
fields.push(fDesc);var colDesc={id:desc.name+i.toString(),header:desc.alias,width:200,sortable:true,resizable:true,renderer:Carmen.Util.carmenTypeToExtRenderer(desc.type),dataIndex:desc.name+i.toString()};columns.push(colDesc);}
if(queryType==Carmen.Control.Info.SRC_MS){fields.push({name:'extent'});fields.push({name:'fid'});}
fields.push({name:'layerName'});for(var i=0;i<result.data.length;i++){result.data[i]=result.data[i].concat([layerName]);}
var config={store:new Ext.data.SimpleStore({fields:fields,data:result.data}),columnModel:new Ext.grid.ColumnModel({columns:columns})};return config;},filterNodeLayerQueryable:function(node){var res=true;res=('type'in node.attributes)&&((node.attributes.type==Carmen.Control.LayerTreeManager.NODE_GROUP&&node.hasChildNodes()&&node.getDepth()>0)||(node.attributes.type==Carmen.Control.LayerTreeManager.NODE_LAYER&&node.attributes.OlLayer.getVisibility(node.attributes.layerName)&&((node.attributes.infoFields&&node.attributes.infoFields.length>0)||(node.attributes.OlLayer instanceof Carmen.Layer.WMSGroup))));return res;},filterNodeLayerWithResults:function(node){var res=true;res=('type'in node.attributes)&&((node.attributes.type==Carmen.Control.LayerTreeManager.NODE_GROUP&&node.hasChildNodes()&&node.getDepth()>0)||(node.attributes.type==Carmen.Control.LayerTreeManager.NODE_LAYER&&node.attributes.infoData!=null)||(node.attributes.type==Carmen.Control.LayerTreeManager.NODE_FEATURE));return res;},transformNodeInfo:function(atts){var cloneAtts=Carmen.Util.clone(atts);if(cloneAtts.text!=Carmen.Control.LayerTreeManager.TREE_NODE_ROOT_LABEL)
cloneAtts.uiProvider=Carmen.TreeNodeInfoUI;else
cloneAtts.uiProvider=Carmen.RootTreeNodeInfoUI;cloneAtts.cls='none';cloneAtts.infoData=null;cloneAtts.listeners={};cloneAtts.expandable=true;if(cloneAtts.type==Carmen.Control.LayerTreeManager.NODE_LAYER){cloneAtts.icon='/IHM/images/NoTreeIcon.gif';cloneAtts.iconCls='cmnInfoGridZoomIcon';}
return cloneAtts;},fieldFilter_URL:function(field){return field.type=='URL';},fieldFilter_TXT:function(field){return field.type=='TXT';},positionToBounds:function(position){var bounds=null;if(position instanceof OpenLayers.Bounds){var minXY=this.map.getLonLatFromPixel(new OpenLayers.Pixel(position.left,position.bottom));var maxXY=this.map.getLonLatFromPixel(new OpenLayers.Pixel(position.right,position.top));bounds=new OpenLayers.Bounds(minXY.lon,minXY.lat,maxXY.lon,maxXY.lat);}
else{var tol=Carmen.Util.INFO_TOOL_XY_TOLERANCE;var minXY=this.map.getLonLatFromPixel(new OpenLayers.Pixel(position.x-tol,position.y-tol));var maxXY=this.map.getLonLatFromPixel(new OpenLayers.Pixel(position.x+tol,position.y+tol));bounds=new OpenLayers.Bounds(minXY.lon,minXY.lat,maxXY.lon,maxXY.lat);}
return bounds;},CLASS_NAME:"Carmen.Control.Info"});Carmen.Control.Info.SRC_MS=0;Carmen.Control.Info.SRC_WMS=1;Carmen.Control.Info.PUNCTUAL_RADIUS=100.0;Carmen.Control.Info.noResultsResponse={"totalCount":0,"results":[]};Proj4js.defs["EPSG:32301"]="+proj=utm +zone=1 +south +ellps=WGS72 +units=m +no_defs";Proj4js.defs["EPSG:32630"]="+proj=utm +zone=30 +ellps=WGS84 +datum=WGS84 +units=m +no_defs";Proj4js.defs["EPSG:2970"]="+proj=utm +zone=20 +ellps=intl +units=m +no_defs";Proj4js.defs["EPSG:27581"]="+proj=lcc +lat_1=49.50000000000001 +lat_0=49.50000000000001 +lon_0=0 +k_0=0.999877341 +x_0=600000 +y_0=1200000 +a=6378249.2 +b=6356515 +towgs84=-168,-60,320,0,0,0,0 +pm=paris +units=m +no_defs";Proj4js.defs["EPSG:27562"]="+proj=lcc +lat_1=46.8 +lat_0=46.8 +lon_0=0 +k_0=0.99987742 +x_0=600000 +y_0=200000 +a=6378249.2 +b=6356515 +towgs84=-168,-60,320,0,0,0,0 +pm=paris +units=m +no_defs";Proj4js.defs["EPSG:3297"]="+proj=utm +zone=6 +south +ellps=GRS80 +units=m +no_defs";Carmen.Control.QueryAttributes=new OpenLayers.Class(OpenLayers.Control,{btn:new Ext.Toolbar.Button({tooltip:'Requêtes attributaires',tooltipType:'title',cls:'x-btn-icon cmn-tool-requete',enableToggle:true,toggleGroup:'mainMapControl',disabled:false}),win:new Ext.Window({layout:'anchor',width:400,height:400,plain:true,title:'Requêtes attributaires',modal:false,autoDestroy:true,resizable:true,closeAction:'hide',shadow:false}),requestPanel:new Ext.FormPanel({id:'requestPanel',autoScroll:true,fitToFrame:true,labelWidth:75,title:'Requête',bodyStyle:'padding:5px 5px 0; color: #000000;',labelStyle:'color: #000000;',items:[{xtype:'combo',tpl:'<tpl for="."><div ext:qtip="{layerTitle}" class="x-combo-list-item">{layerTitle}</div></tpl>',name:'layer',id:'comboLayer',fieldLabel:'Couche',mode:'local',editable:true,loadingText:'Chargement',emptyText:'Sélectionnez une couche',typeAhead:true,forceSelection:true,triggerAction:'all',minChars:1,queryDelay:250,store:new Ext.data.SimpleStore({fields:['layerName','layerTitle'],data:[]}),validator:function(v){return(v!='Sélectionnez une couche');},displayField:'layerTitle',valueField:'layerName',width:240},{xtype:'combo',tpl:'<tpl for="."><div ext:qtip="{fieldLabel}" class="x-combo-list-item">{fieldLabel}</div></tpl>',name:'qitem',id:'comboField',fieldLabel:'Champ',mode:'local',editable:true,loadingText:'Chargement',emptyText:'Sélectionnez un champ',typeAhead:true,forceSelection:true,triggerAction:'all',minChars:1,queryDelay:250,disabled:true,store:new Ext.data.SimpleStore({fields:['fieldName','fieldLabel'],data:[]}),validator:function(v){return(v!='Sélectionnez un champ');},displayField:'fieldLabel',valueField:'fieldName',allowBlank:false,width:240},{xtype:'combo',id:'comboOperator',name:'qstring',fieldLabel:'Opérateur',editable:true,loadingText:'Chargement',emptyText:'Sélectionnez un opérateur',typeAhead:true,forceSelection:true,triggerAction:'all',minChars:1,queryDelay:250,mode:'local',store:new Ext.data.SimpleStore({fields:['qstring','label'],data:[['FIELD like \'PATTERN%\'','commence par '],['FIELD like \'%PATTERN%\'','contient '],['not (FIELD like \'%PATTERN%\')','ne contient pas '],['FIELD = PATTERN','est égal (=)'],['FIELD <> PATTERN','est différent (<>)'],['FIELD >= PATTERN','supérieur ou égal (>=)'],['FIELD > PATTERN','strictement supérieur (>)'],['FIELD <= PATTERN','inférieur ou égal (<=)'],['FIELD < PATTERN','strictement inférieur (<)']]}),validator:function(v){return(v!='Sélectionnez un opérateur');},displayField:'label',valueField:'qstring',width:240},{xtype:'textfield',name:'value',id:'fieldValue',fieldLabel:'Valeur',mode:'local',allowBlank:false,width:240}],buttons:[{id:'requestSubmit',text:'Interroger'}]}),gridInfoPanel:new Ext.grid.GridPanel({store:new Ext.data.SimpleStore({fields:[],data:[]}),columns:[],title:'Résultats sélectionnés',hidden:true,autoScroll:true,collapsible:true,border:false,iconCls:'cmnInfoGridZoomIcon',anchor:'100% 50%'}),layerData:[],fieldData:[],layerFieldsDesc:[],layerTreeManager:null,layerTree:null,mapfile:null,serviceUrl:null,initialize:function(serviceUrl,mapfile,options){OpenLayers.Control.prototype.initialize.apply(this,arguments);this.mapfile=mapfile;this.serviceurl=serviceUrl;},setMap:function(map){OpenLayers.Control.prototype.setMap.apply(this,arguments);this.btn.addListener('toggle',Carmen.Util.buildExt2olHandlerToggle(this));var tb=this.map.app.ui.getTopToolBar();tb.addItem(this.btn);var control=this;this.win.on('hide',function(w){control.btn.toggle(false);},this.win);this.map.app.ui.doLayout();},activate:function(){if(this.getLayerTreeManager==null){Ext.MessageBox.alert("Warning","The control "+
this.CLASS_NAME+" requires the LayerTreeManager control to work.");return null;}
OpenLayers.Control.prototype.activate.apply(this,arguments);this.map.toolTipDeactivate();this.showWindow();},deactivate:function(){this.map.clearSelection();OpenLayers.Control.prototype.deactivate.apply(this,arguments);if(this.win.rendered)
this.win.hide();this.map.toolTipActivate();},showWindow:function(){var control=this;this.layerTree=this.getLayerTreeManager().getLayerTree().clone(this.transformNodeInfo);if(!this.win.rendered){this.win.add(this.requestPanel);this.win.add(this.gridInfoPanel);var submitBtn=Ext.getCmp('requestSubmit');submitBtn.on('click',function(btn,evt){var form=control.requestPanel.getForm();if(!form.isValid())
Ext.Msg.alert('Requêtes attributaires','La requête saisie n\'est pas valide.');else{control.performQuery(control.buildParams(control.layerFieldsDesc));}},submitBtn);this.win.doLayout();}
if(!this.win.isVisible()){this.initFields();this.win.show();}},getLayerTreeManager:function(){if(this.layertreeManager==null){var controls=this.map.getControlsByClass('Carmen.Control.LayerTreeManager');this.layerTreeManager=controls.length==0?null:controls[0];}
return this.layerTreeManager;},getLayerTree:function(){this.layerTree=this.getLayerTreeManager().getLayerTree().clone(this.transformNodeInfo);this.layerTree.filter(this.filterNodeLayerQueryable);return this.layerTree;},initFields:function(){var qLayerAtts=this.getLayerTree().collect('attributes',true);this.layerData=[['none','Sélectionnez une couche']];this.fieldData=[];for(var i=0;i<qLayerAtts.length;i++){var layerAtt=qLayerAtts[i];this.layerData.push([layerAtt.layerName,layerAtt.text]);layerFieldsData=[];fieldsCarmenDesc=Carmen.Util.chompAndSplit(layerAtt.infoFields,';');this.layerFieldsDesc[layerAtt.layerName]=[];for(var j=0;j<fieldsCarmenDesc.length;j++){fieldDesc=Carmen.Util.decodeCarmenFieldDesc(fieldsCarmenDesc[j],layerAtt.baseQueryURL);if(fieldDesc.type=='TXT')
layerFieldsData.push([fieldDesc.name,fieldDesc.alias]);this.layerFieldsDesc[layerAtt.layerName].push(fieldDesc);}
this.fieldData.push(layerFieldsData);}
var comboLayer=Ext.getCmp('comboLayer');var comboField=Ext.getCmp('comboField');comboLayer.getStore().loadData(this.layerData);var control=this;comboLayer.on('select',function(f,r,i){if(i==0){comboField.clearValue();comboField.disable();}
else{comboField.setValue('');comboField.getStore().removeAll();comboField.getStore().loadData(control.fieldData[i-1]);comboField.enable();}},comboLayer);},buildParams:function(layerFieldsDesc){var form=Ext.getCmp('requestPanel').getForm();var values=form.getValues();var comboLayer=Ext.getCmp('comboLayer');var layerName=comboLayer.getValue();var qitem=Ext.getCmp('comboField').getValue();var op=Ext.getCmp('comboOperator').getValue();var pattern=Ext.getCmp('fieldValue').getValue();var qstring=op;var params={layer:layerName,qstring:qstring,pattern:pattern,qitem:qitem,fields:Ext.util.JSON.encode(layerFieldsDesc[layerName]),map:this.mapfile}
return params;},performQuery:function(queryParams){var control=this;var received=function(response){response=Ext.decode(response.responseText);if(response.totalCount==0){control.clearGridPanel();}
else{for(lname in response.results){var node=control.layerTree.findChildByAttribute('layerName',lname);if(node!=null){var data=response.results[lname].data;node.attributes.infoData=response.results[lname];node.attributes.infoData.qfile=response.queryfile;control.updateGridPanel(node);}}}}
Ext.Ajax.request({url:'/services/QueryAttributes/index.php',success:function(response){received(response);},failure:function(response){Carmen.Util.handleAjaxFailure(response,"Requêtes attributaires");},params:queryParams});},clearGridPanel:function(){var gPanel=this.gridInfoPanel;gPanel.setTitle('Aucun résultat');gPanel.reconfigure(Carmen.Util.emptyStore,Carmen.Util.emptyColumnModel);if(!gPanel.isVisible())
gPanel.show();},updateGridPanel:function(layerNode){var control=this;var gPanel=this.gridInfoPanel;this.map.clearSelection();gPanel.purgeListeners();gPanel.setTitle(layerNode.text+' '+
layerNode.attributes.infoData.data.length+' résultats');var extentStr=layerNode.attributes.infoData.extent;var minScale=layerNode.attributes.minScale;var maxScale=layerNode.attributes.maxScale;var bounds=Carmen.Util.strExtentToOlBounds(extentStr,Carmen.Control.QueryAttributes.PUNCTUAL_RADIUS);var lnode=layerNode;gPanel.header.on('click',function(){control.map.zoomToSuitableExtent(bounds,minScale,maxScale);lnode.attributes.OlLayer.setDisplayMode(Carmen.Layer.MapServerGroup.DISPLAY_NQUERYMAP,lnode.attributes.layerName,null,lnode.attributes.infoData.qfile);});layerNode.attributes.OlLayer.setDisplayMode(Carmen.Layer.MapServerGroup.DISPLAY_NQUERYMAP,layerNode.attributes.layerName,null,layerNode.attributes.infoData.qfile);var gConfig=this.buildGridConfig(layerNode.attributes.infoFields,layerNode.attributes.infoData);gPanel.reconfigure(gConfig.store,gConfig.columnModel)
gPanel.on('rowclick',function(grid,rowIndex,e){var rec=grid.store.getAt(rowIndex);var fid=rec.get('fid');lnode.attributes.OlLayer.setDisplayMode(Carmen.Layer.MapServerGroup.DISPLAY_QUERYMAP,lnode.attributes.layerName,fid);});gPanel.on('cellclick',function(grid,rowIndex,columnIndex,e){if(columnIndex==1){var rec=grid.getStore().getAt(rowIndex);var extentStr=rec.get('extent');var bounds=Carmen.Util.strExtentToOlBounds(extentStr,Carmen.Control.Info.PUNCTUAL_RADIUS);control.map.zoomToSuitableExtent(bounds,minScale,maxScale);}});if(!gPanel.isVisible()){gPanel.show();this.win.setSize(control.win.getSize().width,this.win.getSize().height+1);}},extentRenderer:function(v){return'<div class="cmnInfoGridZoomIcon"> </div>';},buildGridConfig:function(fieldsDesc,result){var fields=new Array();var columns=new Array();columns.push(new Ext.grid.RowNumberer());columns.push({id:'extent',header:'',width:20,resizable:true,renderer:this.extentRenderer,dataIndex:'extent'});var arrFieldsDesc=Carmen.Util.chompAndSplit(fieldsDesc,';');for(var i=0;i<arrFieldsDesc.length;i++){var desc=Carmen.Util.decodeCarmenFieldDesc(arrFieldsDesc[i]);var fDesc={name:desc.name+i.toString(),type:Carmen.Util.carmenTypeToExtType(desc.type)};if(desc.type=='date')
fDesc['dateFormat']=Carmen.Util.carmenDateTypeToExtDateFormat(desc.type);fields.push(fDesc);var colDesc={id:desc.name+i.toString(),header:desc.alias,width:200,sortable:true,resizable:true,renderer:Carmen.Util.carmenTypeToExtRenderer(desc.type),dataIndex:desc.name+i.toString()};columns.push(colDesc);}
fields.push({name:'extent'});fields.push({name:'fid'});var config={store:new Ext.data.SimpleStore({fields:fields,data:result.data}),columnModel:new Ext.grid.ColumnModel({columns:columns})};return config;},filterNodeLayerQueryable:function(node){var res=true;res=('type'in node.attributes)&&((node.attributes.type==Carmen.Control.LayerTreeManager.NODE_GROUP&&node.hasChildNodes())||(node.attributes.type==Carmen.Control.LayerTreeManager.NODE_LAYER&&node.attributes.OlLayer.getVisibility(node.attributes.layerName)&&node.attributes.briefFields&&node.attributes.briefFields.length>0&&node.attributes.infoFields&&node.attributes.infoFields.length>0));return res;},filterNodeLayerWithResults:function(node){var res=true;res=('type'in node.attributes)&&((node.attributes.type==Carmen.Control.LayerTreeManager.NODE_GROUP&&node.hasChildNodes())||(node.attributes.type==Carmen.Control.LayerTreeManager.NODE_LAYER&&node.attributes.infoData!=null)||(node.attributes.type==Carmen.Control.LayerTreeManager.NODE_FEATURE));return res;},transformNodeInfo:function(atts){var cloneAtts=Carmen.Util.clone(atts);if(cloneAtts.text!="root")
cloneAtts.uiProvider=Carmen.TreeNodeInfoUI;else
cloneAtts.uiProvider=Carmen.RootTreeNodeInfoUI;cloneAtts.cls='none';cloneAtts.infoData=null;cloneAtts.listeners={};cloneAtts.expandable=true;if(cloneAtts.type==Carmen.Control.LayerTreeManager.NODE_LAYER){cloneAtts.icon='/IHM/images/NoTreeIcon.gif';cloneAtts.iconCls='cmnInfoGridZoomIcon';}
return cloneAtts;},CLASS_NAME:"Carmen.Control.QueryAttributes"});Carmen.Control.QueryAttributes.PUNCTUAL_RADIUS=100.0;Proj4js.defs["EPSG:2972"]="+proj=utm +zone=22 +ellps=GRS80 +towgs84=2,2,-2,0,0,0,0 +units=m +no_defs"
Proj4js.defs["EPSG:3169"]="+proj=utm +zone=57 +south +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs";Proj4js.defs["EPSG:3296"]="+proj=utm +zone=5 +south +ellps=GRS80 +units=m +no_defs";Carmen.Control.InfoURL=new OpenLayers.Class(Carmen.Control.Info,{btn:new Ext.Toolbar.Button({tooltip:'URL Informatives',tooltipType:'title',cls:'x-btn-icon cmn-tool-infourl',enableToggle:true,toggleGroup:'mainMapControl',disabled:false}),windowTitle:'URL informatives',showGraphicalSelection:false,buildParams:function(nodes,position){return Carmen.Control.Info.prototype.buildParams.apply(this,[nodes,position,this.fieldFilter_URL]);},filterNodeLayerQueryable:function(node){var res=Carmen.Control.Info.prototype.filterNodeLayerQueryable.apply(this,arguments);res=res&&((node.attributes.type==Carmen.Control.LayerTreeManager.NODE_GROUP&&node.hasChildNodes()&&node.getDepth()>0)||(node.attributes.infoFields&&node.attributes.infoFields.match(/.*URL.*/)!=null));return res;},performQuery:function(queryParams){var control=this;var received=function(response){response=Ext.decode(response.responseText);uniqueURL=null;if(response.totalCount==1){for(var l in response.results){nbFields=response.results[l].fields.length;}
if(nbFields==3){uniqueURL=response.results[l].data[0][0];}}
if(uniqueURL){control.win.hide();Carmen.Util.openWindowIframe('Information détaillée',uniqueURL.href);}
else{var headerPanel=Ext.getCmp(control.displayClass+'_'+'headerPanel');headerPanel.setTitle(response.totalCount+' résultats');headerPanel.header.on('click',function(){var extentStr=response.extent;var bounds=Carmen.Util.strExtentToOlBounds(extentStr,Carmen.Control.Info.PUNCTUAL_RADIUS);control.map.zoomToSuitableExtent(bounds);});control.attachResultsToTree(control.layerTree,response.results,Carmen.Control.Info.SRC_MS);control.layerTree.filter(control.filterNodeLayerWithResults);}}
Ext.Ajax.request({url:'/services/GetInformation/index.php',success:function(response){received(response);},failure:function(response){control.win.hide();Carmen.Util.handleAjaxFailure(response,control.windowTitle,true);},headers:{'my-header':'foo'},params:queryParams});},CLASS_NAME:"Carmen.Control.InfoURL"});Proj4js.defs["EPSG:27564"]="+proj=lcc +lat_1=42.16500000000001 +lat_0=42.16500000000001 +lon_0=0 +k_0=0.99994471 +x_0=234.358 +y_0=185861.369 +a=6378249.2 +b=6356515 +towgs84=-168,-60,320,0,0,0,0 +pm=paris +units=m +no_defs";Proj4js.defs["EPSG:32632"]="+proj=utm +zone=32 +ellps=WGS84 +datum=WGS84 +units=m +no_defs";Carmen.Control.ExportImg=new OpenLayers.Class(OpenLayers.Control,{btn:new Ext.Toolbar.Button({tooltip:'Export image',tooltipType:'title',cls:'x-btn-icon cmn-tool-save',enableToggle:true,toggleGroup:'mainMapControl',disabled:false}),win:new Ext.Window({layout:'anchor',width:400,height:250,plain:true,id:"winExport",title:'Export image',modal:false,autoDestroy:true,resizable:true,closeAction:'hide',shadow:false}),printPanel:new Ext.FormPanel({id:'ExportImg',autoScroll:true,fitToFrame:true,labelWidth:75,bodyStyle:'padding:5px 5px 0; color: #000000;',labelStyle:'color: #000000;',url:'/services/GetIMG/getIMG.php',items:[{xtype:'combo',id:'comboFormat',name:'format',fieldLabel:'Format de sauvegarde',editable:false,loadingText:'Chargement',emptyText:'Sélectionnez un format',typeAhead:true,forceSelection:true,triggerAction:'all',minChars:1,queryDelay:250,mode:'local',store:new Ext.data.SimpleStore({fields:['qstring1','label'],data:[['Image PNG','Image PNG'],['Image JPEG','Image JPEG'],['Image PNG24','Image PNG24']]}),validator:function(v){return(v!='Sélectionnez un format');},displayField:'label',allowBlank:false,valueField:'qstring1',width:180},{xtype:'combo',id:'comboWidth',name:'size',fieldLabel:'Taille de l\'image',editable:false,loadingText:'Chargement',emptyText:'Sélectionnez une taille',typeAhead:true,forceSelection:true,triggerAction:'all',minChars:1,queryDelay:250,allowBlank:false,mode:'local',store:new Ext.data.SimpleStore({fields:['qstring','label'],data:[['300x200','300x200'],['600x400','600x400'],['1200x800','1200x800']]}),validator:function(v){return(v!='Sélectionnez une taille');},displayField:'label',valueField:'qstring',width:180},{xtype:'radiogroup',columns:1,fieldLabel:'Traitement de la carte',name:'typeExport',items:[{boxLabel:'Echelle conservée',name:'typeExport',inputValue:'0',checked:true},{boxLabel:'Emprise conservée',name:'typeExport',inputValue:'1'}]},{xtype:"hidden",name:"contextJs",value:"",hidden:true,hiddenLabel:true},{xtype:"hidden",name:"mapWidth",value:"",hidden:true,hiddenLabel:true},new Ext.ux.IFrameComponent({url:"/blank.html",name:"iFrameImg",width:"0",height:"0"})],buttons:[{id:'submitImg',text:'Générer'}]}),initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,arguments);},setMap:function(map){OpenLayers.Control.prototype.setMap.apply(this,arguments);this.btn.addListener('toggle',Carmen.Util.buildExt2olHandlerToggle(this));var tb=this.map.app.ui.getTopToolBar();tb.addItem(this.btn);var control=this;this.win.on('hide',function(w){control.btn.toggle(false);},this.win);this.map.app.ui.doLayout();},trigger:function(){this.showWindow();},activate:function(){OpenLayers.Control.prototype.activate.apply(this,arguments);this.map.toolTipDeactivate();this.showWindow();},deactivate:function(){OpenLayers.Control.prototype.deactivate.apply(this,arguments);if(this.win.rendered)
this.win.hide();this.map.toolTipActivate();},showWindow:function(){var win=this.win;if(!this.win.rendered){this.win.add(this.printPanel);var submitBtn=Ext.getCmp('submitImg');submitBtn.on('click',function(btn,evt){var form=Ext.getCmp("ExportImg").getForm();form.getEl().dom.target='iFrameImg';form.getEl().dom.action='/services/GetIMG/getIMG.php';if(!form.isValid())
Ext.Msg.alert('Export Image','Demande non valide');else{form.getEl().dom.submit();}},submitBtn);this.win.doLayout();}
if(!this.win.isVisible()){var form=this.printPanel.getForm();this.win.show();var app=this.map.app;var ctx=app.context;form.setValues({"mapWidth":app.map.size.w,"contextJs":Ext.util.JSON.encode(app.updateContext(true))});}},CLASS_NAME:"Carmen.Control.ExportImg"});Proj4js.defs["EPSG:3171"]="+proj=utm +zone=59 +south +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs";OpenLayers.Control.MapserverScale=new OpenLayers.Class(OpenLayers.Control,{serverUrl:'',mapfile:'',scaleImg:null,displayTxt:true,displayImg:true,font:null,fontFamily:'tahoma,arial,helvetica,sans-serif',color:'#000000',fontSize:'12px',fontWeight:'normal',fontStyle:'normal',backgroundColor:null,opacity:1.0,initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,arguments);this.fontFamily=this.font?this.font+','+this.fontFamily:this.fontFamily;if(this.fontSize&&this.fontSize.search(/^\d+$/g)!=-1)
this.fontSize=this.fontSize+'px';if(this.color&&this.color.charAt(0)!='#')
this.color='#'+this.color;if(this.backgroundColor&&this.backgroundColor.charAt(0)!='#')
this.backgroundColor='#'+this.backgroundColor;if(this.backgroundColor&&this.backgroundColor.length==9){this.opacity=1.0-(parseInt(this.backgroundColor.substring(7,9),16)/255);this.backgroundColor=this.backgroundColor.substring(0,7);}},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);this.div.style.display="block";this.div.style.position="absolute";this.div.style.backgroundColor=this.backgroundColor;this.div.style.fontFamily=this.fontFamily;this.div.style.fontWeight=this.fontWeight;this.div.style.color=this.color;this.div.style.fontSize=this.fontSize;this.div.style.fontStyle=this.fontStyle;OpenLayers.Util.modifyDOMElement(this.div,null,null,null,null,null,null,this.opacity);if(!this.scaleImg&&this.displayImg){this.scaleImg=document.createElement("img");this.scaleImg.style.verticalAlign='top';this.div.appendChild(this.scaleImg);}
if(!this.scaleTxt&&this.displayTxt){this.scaleTxt=document.createElement("span");this.scaleTxt.style.verticalAlign='top';this.scaleTxt.style.marginLeft='10px';this.div.appendChild(this.scaleTxt);}
this.map.events.register('moveend',this,this.update);this.update();return this.div;},update:function(){if(this.displayImg&&this.scaleImg){var params={MAP:this.mapfile,MAP_IMAGETYPE:'PNG',MODE:'SCALEBAR',map_resolution:Carmen.Mapserver_DOTS_PER_INCH,SCALE:this.map.getScale()};this.scaleImg.src=this.serverUrl+'?'+
OpenLayers.Util.getParameterString(params);}
if(this.displayTxt&&this.scaleTxt){this.scaleTxt.innerHTML=this.map.getScale()?'Echelle '+Carmen.SpecialChars["around"]+' '+
Carmen.Util.scaleTextFormater(Carmen.Util.roundIntToDigits(this.map.getScale())):'';}},CLASS_NAME:"OpenLayers.Control.MapserverScale"});Proj4js.defs["EPSG:27573"]="+proj=lcc +lat_1=44.10000000000001 +lat_0=44.10000000000001 +lon_0=0 +k_0=0.999877499 +x_0=600000 +y_0=3200000 +a=6378249.2 +b=6356515 +towgs84=-168,-60,320,0,0,0,0 +pm=paris +units=m +no_defs";Carmen.Control.PanArrows=OpenLayers.Class(OpenLayers.Control,{slideFactor:50,buttons:null,position:null,initialize:function(options){this.position=new OpenLayers.Pixel(0,0);OpenLayers.Control.prototype.initialize.apply(this,arguments);},destroy:function(){OpenLayers.Control.prototype.destroy.apply(this,arguments);while(this.buttons.length){var btn=this.buttons.shift();btn.map=null;OpenLayers.Event.stopObservingElement(btn);}
this.buttons=null;this.position=null;},setMap:function(map){OpenLayers.Control.PanZoom.prototype.setMap.apply(this,arguments);this.map.app.ui.getMainPanel().on('resize',function(){this.draw(this.position);},this);},draw:function(px){OpenLayers.Control.prototype.draw.apply(this,arguments);px=this.position;this.buttons=[];var sz=new OpenLayers.Size(9,9);var mp_height=this.map.app.ui.getMainPanel().getInnerHeight();var mp_width=this.map.app.ui.getMainPanel().getInnerWidth();px_north=new OpenLayers.Pixel((mp_width+sz.w)/2,0);this._updateButton("panup","/IHM/images/Pan_Nord_OFF.png",px_north,sz);px_south=new OpenLayers.Pixel((mp_width+sz.w)/2,mp_height-sz.h);this._updateButton("pandown","/IHM/images/Pan_Sud_OFF.png",px_south,sz);px_east=new OpenLayers.Pixel(mp_width-sz.w,(mp_height-sz.h)/2);this._updateButton("panright","/IHM/images/Pan_Est_OFF.png",px_east,sz);px_west=new OpenLayers.Pixel(0,(mp_height-sz.h)/2);this._updateButton("panleft","/IHM/images/Pan_Ouest_OFF.png",px_west,sz);px_northeast=new OpenLayers.Pixel(mp_width-sz.w,0);this._updateButton("panupright","/IHM/images/Pan_NordEst_OFF.png",px_northeast,sz);px_sudeast=new OpenLayers.Pixel(mp_width-sz.w,mp_height-sz.h);this._updateButton("pandownright","/IHM/images/Pan_SudEst_OFF.png",px_sudeast,sz);px_northwest=new OpenLayers.Pixel(0,0);this._updateButton("panupleft","/IHM/images/Pan_NordOuest_OFF.png",px_northwest,sz);px_sudwest=new OpenLayers.Pixel(0,mp_height-sz.h);this._updateButton("pandownleft","/IHM/images/Pan_SudOuest_OFF.png",px_sudwest,sz);return this.div;},_updateButton:function(id,img,xy,sz){var full_id=this.id+'_'+id;var btn=Ext.getDom(full_id);if(btn==null){var imgLocation=img;var btn=OpenLayers.Util.createAlphaImageDiv(full_id,xy,sz,imgLocation,"absolute");this.div.appendChild(btn);OpenLayers.Event.observe(btn,"mousedown",OpenLayers.Function.bindAsEventListener(this.buttonDown,btn));OpenLayers.Event.observe(btn,"dblclick",OpenLayers.Function.bindAsEventListener(this.doubleClick,btn));OpenLayers.Event.observe(btn,"click",OpenLayers.Function.bindAsEventListener(this.doubleClick,btn));btn.action=id;btn.map=this.map;btn.slideFactor=this.slideFactor;this.buttons.push(btn);}
else
OpenLayers.Util.modifyDOMElement(btn,full_id,xy,sz,"absolute");return btn;},doubleClick:function(evt){OpenLayers.Event.stop(evt);return false;},buttonDown:function(evt){if(!OpenLayers.Event.isLeftClick(evt)){return;}
switch(this.action){case"panup":this.map.pan(0,-this.slideFactor);break;case"pandown":this.map.pan(0,this.slideFactor);break;case"panleft":this.map.pan(-this.slideFactor,0);break;case"panright":this.map.pan(this.slideFactor,0);break;case"panupright":this.map.pan(this.slideFactor,-this.slideFactor);break;case"panupleft":this.map.pan(-this.slideFactor,-this.slideFactor);break;case"pandownright":this.map.pan(this.slideFactor,this.slideFactor);break;case"pandownleft":this.map.pan(-this.slideFactor,this.slideFactor);break;}
OpenLayers.Event.stop(evt);},CLASS_NAME:"OpenLayers.Control.PanArrows"});Carmen.Control.FavoriteAreas=new OpenLayers.Class(OpenLayers.Control,{areaBox:new Ext.form.ComboBox({autoLoad:true,typeAhead:false,mode:'local',triggerAction:'all',emptyText:'Zones favorites',selectOnFocus:true,forceSelection:true,width:160,displayField:'areaName',loadingText:'Chargement',valueField:'value',editable:false,disableKeyFilter:false,valueNotFoundText:'Zones favorites',store:new Ext.data.SimpleStore({fields:['areaName','value'],data:[['Nouvelle zone','']]})}),initialize:function(contextInit,options){OpenLayers.Control.prototype.initialize.apply(this,arguments);if(contextInit!=null)
this.initFromContext(contextInit);},setMap:function(map){OpenLayers.Control.prototype.setMap.apply(this,arguments);var tb=this.map.app.ui.getTopToolBar();tb.addItem(this.areaBox);var map=this.map;var control=this;this.areaBox.addListener('select',function(f,r,i){if(r.data.areaName==Carmen.Control.FavoriteAreas.newFavoriteAreaTxt){var control=this;Ext.Msg.prompt('Nouvelle zone','Nom',function(btn,value){if(btn=='ok'){var gbmName=value.length>0?value:Carmen.Control.FavoriteAreas.defaultName+
Carmen.Control.FavoriteAreas.getUniqueId().toString();f.getStore().loadData([[gbmName,map.getExtent()]],true);}},control);}
else if(r.data.areaName!=Carmen.Control.FavoriteAreas.emptyFavoriteAreaTxt&&r.data.areaName!=''){map.zoomToExtent(r.data.value);}},control);this.areaBox.addListener('collapse',function(){this.areaBox.setValue(-1);this.areaBox.getEl().blur();},this);this.map.app.ui.doLayout();},serializeForContext:function(){var bookmarks=[];var store=this.areaBox.getStore();for(var i=1;i<store.getTotalCount();i++){var rec=store.getAt(i);var extent=rec.get('value');var lc=extent.left.toString()+' '+extent.bottom.toString();var uc=extent.right.toString()+' '+extent.top.toString();var bookmark={name:rec.get('areaName'),BoundingBox:{LowerCorner:lc,UpperCorner:uc}}
bookmarks.push(bookmark);}
return{GeoBookmark:bookmarks};},initFromContext:function(bookmarks){var store=this.areaBox.getStore();for(var i=1;i<store.getTotalCount();i++){store.removeAt(i);}
if(!(bookmarks instanceof Array))
bookmarks=[bookmarks];var BookmarkRecord=Ext.data.Record.create([{name:'areaName'},{name:'value'}]);for(var i=0;i<bookmarks.length;i++){var rec=new BookmarkRecord({areaName:bookmarks[i].name,value:Carmen.Util.convertContextBBtoolBounds(bookmarks[i].BoundingBox)});store.add(rec);}},CLASS_NAME:"Carmen.Control.FavoriteAreas"});Carmen.Control.FavoriteAreas.defaultName='zone_';Carmen.Control.FavoriteAreas.uniqueId=0;Carmen.Control.FavoriteAreas.getUniqueId=function(){Carmen.Control.FavoriteAreas.uniqueId++;return(Carmen.Control.FavoriteAreas.uniqueId-1);};Carmen.Control.FavoriteAreas.emptyFavoriteAreaTxt='Zones favorites';Carmen.Control.FavoriteAreas.newFavoriteAreaTxt='Nouvelle zone';Carmen.Layer.WMSGroup=new OpenLayers.Class(OpenLayers.Layer.WMS,{subLayers:[],mainLayers:'',wmsName:'',initialize:function(options){OpenLayers.Layer.WMS.prototype.initialize.apply(this,arguments);this.mainLayers=this.params.LAYERS;this.subLayers=[];if(!this.wmsName&&this.mainLayers&&this.mainLayers.length>0)
this.wmsName=this.mainLayers;if(this.mainLayers.length==0&&this.wmsName)
this.mainLayers=this.wmsName;},hasSubLayers:function(){return this.subLayers.length>0;},addSubLayer:function(layerName,visible,wmsName){var info=this.getSubLayerInfo(layerName);if(info==null){this.subLayers.push({name:layerName,visible:visible,wmsName:wmsName,index:this.subLayers.length});}
else{info.visible=visible;info.wmsName=wmsName;}
var layerVisibility=false;for(i=0;i<this.subLayers.length;i++){layerVisibility=layerVisibility||this.subLayers[i].visible;}
this.setVisibility(layerVisibility);},moveSubLayer:function(layerName,index){var info=this.getSubLayerInfo(layerName);if(info!=null){var toBeUpdated=this.subLayers.splice(info.index+1);this.subLayers.pop();for(var i=0;i<toBeUpdated.length;i++)
toBeUpdated[i].index=toBeUpdated[i].index-1;this.subLayers=this.subLayers.concat(toBeUpdated);var toBeUpdated=this.subLayers.splice(index);info.index=index;this.subLayers.push(info);for(var i=0;i<toBeUpdated.length;i++)
toBeUpdated[i].index=toBeUpdated[i].index+1;this.subLayers=this.subLayers.concat(toBeUpdated);}},clone:function(obj){if(obj==null){obj=new Carmen.Layer.WMSGroup(this.name,this.url,this.params,this.options);}
obj=OpenLayers.Layer.Grid.prototype.clone.apply(this,[obj]);obj.setVisibility(this.visibility);obj.setIsBaseLayer(this.isBaseLayer);obj.subLayers=[].concat(this.subLayers);obj.mainLayers=this.mainLayers;obj.displayMode=this.DISPLAY_MAP;obj.qstring='';obj.qitem='';return obj;},split:function(index){var res=[];if(index>this.subLayers.length){res.push(this);res.push(null);}
else if(index<0){this.subLayers=[];newLayer=this.clone();res.push(this);res.push(newLayer);}
else{var newLayer=this.clone();newLayer.subLayers=new Array();var subLayers2=new Array();for(var i=0;i<this.subLayers.length;i++){if(i<=index)
subLayers2.push(this.subLayers[i]);else
newLayer.subLayers.push(this.subLayers[i]);}
delete this.subLayers;this.subLayers=subLayers2;for(var i=0;i<this.subLayers.length;i++){this.subLayers[i].index=i;}
for(var i=0;i<newLayer.subLayers.length;i++){newLayer.subLayers[i].index=i;}
res.push(this);res.push(newLayer);}
return res;},getSubLayerInfo:function(layerName){var i=0;while(i<this.subLayers.length&&this.subLayers[i].name!=layerName){i++;}
return(i<this.subLayers.length)?this.subLayers[i]:null;},setSubLayerVisibility:function(layerName,isVisible){var subLayer=this.getSubLayerInfo(layerName);if(subLayer!=null)
subLayer.visible=isVisible;var layerVisibility=false;for(i=0;i<this.subLayers.length;i++){layerVisibility=layerVisibility||this.subLayers[i].visible;}
this.setVisibility(layerVisibility);this.display(layerVisibility);this.redraw();if(this.map!=null){this.map.events.triggerEvent("changelayer",{layer:this,property:"visibility"});}
this.events.triggerEvent("visibilitychanged");},getVisibility:function(layerName){var vis=true;if(layerName==null||layerName==this.mainLayers)
vis=OpenLayers.Layer.WMS.prototype.getVisibility.apply(this,[]);else
vis=this.getSubLayerVisibility(layerName);return vis;},getSubLayerVisibility:function(layerName){var subLayer=this.getSubLayerInfo(layerName);return subLayer.visible;},_getLayersParam:function(){var str=this.mainLayers;for(var i=0;i<this.subLayers.length;i++){if(this.subLayers[i].visible){str=str+","+this.subLayers[i].wmsName;}}
str=(str.length>0)&&(str.charAt(0)==',')?str.slice(1):str;return str;},redraw:function(){this.params.LAYERS=this._getLayersParam();var redrawn=OpenLayers.Layer.WMS.prototype.redraw.apply(this,arguments);return redrawn;},getURL:function(bounds){bounds=this.adjustBounds(bounds);var imageSize=this.getImageSize();var newParams={'BBOX':this.encodeBBOX?bounds.toBBOX():bounds.toArray(),'WIDTH':imageSize.w,'HEIGHT':imageSize.h};if(this.projection)
newParams.SRS=this.projection;var requestString=this.getFullRequestString(newParams);return requestString;},getLegendGraphicURL:function(layerName){if(layerName==null||layerName.length==0){layerName=this.params.LAYERS.split(' ')[0];}
if(layerName.length==0){Ext.msg.alert('Problème dans la récupération du caisson de légende de couches WMS.');return null;}
var getMapParams=Carmen.Util.clone(this.params);delete(this.params['LAYERS']);this.params.LAYER=layerName;this.params.REQUEST='GetLegendGraphic';this.params.EXCEPTIONS='application/vnd.ogc.se_xml';var url=OpenLayers.Layer.HTTPRequest.prototype.getFullRequestString.apply(this,[]);this.params=getMapParams;return url;},getLegendGraphicInfo:function(layerName){if(layerName==null||layerName.length==0){layerName=this.params.LAYERS.split(' ')[0];}
if(layerName.length==0){Ext.msg.alert('Problème dans la récupération du caisson de légende de couches WMS.');return null;}
var getMapParams=Carmen.Util.clone(this.params);delete(this.params['LAYERS']);this.params.LAYER=layerName;this.params.REQUEST='GetLegendGraphic';this.params.EXCEPTIONS='application/vnd.ogc.se_xml';var url=OpenLayers.Layer.HTTPRequest.prototype.getFullRequestString.apply(this,[]);this.params=getMapParams;return url;},getFeatureInfoURL:function(layerName,position,imgSize,mapExtent){if(layerName==null||layerName.length==0){layerName=this.params.LAYERS.split(' ')[0];}
if(layerName.length==0){Ext.msg.alert('Wrong parameters in GetFeatureInfoURL.');return null;}
var getMapParams=Carmen.Util.clone(this.params);mapExtent=this.adjustBounds(mapExtent);var newParams={'BBOX':this.encodeBBOX?mapExtent.toBBOX():mapExtent.toArray(),'LAYERS':layerName,'QUERY_LAYERS':layerName,'REQUEST':'GetFeatureInfo','FEATURE_COUNT':1,'X':position.x,'Y':position.y,'HEIGHT':imgSize.h,'WIDTH':imgSize.w,'INFO_FORMAT':'application/vnd.ogc.gml'};var url=OpenLayers.Layer.HTTPRequest.prototype.getFullRequestString.apply(this,[newParams]);return url;},getFeatureInfoParams:function(layerName,position,imgSize,mapExtent){if(layerName==null||layerName.length==0){layerName=this.params.LAYERS.split(' ')[0];}
if(layerName.length==0){Ext.msg.alert('Wrong parameters in GetFeatureInfoURL.');return null;}
mapExtent=this.adjustBounds(mapExtent);var params=OpenLayers.Util.extend({},this.params);params=OpenLayers.Util.extend(this.params,{'BBOX':mapExtent.toBBOX(),'LAYERS':layerName,'QUERY_LAYERS':layerName,'REQUEST':'GetFeatureInfo','FEATURE_COUNT':1,'X':position.x,'Y':position.y,'HEIGHT':imgSize.h,'WIDTH':imgSize.w,'INFO_FORMAT':'application/vnd.ogc.gml'});return params;},CLASS_NAME:"Carmen.Layer.WMSGroup"});Carmen.Control.Legend=new OpenLayers.Class(OpenLayers.Control,{btn:new Ext.Toolbar.Button({tooltip:'Légende',tooltipType:'title',cls:'x-btn-icon cmn-tool-legend',enableToggle:false,disabled:false}),win:new Ext.Window({layout:'fit',width:300,height:300,plain:true,title:'Légende',modal:false,autoDestroy:true,resizable:true,closeAction:'hide',shadow:false}),mainPanel:new Ext.Panel({id:'mainPanel',header:false,border:false,margins:'0 0 0 0',resizeEl:'layerTreeLegendPanel',layout:'fit'}),layerTreeLegendPanel:new Ext.tree.TreePanel({id:'layerTreeLegendPanel',margins:'5 0 5 5',useArrows:false,animate:false,border:false,autoScroll:true,fitToFrame:true,rootVisible:false,root:{text:'root'}}),layerTreeManager:null,layerTree:null,visible:true,initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,arguments);},setMap:function(map){OpenLayers.Control.prototype.setMap.apply(this,arguments);if(this.visible){this.btn.addListener('click',Carmen.Util.buildExt2olHandlerButton(this));var tb=this.map.app.ui.getTopToolBar();tb.addItem(this.btn);this.map.app.ui.doLayout();}},trigger:function(){if(this.getLayerTreeManager==null){Ext.MessageBox.alert("Warning","The control "+
this.CLASS_NAME+" requires the LayerTreeManager control to work.");return null;}
this.showWindow();},showWindow:function(){this.layerTree=this.getLayerTreeManager().getLayerTree().clone(this.transformNodeLegend);if(!this.win.rendered){this.mainPanel.add(this.layerTreeLegendPanel);this.win.add(this.mainPanel);this.layerTreeLegendPanel.setRootNode(this.layerTree);this.win.doLayout();this.win.show();}
else{this.layerTreeLegendPanel.getRootNode().destroy();this.layerTreeLegendPanel.setRootNode(this.layerTree);this.layerTreeLegendPanel.getRootNode().render();}
if(!this.win.isVisible()){this.win.show();}
this.layerTree.filter(this.filterNodeLayerVisible);},getLayerTreeManager:function(){if(this.layerTreeManager==null){var controls=this.map.getControlsByClass('Carmen.Control.LayerTreeManager');this.layerTreeManager=controls.length==0?null:controls[0];}
return this.layerTreeManager;},transformNodeLegend:function(atts){var cloneAtts=Carmen.Util.clone(atts);cloneAtts.checked='',cloneAtts.cls='none';cloneAtts.infoData=null;cloneAtts.listeners={};cloneAtts.expanded=true;cloneAtts.hasBottomElt=false;cloneAtts.rightIcon=null;cloneAtts.uiProvider=(atts.text==Carmen.Control.LayerTreeManager.TREE_NODE_ROOT_LABEL)?Carmen.RootTreeNodeUI:Carmen.TreeNodeUI;return cloneAtts;},filterNodeLayerVisible:function(node){var res=true;res=('type'in node.attributes)&&((node.attributes.type==Carmen.Control.LayerTreeManager.NODE_GROUP&&node.hasChildNodes()&&node.getDepth()>0)||(node.attributes.type==Carmen.Control.LayerTreeManager.NODE_LAYER&&((node.attributes.OlLayer.hasSubLayers()&&node.attributes.OlLayer.getSubLayerVisibility(node.attributes.layerName))||(!node.attributes.OlLayer.hasSubLayers()&&node.attributes.OlLayer.getVisibility()))&&node.attributes.visible==true)||(node.attributes.type==Carmen.Control.LayerTreeManager.NODE_CLASS));return res;},toHTML:function(staticRendering){this.showWindow();this.win.hide();if(staticRendering!=null&&staticRendering)
this.layerTree.cascade(this.toStaticNodeUI);return this.layerTree.getUI().wrap;},toStaticNodeUI:function(n){var ui=n.getUI();var elt=Ext.fly(ui.ecNode);if(elt==null)
return true;var cls='';var newClass='';if(elt.hasClass('x-tree-elbow-minus')){cls='x-tree-elbow-minus';newClass='x-tree-elbow';}
else if(elt.hasClass('x-tree-elbow-plus')){cls='x-tree-elbow-plus';newClass='x-tree-elbow';}else if(elt.hasClass('x-tree-elbow-end-minus')){cls='x-tree-elbow-end-minus';newClass='x-tree-elbow-end';}
else if(elt.hasClass('x-tree-elbow-end-plus')){cls='x-tree-elbow-end-plus';newClass='x-tree-elbow-end';};if(cls!=''){Ext.fly(ui.ecNode).replaceClass(cls,newClass);ui.ecc=ui.ecNode.className;}
var elt=document.createElement('span');elt.className="x-tree-node-anchor";Ext.fly(elt).insertFirst(ui.anchor.firstChild);Ext.fly(ui.anchor).replaceWith(elt);ui.wrap.style.cursor='default';c=ui.wrap.firstChild;while(c!=null){c.style.cursor='default';c=Ext.fly(c).next(null,true);}
return true;},renderHTMLto:function(elt){this.layerTree=this.getLayerTreeManager().getLayerTree().clone(this.transformNodeLegend);this.layerTreeLegendPanel.setRootNode(this.layerTree);this.layerTree.filter(function(node){var res=true;res=('type'in node.attributes)&&((node.attributes.type==Carmen.Control.LayerTreeManager.NODE_GROUP&&node.hasChildNodes()&&node.getDepth()>0)||(node.attributes.type==Carmen.Control.LayerTreeManager.NODE_LAYER&&node.attributes.initialChecked&&node.attributes.visible==true)||(node.attributes.type==Carmen.Control.LayerTreeManager.NODE_CLASS));return res;});this.layerTreeLegendPanel.render(elt);},CLASS_NAME:"Carmen.Control.Legend"});Carmen.ApplicationUI=Ext.extend(Ext.Viewport,{headerPanel:new Ext.Panel({region:'north',id:'header',fitToFrame:true,height:100,border:false,margins:'0 0 0 0'}),footerPanel:new Ext.Panel({region:'south',id:'footer',split:false,height:10,border:true,margins:'0 0 0 0'}),navigationPanel:new Ext.Panel({region:'west',id:'navigationPanel',title:' ',split:true,width:260,minSize:175,maxSize:400,collapsible:true,containerScroll:true,fitToFrame:true,margins:'5 0 5 5',cmargins:'5 5 5 5',layout:'ux.row',layoutConfig:{titleCollapse:false,animate:true,anchor:'100%'},hideMode:'offsets',hidden:true}),mainPanel:new Ext.Panel({region:'center',id:'mainPanel',fitToFrame:true,margins:'5 5 5 0',tbar:[],bbar:[],layout:'absolute'}),displayHeader:false,displayNavPanel:true,constructor:function(ctx,options){defaultConfig={layout:'border',items:[]};this.displayHeader=(ctx!=null)&&(Ext.value(ctx.getGeneralConfig('display_header'),"OFF",false)=="ON");if(this.displayHeader){var srcBanner=window.CARMEN_URL_SERVER_FRONT+window.IHMUrl+"BannerModels/"+Ext.value(ctx.mdataMap.header_model,'bandeau.html',false);var eltBanner=new Ext.ux.IFrameComponent({id:'banner',name:'banner',url:srcBanner});this.headerPanel.add(eltBanner);defaultConfig.items.push(this.headerPanel);}
defaultConfig.items.push(this.navigationPanel);defaultConfig.items.push(this.mainPanel);Ext.apply(this,options,defaultConfig);Carmen.ApplicationUI.superclass.constructor.apply(this,arguments);this.navigationPanel.setVisible(this.displayNavPanel);this.getTopToolBar().getEl().applyStyles("overflowX:auto");this.getBottomToolBar().getEl().applyStyles("overflowX:auto");if(Ext.isIE){this.getMainPanel().on('resize',function(){Carmen.Util.forceScrollOnToolbarInIE(this.getTopToolBar());Carmen.Util.forceScrollOnToolbarInIE(this.getBottomToolBar());},this);}
this.doLayout();},getMapDiv:function(){return this.mainPanel.body;},getTopToolBar:function(){return this.mainPanel.getTopToolbar();},getBottomToolBar:function(){return this.mainPanel.getBottomToolbar();},getNavigationPanel:function(){return this.navigationPanel;},getMainPanel:function(){return this.mainPanel;},doLayout:function(){Carmen.ApplicationUI.superclass.doLayout.apply(this,arguments);this.getMainPanel().updateBox(this.getMainPanel().getBox());this.updateBox(this.getBox());},getScreenResolution:function(){var testDiv=document.createElement("div");testDiv.style.position='absolute';testDiv.style.width='1in';testDiv.style.padding='0px';testDiv.id="testDiv";this.doLayout();this.getMapDiv().appendChild(testDiv);return testDiv.offsetWidth;}});Carmen.ApplicationUI.CLASS_NAME="Carmen.ApplicationUI";Proj4js.defs["EPSG:32738"]="+proj=utm +zone=38 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs";Carmen.Control.Print=new OpenLayers.Class(OpenLayers.Control,{layoutModelsData:[['modele1.tpl','Légende et carte de situation à droite'],['modele2.tpl','Légende, carte de situation et copyright à gauche'],['modele3.tpl','Grandes légendes'],['modele4.tpl','Légende à gauche, carte de siuation au dessus']],btn:new Ext.Toolbar.Button({tooltip:'Imprimer',tooltipType:'title',cls:'x-btn-icon cmn-tool-printnav',enableToggle:true,toggleGroup:'mainMapControl',disabled:false}),win:new Ext.Window({layout:'anchor',width:400,autoHeight:true,plain:true,id:"winPrint",title:'Impression',modal:false,autoDestroy:true,resizable:true,closeAction:'hide',shadow:false}),printPanel:new Ext.FormPanel({id:'print',autoScroll:true,fitToFrame:true,labelWidth:75,bodyStyle:'padding:5px 5px 0; color: #000000;',labelStyle:'color: #000000;',url:'/services/GetHTML/getHTML.php',items:[{xtype:"field",fieldLabel:'Titre',name:'title',value:"",width:'270'},{xtype:"textarea",fieldLabel:'Commentaire',name:'comment',width:'270'},{xtype:'radiogroup',columns:1,fieldLabel:'Qualité',name:'quality',items:[{boxLabel:'Moyenne (Firefox 2.x)',name:'quality',inputValue:'medium'},{boxLabel:'Bonne (Autres navigateurs)',inputValue:'high',name:'quality',checked:true}]},{xtype:'radiogroup',columns:1,fieldLabel:'Traitement de la carte',name:'typeExport',items:[{boxLabel:'Echelle conservée',name:'typeExport',inputValue:'0',checked:true},{boxLabel:'Emprise conservée',name:'typeExport',inputValue:'1'}]},{xtype:"hidden",id:"legend",name:"legend",value:"",hidden:true,hiddenLabel:true},{xtype:"hidden",name:"contextJs",value:"",hidden:true,hiddenLabel:true},{xtype:"hidden",name:"mapWidth",value:"",hidden:true,hiddenLabel:true}],buttons:[{id:'submitPrint',text:'Prévisualiser'}]}),initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,arguments);},initLayoutCombo:function(context){if(context.mdataMap.layoutModels!="undefined"&&context.mdataMap.layoutModels!=""){var tabModels=(Url.decode(context.mdataMap.layoutModels)).split(";");if(tabModels.length>0){this.layoutModelsData=[];for(var i=0;i<tabModels.length;i++){var tabInfoModel=tabModels[i].split("@");this.layoutModelsData.push([tabInfoModel[0],tabInfoModel[1]]);}}}
var layoutCombo=new Ext.form.ComboBox({tpl:'<tpl for="."><div ext:qtip="{desc}" class="x-combo-list-item">{desc}</div></tpl>',typeAhead:true,editable:false,mode:'local',triggerAction:'all',emptyText:'Modèles de mise en page',selectOnFocus:true,width:280,displayField:'desc',loadingText:'Chargement',valueField:'modele',name:'modeleLayout',hiddenName:'modele',fieldLabel:'Modèle',store:new Ext.data.SimpleStore({fields:['modele','desc'],data:[]})});this.printPanel.add(layoutCombo);layoutCombo.getStore().loadData(this.layoutModelsData);layoutCombo.setValue(this.layoutModelsData[0][0]);},setMap:function(map){OpenLayers.Control.prototype.setMap.apply(this,arguments);this.initLayoutCombo(this.map.app.context);this.btn.addListener('toggle',Carmen.Util.buildExt2olHandlerToggle(this));var tb=this.map.app.ui.getTopToolBar();tb.addItem(this.btn);var control=this;this.win.on('hide',function(w){control.btn.toggle(false);},this.win);this.map.app.ui.doLayout();},activate:function(){OpenLayers.Control.prototype.activate.apply(this,arguments);this.map.toolTipDeactivate();this.showWindow();},deactivate:function(){OpenLayers.Control.prototype.deactivate.apply(this,arguments);if(this.win.rendered)
this.win.hide();this.map.toolTipActivate();},showWindow:function(){var win=this.win;if(!this.win.rendered){this.win.add(this.printPanel);var submitBtn=Ext.getCmp('submitPrint');submitBtn.on('click',function(btn,evt){var form=Ext.getCmp('print').getForm();form.getEl().dom.target='iFrameHtml';form.getEl().dom.action='/services/GetHTML/getHTML.php';if(!form.isValid())
Ext.Msg.alert('Impression','Erreur');else{var winPrevisu=new Ext.Window({layout:'anchor',plain:true,title:'Prévisualisation',modal:false,width:Math.min(document.body.clientWidth-100,1220),height:Math.min(document.body.clientHeight-100,790),autoDestroy:true,resizable:true,closeAction:'close',shadow:false,items:[new Ext.ux.IFrameComponent({url:"/blank.html",name:"iFrameHtml",width:Math.min(document.body.clientWidth-100,1220)-20,height:Math.min(document.body.clientHeight-100,790)-25})]});winPrevisu.show();form.getEl().dom.submit();}},submitBtn);this.win.doLayout();}
if(!this.win.isVisible()){this.win.show();var form=this.printPanel.getForm();var app=this.map.app;var ctx=app.context;form.setValues({"title":(ctx.getTitle()),"mapWidth":app.map.size.w,"legend":app.map.getLegend().toHTML(true).innerHTML,"contextJs":Ext.util.JSON.encode(app.updateContext(true))});}},CLASS_NAME:"Carmen.Control.Print"});Proj4js.defs["EPSG:27561"]="+proj=lcc +lat_1=49.50000000000001 +lat_0=49.50000000000001 +lon_0=0 +k_0=0.999877341 +x_0=600000 +y_0=200000 +a=6378249.2 +b=6356515 +towgs84=-168,-60,320,0,0,0,0 +pm=paris +units=m +no_defs";Carmen.Control.ZoomToPlace=new OpenLayers.Class(OpenLayers.Control,{extentArea:"",zoomToPlacePanel:new Ext.FormPanel({title:'Localiser',collapsible:true,margins:'5 0 5 5',itemCls:'areasClass',labelWidth:75,autoHeight:true,buttons:[{id:'btn_zoomToPlace',text:'localiser'}],listeners:{collapse:function(p){p.ownerCt.doLayout();},expand:function(p){p.ownerCt.doLayout();}}}),combos:[],setMap:function(map){OpenLayers.Control.prototype.setMap.apply(this,arguments);for(var i=0;i<this.configs.length;i++){var combo=Carmen.Control.ZoomToPlace.buildCombo(this.configs[i],i);combo['config']=this.configs[i];combo.addListener('change',function(cmb,newVal,oldVal){});if(this.configs[i].linkedCombo){combo.addListener('select',function(cmb,record,index){this.extentArea=record.data.extent;},this);this.combos[this.configs[i].linkedCombo-1].addListener('select',Carmen.Control.ZoomToPlace.buildListenerLink(combo),this);}else{combo.addListener('select',function(cmb,record,index){this.extentArea=record.data.extent;},this);}
this.combos.push(combo);this.zoomToPlacePanel.add(combo);}
var btn=this.zoomToPlacePanel.buttons[0];btn.addListener('click',function(){var tabExtent=this.extentArea.split(",");this.map.zoomToExtent(new OpenLayers.Bounds(tabExtent[0],tabExtent[1],tabExtent[2],tabExtent[3]));},this);var navPanel=this.map.app.ui.getNavigationPanel();navPanel.add(this.zoomToPlacePanel);this.map.app.ui.doLayout();for(var i=0;i<this.combos.length;i++){this.combos[i].getEl().dom.size=18;}},loadContent:function(){for(var i=0;i<this.combos.length;i++){if(!this.combos[i]['config'].linkedCombo){this.combos[i].getStore().load();}}},CLASS_NAME:"Carmen.Control.ZoomToPlace"});Carmen.Control.ZoomToPlace.buildCombo=function(config,number){var combo=new Ext.form.ComboBox({tpl:'<tpl for="."><div ext:qtip="{name}" class="x-combo-list-item">{name}</div></tpl>',fieldLabel:config.labelText,loadingText:'Chargement',emptyText:'Saisir les premières lettres',displayField:'name',valueField:'name',typeAhead:true,typeAheadDelay:250,forceSelection:true,mode:'local',triggerAction:'all',editable:true,minChars:1,queryDelay:250,width:'125px',xtype:'combo',id:'combo'+number.toString(),store:Carmen.Control.ZoomToPlace.buildStore(config)});return combo;};Carmen.Control.ZoomToPlace.buildStore=function(config){var store=new Ext.data.Store({proxy:new Ext.data.ScriptTagProxy({url:config.providerUrl}),baseParams:config.providerBaseParams,reader:new Ext.data.JsonReader({id:'ID',totalProperty:'totalCount',root:'Names'},[{name:'extent'},{name:'id'},{name:'name'}])});return store;};Carmen.Control.ZoomToPlace.buildListenerLink=function(cbSlave){return function(cmb,record,index){var linkFieldName=cbSlave.config.linkedFieldName
var newBaseParams=OpenLayers.Util.extend({},cbSlave.getStore().baseParams);newBaseParams=OpenLayers.Util.extend(newBaseParams,cbSlave.config.providerLinkParams);newBaseParams[linkFieldName]=record.data.id;cbSlave.getStore().baseParams=newBaseParams;cbSlave.clearValue();cbSlave.getStore().load();this.extentArea=record.data.extent;};};Carmen.Control.AddWMS=new OpenLayers.Class(OpenLayers.Control,{btn:new Ext.Toolbar.Button({tooltip:'Ajouter une couche WMS',tooltipType:'title',cls:'x-btn-icon cmn-tool-addwms',enableToggle:true,toggleGroup:'mainMapControl',disabled:false}),win:null,setMap:function(map){OpenLayers.Control.prototype.setMap.apply(this,arguments);this.btn.addListener('toggle',Carmen.Util.buildExt2olHandlerToggle(this));var tb=this.map.app.ui.getTopToolBar();tb.addItem(this.btn);this.map.app.ui.doLayout();},activate:function(){OpenLayers.Control.prototype.activate.apply(this,arguments);this.map.toolTipDeactivate();this.showWindow();},deactivate:function(){OpenLayers.Control.prototype.deactivate.apply(this,arguments);if(this.win&&this.win.rendered)
this.win.hide();this.map.toolTipActivate();},showWindow:function(){this.win=new Ext.Window({layout:'fit',width:550,plain:true,title:"Ajout de couches WMS",modal:false,x:150,y:100,autoDestroy:true,resizable:true,autoLoad:{url:'/services/AddWMS/addWMS.php',loadingText:'Chargement',params:{mapProjection:this.map.projection,extent:app.map.getExtent().left.toString()+','
+app.map.getExtent().bottom.toString()+','
+app.map.getExtent().right.toString()+','
+app.map.getExtent().top.toString()},method:'GET',scripts:true}});var control=this;this.win.on('hide',function(w){control.btn.toggle(false);},this.win);this.win.show();},CLASS_NAME:"Carmen.Control.AddWMS"});Carmen.Control.AddWMS.addLayerToMap=function(lLayerTitle,lUrlValue,lLayerName,lLayerFormat,lLayerSRS){var mapParams={singleTile:true,isBaseLayer:false,projection:lLayerSRS};if(!app.context.hasLayerWMSC()){mapParams.maxResolution='auto';}
var layer=new Carmen.Layer.WMSGroup(lLayerTitle,lUrlValue,{layers:escape(lLayerName),version:"1.1.1",format:lLayerFormat,transparent:true},mapParams);layer.setVisibility(true);app.map.addLayer(layer);var descs=Carmen.Util.OLWMSGroup2CarmenOWSDesc(layer,app.context.getNextLayerId(),{projection:app.map.projection});var layerIdx=app.context.addLayerDescs(descs);var node=new Ext.tree.TreeNode({text:lLayerTitle,leaf:true,expanded:false,checked:true,icon:layer.getLegendGraphicURL(),iconCls:'cmnLayerTreeLayerNodeIcon',rightIcon:'/IHM/images/delete.gif',rightIconCls:'cmnTreeNodeRightIcon',iconDisplayStrategy:true,uiProvider:Carmen.TreeNodeUI});node.attributes.type=Carmen.Control.LayerTreeManager.NODE_LAYER;node.attributes.OlLayer=layer;node.attributes.visible=true;node.attributes.expanded=false;node.attributes.layerIdx=layerIdx;node.attributes.opacity=1.0;node.attributes.hasBottomElt=true;var layerManager=app.map.getLayerTreeManager();node.addListener('checkchange',function(n,cb_state){var layer=n.attributes.OlLayer;layer.setVisibility(n.attributes.checked);},node);var tree=layerManager.getLayerTree();if(tree.hasChildNodes()){tree.insertBefore(node,tree.childNodes[0]);}
else{tree.appendChild(node);}
node.attributes.layerName=layer.params.LAYERS;node.attributes.visible=true;node.render();rIconDom=node.getUI().getRightIcon();new Ext.ToolTip({target:rIconDom,html:'Supprimer la couche WMS'});var rIconElt=Ext.fly(rIconDom);rIconElt.addListener('click',function(evt){var layer=node.attributes.OlLayer;var map=layer.map;map.removeLayer(layer);node.remove();evt.stopPropagation();return false;});Carmen.Control.LayerTreeManager.addTransparencySliderToNode(node);};Proj4js.defs["EPSG:3312"]="+proj=utm +zone=21 +ellps=intl +towgs84=-186,230,110,0,0,0,0 +units=m +no_defs";Carmen.Layer.MapServerGroup=new OpenLayers.Class(OpenLayers.Layer.MapServer,{subLayers:null,mainLayers:'',displayMode:0,qstring:'',qitem:'',initialize:function(options){OpenLayers.Layer.MapServer.prototype.initialize.apply(this,arguments);this.mainLayers=this.params.LAYERS;this.subLayers=[];this.params.map_imagetype=Ext.isIE6?"gif":this.params.map_imagetype;},hasSubLayers:function(){return this.subLayers.length>0;},addSubLayer:function(layerName,visible){var info=this.getSubLayerInfo(layerName);if(info==null){this.subLayers.push({name:layerName,visible:visible,index:this.subLayers.length});}
else
info.visible=visible;var layerVisibility=false;for(i=0;i<this.subLayers.length;i++){layerVisibility=layerVisibility||this.subLayers[i].visible;}
this.setVisibility(layerVisibility);},moveSubLayer:function(layerName,index){var info=this.getSubLayerInfo(layerName);if(info!=null){var toBeUpdated=this.subLayers.splice(info.index+1);this.subLayers.pop();for(var i=0;i<toBeUpdated.length;i++)
toBeUpdated[i].index=toBeUpdated[i].index-1;this.subLayers=this.subLayers.concat(toBeUpdated);var toBeUpdated=this.subLayers.splice(index);info.index=index;this.subLayers.push(info);for(var i=0;i<toBeUpdated.length;i++)
toBeUpdated[i].index=toBeUpdated[i].index+1;this.subLayers=this.subLayers.concat(toBeUpdated);}},clone:function(obj){if(obj==null){obj=new Carmen.Layer.MapServerGroup(this.name,this.url,this.params,this.options);}
obj=OpenLayers.Layer.Grid.prototype.clone.apply(this,[obj]);obj.setVisibility(this.visibility);obj.setIsBaseLayer(this.isBaseLayer);obj.subLayers=[].concat(this.subLayers);obj.mainLayers=this.mainLayers;obj.displayMode=this.DISPLAY_MAP;obj.qstring='';obj.qitem='';return obj;},split:function(index){var res=[];if(index>this.subLayers.length){res.push(this);res.push(null);}
else if(index<0){this.subLayers=[];newLayer=this.clone();res.push(this);res.push(newLayer);}
else{var newLayer=this.clone();newLayer.subLayers=new Array();var subLayers2=new Array();for(var i=0;i<this.subLayers.length;i++){if(i<=index)
subLayers2.push(this.subLayers[i]);else
newLayer.subLayers.push(this.subLayers[i]);}
delete this.subLayers;this.subLayers=subLayers2;for(var i=0;i<this.subLayers.length;i++){this.subLayers[i].index=i;}
for(var i=0;i<newLayer.subLayers.length;i++){newLayer.subLayers[i].index=i;}
res.push(this);res.push(newLayer);}
return res;},getSubLayerInfo:function(layerName){var i=0;while(i<this.subLayers.length&&this.subLayers[i].name!=layerName){i++;}
return(i<this.subLayers.length)?this.subLayers[i]:null;},setSubLayerVisibility:function(layerName,isVisible){var subLayer=this.getSubLayerInfo(layerName);if(subLayer!=null)
subLayer.visible=isVisible;var layerVisibility=false;for(i=0;i<this.subLayers.length;i++){layerVisibility=layerVisibility||this.subLayers[i].visible;}
this.setVisibility(layerVisibility);this.display(layerVisibility);this.redraw();if(this.map!=null){this.map.events.triggerEvent("changelayer",{layer:this,property:"visibility"});}
this.events.triggerEvent("visibilitychanged");},getSubLayerVisibility:function(layerName){var subLayer=this.getSubLayerInfo(layerName);return subLayer.visible;},getVisibility:function(layerName){var vis=true;if(layerName==null||layerName==this.mainLayers)
vis=OpenLayers.Layer.WMS.prototype.getVisibility.apply(this,[]);else
vis=this.getSubLayerVisibility(layerName);return vis;},_getLayersParam:function(){var str=this.mainLayers;for(var i=0;i<this.subLayers.length;i++){if(this.subLayers[i].visible){str=str+"+"+this.subLayers[i].name;}}
str=(str.length>0)&&(str[0]=='+')?str.slice(1):str;return str;},getURL:function(bounds){var url=null;if(Ext.value(this.map,null)!=null&&this.displayMode==this.DISPLAY_MAP){bounds=this.adjustBounds(bounds);var extent=[bounds.left,bounds.bottom,bounds.right,bounds.top];var imageSize=this.getImageSize();var center=bounds.getCenterLonLat();var scale=this.map.getScale();url=this.getFullRequestString({map_size:[imageSize.w,imageSize.h],imgx:imageSize.w/2,imgy:imageSize.h/2,imgxy:[imageSize.w,imageSize.h],mapxy:[center.lon,center.lat],scaledenom:scale});}
else{url=OpenLayers.Layer.MapServer.prototype.getURL.apply(this,arguments);}
return url;},redraw:function(){this.params.LAYERS=this._getLayersParam();this.params.map_resolution=Carmen.Mapserver_DOTS_PER_INCH;var redrawn=OpenLayers.Layer.MapServer.prototype.redraw.apply(this,arguments);return redrawn;},setDisplayMode:function(mode,qlayer,fid,qfile){switch(mode){case this.DISPLAY_QUERYMAP:this.params.mode='indexquerymap';this.params['QLAYER']=qlayer;this.params['SHAPEINDEX']=fid;delete this.params['QUERYFILE'];delete this.params['TIME'];break;case this.DISPLAY_NQUERYMAP:this.params.mode='nquerymap';this.params['QUERYFILE']=qfile;this.params['TIME']=new Date().getTime();delete this.params['SHAPEINDEX'];delete this.params['QLAYER'];break;case this.DISPLAY_MAP:default:this.params.mode='map';delete this.params['SHAPEINDEX'];delete this.params['QLAYER'];delete this.params['QUERYFILE'];delete this.params['TIME'];break;}
this.displayMode=mode;this.redraw();},DISPLAY_MAP:0,DISPLAY_QUERYMAP:1,DISPLAY_NQUERYMAP:2,CLASS_NAME:"Carmen.Layer.MapServerGroup"});Carmen.Layer.MapServerGroup.DISPLAY_MAP=0;Carmen.Layer.MapServerGroup.DISPLAY_QUERYMAP=1;Carmen.Layer.MapServerGroup.DISPLAY_NQUERYMAP=2;Carmen.TreeNodeUI=Ext.extend(Ext.tree.TreeNodeUI,{labelVisible:true,constructor:function(config){Ext.apply(this,{});Carmen.TreeNodeUI.superclass.constructor.apply(this,arguments);},renderElements:function(e,j,i,k){this.indentMarkup=e.parentNode?e.parentNode.ui.getChildIndent():"";var f=typeof j.checked=="boolean";var c=j.href?j.href:Ext.isGecko?"":"#";var d=['<li class="x-tree-node" style="clear:both;">','<div ext:tree-node-id="',e.id,'" class="x-tree-node-el x-tree-node-leaf x-unselectable ',j.cls,'" unselectable="on" style="clear:both;">','<span class="x-tree-node-indent">',this.indentMarkup,"</span>",'<img src="',this.emptyIcon,'" class="x-tree-ec-icon x-tree-elbow" />',f?('<input class="x-tree-node-cb cmnLayerTreeNodeCb" type="checkbox" '+(j.checked?'checked="checked" />':"/>")):"",'<img src="',j.icon||this.emptyIcon,'" class="x-tree-node-icon cmnLayerTreeNodeIcon',(j.icon?" x-tree-node-inline-icon":""),(j.iconCls?" "+j.iconCls:""),'" unselectable="on" />','<a hidefocus="on" class="x-tree-node-anchor" href="',c,'" tabIndex="1" ',j.hrefTarget?' target="'+j.hrefTarget+'"':"",'><span unselectable="on">',this.labelVisible?e.text:'',"</span></a>",j.rightIcon?'<img src="'+j.rightIcon+'" class="x-tree-node-inline-icon '+
(j.rightIconCls?j.rightIconCls+'"':'"')+'unselectable="on" />':'',j.hasBottomElt?'<div style="clear:both;"></div>'+'<div style="display:inline; float:left;">'+'<span class="x-tree-node-indent">'+
this.indentMarkup+"</span>"+'<img src="'+
this.emptyIcon+'" class="x-tree-ec-icon x-tree-elbow" />'+'</div>'+'<div id="'+e.id+'_ext" style="display:inline; float:left;" ></div>':'',"</div>",'<ul class="x-tree-node-ct" style="display:none;clear:both;"></ul>',"</li>"].join("");var b;if(k!==true&&e.nextSibling&&(b=e.nextSibling.ui.getEl())){this.wrap=Ext.DomHelper.insertHtml("beforeBegin",b,d)}else{this.wrap=Ext.DomHelper.insertHtml("beforeEnd",i,d)}
this.elNode=this.wrap.childNodes[0];this.ctNode=this.wrap.childNodes[1];var h=this.elNode.childNodes;this.indentNode=h[0];this.ecNode=h[1];var g=2;if(f){this.checkbox=h[g];this.checkbox.defaultChecked=this.checkbox.checked;g++;}
this.iconNode=h[g];g++;this.anchor=h[g];this.textNode=this.anchor.firstChild;g++;if(j.rightIcon)
this.rightIconNode=h[g];if(j.iconDisplayStrategy){var iconElt=Ext.fly(this.iconNode);iconElt.addListener('load',function(){var iconElt=Ext.fly(this.getIconEl());var imgDom=iconElt.dom;imgDom.style.display='';if(imgDom.width>Carmen.Util.WMS_FULL_LEGEND_MIN_WIDTH||imgDom.height>Carmen.Util.WMS_FULL_LEGEND_MIN_HEIGHT){this.hideLabel();}},this);}
var iconElt=Ext.fly(this.iconNode);iconElt.addListener('error',function(){var iconElt=Ext.fly(this.getIconEl());var imgDom=iconElt.dom;imgDom.style.display='none';},this);},getCheckboxEl:function(){return this.ckeckbox;},getRightIcon:function(){return this.rightIconNode;},hideLabel:function(){this.labelVisible=false;if(this.textNode)
this.textNode.innerHTML='';},showLabel:function(){this.labelVisible=true;if(this.textNode)
this.textNode.innerHTML=this.node.attributes.text;}});Carmen.RootTreeNodeUI=Ext.extend(Carmen.TreeNodeUI,{render:function(){if(!this.rendered){var targetNode=this.node.ownerTree.innerCt.dom;this.node.expanded=true;targetNode.innerHTML='<div class="x-tree-root-node"></div>';this.wrap=this.ctNode=targetNode.firstChild;}},collapse:Ext.emptyFn,expand:Ext.emptyFn});Proj4js.defs["EPSG:2987"]="+proj=utm +zone=21 +ellps=clrk66 +towgs84=30,430,368,0,0,0,0 +units=m +no_defs";Proj4js.defs["EPSG:2973"]="+proj=utm +zone=20 +ellps=intl +units=m +no_defs";Proj4js.defs["EPSG:27582"]="+proj=lcc +lat_1=46.8 "+"+lat_0=46.8 +lon_0=-2.33722917 +k_0=0.99987742 "+"+x_0=600000 +y_0=2200000 +a=6378249.2 +b=6356515 "+"+towgs84=-168,-60,320,0,0,0,0 +pm=paris +units=m "+"+no_defs";Proj4js.defs["EPSG:3170"]="+proj=utm +zone=58 +south +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs";Ext.ux.SliderTip=Ext.extend(Ext.Tip,{minWidth:10,offsets:[0,-10],init:function(slider){slider.on('dragstart',this.onSlide,this);slider.on('drag',this.onSlide,this);slider.on('dragend',this.hide,this);slider.on('destroy',this.destroy,this);},onSlide:function(slider){this.show();this.body.update(this.getText(slider));this.doAutoWidth();this.el.alignTo(slider.thumb,'b-t?',this.offsets);},getText:function(slider){return slider.getValue();}});Proj4js.defs["EPSG:27583"]="+proj=lcc +lat_1=44.10000000000001 +lat_0=44.10000000000001 +lon_0=0 +k_0=0.999877499 +x_0=600000 +y_0=3200000 +a=6378249.2 +b=6356515 +towgs84=-168,-60,320,0,0,0,0 +pm=paris +units=m +no_defs";Proj4js.defs["EPSG:4625"]="+proj=longlat +ellps=intl +no_defs";Proj4js.defs["EPSG:27571"]="+proj=lcc +lat_1=49.50000000000001 +lat_0=49.50000000000001 +lon_0=0 +k_0=0.999877341 +x_0=600000 +y_0=1200000 +a=6378249.2 +b=6356515 +towgs84=-168,-60,320,0,0,0,0 +pm=paris +units=m +no_defs";Carmen.Control.ScaleChooser=new OpenLayers.Class(OpenLayers.Control,{scaleValue:[],scaleDenoms:['2000000','1000000','500000','250000','200000','150000','100000','90000','80000','70000','60000','50000','40000','30000','25000','20000','15000','10000','9000','8000','7000','6000','5000','4000','3000','2000','1000'],scaleBox:new Ext.form.ComboBox({typeAhead:true,mode:'local',triggerAction:'all',emptyText:'Zoomer à l\'échelle',selectOnFocus:true,width:135,displayField:'value',loadingText:'Chargement',valueField:'scale',editable:true,store:new Ext.data.SimpleStore({fields:['scale','value'],data:[]})}),setMap:function(map){OpenLayers.Control.prototype.setMap.apply(this,arguments);this.updateScaleValues(this.scaleDenoms);this.scaleBox.getStore().loadData(this.scaleValue);var tb=this.map.app.ui.getTopToolBar();tb.addItem(this.scaleBox);this.scaleBox.addListener('select',function(combo,record,index){if(index>0){map.zoomToScale(parseFloat(record.data.scale),true);}
else
map.zoomToMaxExtent();});this.map.app.ui.doLayout();this.map.events.register('zoomend',this,this.update);},update:function(){var mapScale=this.map.getScale();var i=1;var found=false;while(i<this.scaleValue.length&&!found){var scale=parseFloat(this.scaleValue[i][0]);found=mapScale>scale;i++;}
i--;if(found&&(i>1))
i=((parseFloat(this.scaleValue[i-1][0])-mapScale)<mapScale-parseFloat(this.scaleValue[i][0]))?i-1:i;this.scaleBox.setValue(this.scaleValue[i][0]);},updateScaleValues:function(scaleDenoms){this.scaleValue=[['maxExtentScale','Emprise Maximale']];for(var i=0;i<scaleDenoms.length;i++){this.scaleValue.push([scaleDenoms[i],Carmen.SpecialChars["around"]+
Carmen.Util.scaleTextFormater(scaleDenoms[i])]);}
this.scaleBox.getStore().removeAll();this.scaleBox.getStore().loadData(this.scaleValue);}});Carmen.Application=new OpenLayers.Class({ui:null,map:null,context:null,initialize:function(jsonContext){OpenLayers.DOTS_PER_INCH=Carmen.DOTS_PER_INCH;OpenLayers.Util.onImageLoadErrorColor="transparent";Proj4js.libPath=CARMEN_URL_SERVER_FRONT+"/IHM/JavaScript/proj4js/lib/";Ext.apply(Ext.form.VTypes,{owsContext:function(v){return/^.*\.(ows)$/.test(v);},owsContextText:'Seuls les fichiers de contexte ows sont autorisés'});if(jsonContext!=null){this.context=new Carmen.JSONContext(jsonContext);}
if(this.context!=null){var displayNavPanel=this.context.isToolActiv('referenceMap')||this.context.isToolActiv('zoomToPlace')||this.context.isToolActiv('legend');this.ui=new Carmen.ApplicationUI(this.context,{displayNavPanel:displayNavPanel});this.loadContext(this.context);this.zoomToInitialExtent();}},initMap:function(config){this.map=new Carmen.Map(this.ui.getMapDiv().id,config);this.map.app=this;return this.map;},getMap:function(){if(this.map==null){this.initMap([]);}
return this.map;},zoomToInitialExtent:function(){var initialExtent=this.context.getExtent();var adjusted=false;var urlParams=Ext.urlDecode(window.location.href);var extent=Ext.value(urlParams.extent,null,false);var object=Ext.value(urlParams.object,null,false);if(extent==null&&object!=null){layername=object.split(';')[0];var layerDesc=this.context.getLayerDescFromMdataValue('LAYER_TITLE',layername);if(layerDesc!=null){var minScale=Ext.value(layerDesc.MinScaleDenominator,null,false);var maxScale=Ext.value(layerDesc.MaxScaleDenominator,null,false);if(minScale!=null&&minScale>0.0&&maxScale!=null&&maxScale>0.0){adjusted=true;this.map.zoomToSuitableExtent(initialExtent,minScale,maxScale);}}}
if(!adjusted)
this.map.zoomToExtent(initialExtent);},loadContext:function(jsOws){var ctx=this.context;var mapOptions={maxExtent:ctx.getMaxExtent(),projection:ctx.getProjection(),maxResolution:'auto',fractionalZoom:true,numZoomLevels:128,allOverlays:true,units:ctx.getProjectionUnits(),zoomOutsideMaxExtent:true,controls:[]};if(ctx.hasLayerWMSC()){mapOptions.fractionalZoom=false;mapOptions.numZoomLevels=null;mapOptions.maxResolution=null;mapOptions.resolutions=Carmen.Util.WMSC_RESOLUTIONS;}
this.initMap(mapOptions);var title=ctx.getTitle();document.title=title;var map=this.map;map.addControl(new OpenLayers.Control.Navigation({'zoomWheelEnabled':true}));if(ctx.isToolActiv('fitall'))
map.addControl(new Carmen.Control.ZoomFitAll());if(ctx.isToolActiv('zoom')){map.addControl(new Carmen.Control.ZoomIn());map.addControl(new Carmen.Control.ZoomOut());map.addControl(new Carmen.Control.ZoomHistory({displayConfig:Carmen.Control.ZoomHistory.PREV_BTN}));}
if(ctx.isToolActiv('pan')){map.addControl(new Carmen.Control.DragPan());map.addControl(new Carmen.Control.PanArrows());}
if(ctx.isToolActiv('info')){map.addControl(new Carmen.Control.Info(window.CARMEN_URL_SERVER_FRONT+'/services/GetInformation/index.php',window.mapfile));map.addControl(new Carmen.Control.InfoURL(window.CARMEN_URL_SERVER_FRONT+'/services/GetInformation/index.php',window.mapfile));}
var legendControl=new Carmen.Control.Legend({visible:ctx.isToolActiv('symbology')});map.addControl(legendControl);if(ctx.isToolActiv('measure'))
map.addControl(new Carmen.Control.Measure());if(ctx.isToolActiv('refresh'))
map.addControl(new Carmen.Control.Refresh());var controlScaleChooser=null;if(ctx.isToolActiv('scale')){controlScaleChooser=new Carmen.Control.ScaleChooser();map.addControl(controlScaleChooser);}
if(ctx.isToolActiv('geobookmark')){geoBookmarkConfig=ctx.getFavoriteAreas();map.addControl(new Carmen.Control.FavoriteAreas(geoBookmarkConfig));}
if(ctx.isToolActiv('context')){map.addControl(new Carmen.Control.ContextManager(window.CARMEN_URL_SERVER_FRONT+'/services/SaveContext/index.php',window.mapfile));}
if(ctx.isToolActiv('annotation')){var annotationConfig=ctx.getGeneralConfig('Annotation');Annotations=new Carmen.Control.Annotation(annotationConfig);map.addControl(Annotations);}
if(ctx.isToolActiv('queryAttributes')){map.addControl(new Carmen.Control.QueryAttributes(window.CARMEN_URL_SERVER_FRONT+'/services/QueryAttributes/index.php',window.mapfile));}
if(ctx.isToolActiv('help'))
map.addControl(new Carmen.Control.Help());if(ctx.isToolActiv('exportImg'))
map.addControl(new Carmen.Control.ExportImg());if(ctx.isToolActiv('exportPdf'))
map.addControl(new Carmen.Control.ExportPdf());if(ctx.isToolActiv('print'))
map.addControl(new Carmen.Control.Print());if(ctx.isToolActiv('download'))
map.addControl(new Carmen.Control.DataDownload());if(ctx.isToolActiv('addLayer'))
map.addControl(new Carmen.Control.AddWMS());map.addControl(new Carmen.Control.Coordinate());if(ctx.isToolActiv('referenceMap')){var rm_config=ctx.mdataMap.ReferenceMap;var rm_imgUrl=rm_config.OnlineResource.attributes.href;var rm_size=new OpenLayers.Size(rm_config.attributes.width,rm_config.attributes.height);var rm_lc=rm_config.BoundingBox.LowerCorner.split(" ");var rm_uc=rm_config.BoundingBox.UpperCorner.split(" ");var rm_maxExtent=new OpenLayers.Bounds(rm_lc[0],rm_lc[1],rm_uc[0],rm_uc[1]);var rm_projection=ctx.getProjection();var rm_projectionUnits=ctx.getProjectionUnits();var layerReference=new OpenLayers.Layer.Image("Reference Map",rm_imgUrl,rm_maxExtent,rm_size,{projection:rm_projection,units:rm_projectionUnits});var RmOptions={size:new OpenLayers.Size(180,100),layers:[layerReference],minRectSize:5,mapOptions:{numZoomLevels:1,maxExtent:rm_maxExtent,projection:rm_projection,units:rm_projectionUnits}};map.addControl(new Carmen.Control.ReferenceMap(layerReference,RmOptions));}
if(ctx.isToolActiv('zoomToPlace')){var ztp_config=Url.decode(ctx.mdataTool.zoomToPlaceConfig);var combosConfig=Carmen.Util.chompAndSplit(ztp_config,';');for(var i=0;i<combosConfig.length;i++){combosConfig[i]=Carmen.Util.chompAndSplit(combosConfig[i],'|');}
ztp_configs=[];for(var i=0;i<combosConfig.length;i++){var config={labelText:combosConfig[i][0],fieldNameId:combosConfig[i][2],providerUrl:window.CARMEN_URL_SERVER_FRONT+'/services/GetAreas/index.php',providerBaseParams:{'map':window.mapfile,'layer':combosConfig[i][1],'fieldId':combosConfig[i][2],'fieldName':combosConfig[i][3]}};if(combosConfig[i].length>4){var linkedCombo=combosConfig[i][4];config['linkedCombo']=linkedCombo;config['linkedFieldName']='filter_id';config['providerLinkParams']={'filter_item':combosConfig[i][5],'filter_id':''};}
ztp_configs.push(config);}
map.addControl(new Carmen.Control.ZoomToPlace({configs:ztp_configs}));};var ctx=this.context;var map=this.map;var layerTreeManager=new Carmen.Control.LayerTreeManager({visible:ctx.isToolActiv('legend')});var jsonLayerTree=ctx.mdataMap.LayerTree;var jsonLayerList=ctx.layer;layerTreeManager.buildTree(jsonLayerTree,jsonLayerList);this.map.addControl(layerTreeManager);var ctx=this.context;var map=this.map;var layerTreeManager=map.getLayerTreeManager();var layerTree=layerTreeManager.getLayerTree();var baseLayer=new Carmen.Layer.MapServerGroup("Base Map",window.CARMEN_URL_SERVER_DATA+"/cgi-bin/mapserv?map="+window.mapfile,{map_imagetype:ctx.mdataMap.outputFormat},{maxExtent:ctx.getMaxExtent(),projection:ctx.getProjection(),units:ctx.getProjectionUnits(),isBaseLayer:true,singleTile:true});map.addLayer(baseLayer);if(Ext.value(ctx.mdataMap.inlay,"0")=="1"){var inlayParams={displayTxt:Ext.value(ctx.mdataMap.scaleTxt,"0")=="1",displayImg:Ext.value(ctx.mdataMap.scaleImg,"0")=="1",displayLogo:Ext.value(ctx.mdataMap.logo,"0")=="1",fontSize:Ext.value(ctx.mdataMap.fontSize,null),color:Ext.value(ctx.mdataMap.fontColor,null),backgroundColor:Ext.value(ctx.mdataMap.backgroundColor,null),logoPath:Ext.value(Url.decode(ctx.mdataMap.logoPath),null)};if(ctx.mdataMap.font)
OpenLayers.Util.extend(inlayParams,Carmen.Util.carmenFontDescToFontStyles(ctx.mdataMap.font));if(Ext.value(ctx.mdataMap.copyright,"0")=="1"){baseLayer.attribution=Url.decode(ctx.mdataMap.copyrightTxt);map.addControl(new OpenLayers.Control.AttributionCarmen(inlayParams));}
if(inlayParams.displayTxt||inlayParams.displayImg){var options=OpenLayers.Util.extend(inlayParams,{serverUrl:window.CARMEN_URL_SERVER_DATA+'/cgi-bin/mapserv',mapfile:window.mapfile});map.addControl(new OpenLayers.Control.MapserverScale(options));}}
var labelLayer=new Carmen.Layer.MapServerGroup("Label layer",window.CARMEN_URL_SERVER_DATA+"/cgi-bin/mapserv?map="+window.mapfile,{LAYERS:'',map_imagetype:'png',map_transparent:true},{maxExtent:ctx.getMaxExtent(),projection:ctx.getProjection(),units:ctx.getProjectionUnits(),isBaseLayer:false,singleTile:true});var layers=this._buildLayers2(layerTree,ctx,labelLayer);for(var i=layers.length-1;i>=0;i--){if(layers[i].maxExtent==null)
layers[i].maxExtent=ctx.getMaxExtent();if(layers[i].resolutions!=null&&map.resolutions!=null){var nbRes=layers[i].resolutions.length;var newRes=[].concat(layers[i].resolutions);for(var j=0;j<map.resolutions.length;j++){newRes=Carmen.Util.set_add(newRes,map.resolutions[j],Carmen.Util.resNearTester);}
newRes.sort(Carmen.Util.descendingOrder);map.resolutions=newRes;}
layers[i].setIsBaseLayer(false);map.addLayer(layers[i]);}
map.addLayer(labelLayer);map.setLabelLayer(labelLayer);map.addControl(new Carmen.Control.ToolTip(window.CARMEN_URL_SERVER_FRONT+'/services/GetInformation/index.php',window.mapfile));layerTreeManager.treeLayoutInit.defer(250,layerTreeManager);if(map.resolutions!=null&&controlScaleChooser!=null){var scales=[];for(var i=0;i<map.resolutions.length;i++){var sc=OpenLayers.Util.getScaleFromResolution(map.resolutions[i],"m").toFixed();scales.push(Carmen.Util.roundIntToDigits(sc));}
controlScaleChooser.updateScaleValues(scales);}
if(ctx.isToolActiv('zoomToPlace')){var ztpCtl=map.getControlsByClass("Carmen.Control.ZoomToPlace");if(ztpCtl.length>0){ztpCtl=ztpCtl[0];ztpCtl.loadContent();}}
return this.context;},updateContext:function(bPrint){this.context.setExtent(this.map.getExtent());var layerMgr=this.map.getLayerTreeManager();var layersVisibility=layerMgr.getLayersVisibility();for(var i=0;i<layersVisibility.length;i++){layerVis=layersVisibility[i];this.context.setLayerVisibility(layerVis.layerIdx,layerVis.visible);}
this.context.setGeneralConfig(layerMgr.serializeForContext());var favoriteAreas=this.map.getControlsByClass('Carmen.Control.FavoriteAreas');if(favoriteAreas.length>0){favoriteAreas=favoriteAreas[0];this.context.setGeneralConfig(favoriteAreas.serializeForContext());}
var annotation=this.map.getControlsByClass('Carmen.Control.Annotation');if(annotation.length>0){annotation=annotation[0];if(bPrint){this.context.setGeneralConfig({Annotation:annotation.exportFeatures()})}
else{this.context.setGeneralConfig(annotation.serializeForContext());}}
return this.context.getObj();},NODE_LAYER:0,NODE_GROUP:1,_buildLayers2:function(layerTree,ctx,labelLayer){var layers=new Array();var providerGrp=new Array();this._getProvider2layers(layerTree,providerGrp);for(var i=0;i<providerGrp.length;i++){var layerNames='';if(providerGrp[i]instanceof Array){for(var j=0;j<providerGrp[i].length;j++){var nodes=providerGrp[i];layerNames=layerNames+'+'+providerGrp[i][j].attributes.jsonLayerDesc.Title;}
var layer=this._buildLayer2(providerGrp[i],i,ctx,labelLayer);if(layer!=null)
layers[layers.length]=layer;}}
return layers;},_getProvider2layers:function(node,provider2layers){if(node.attributes.type==this.NODE_LAYER){var providerId=node.attributes.providerId;if(!(provider2layers[providerId]instanceof Array)){provider2layers[providerId]=new Array();}
provider2layers[providerId][provider2layers[providerId].length]=node;}
else if(node.attributes.type==this.NODE_GROUP){for(var i=0;i<node.childNodes.length;i++){this._getProvider2layers(node.childNodes[i],provider2layers);}}},_buildMapserverLayer2:function(layerNodes,providerUrl,ctx,labelLayer){var msParams={LAYERS:'',map_imagetype:ctx.mdataMap.outputFormat,map_transparent:'TRUE'};var layerNames="";for(var i=0;i<layerNodes.length;i++){var node=layerNodes[i];var lname=node.attributes.jsonLayerDesc.Title;layerNames=layerNames+'+'+lname;if(Ext.value(node.attributes.minScale,null,false)!=null)
msParams['map.layer['+lname+']']='MINSCALEDENOM '+(parseFloat(node.attributes.minScale)*0.999999);if(Ext.value(node.attributes.maxScale,null,false)!=null){msParams['map.layer['+lname+']']='MAXSCALEDENOM '+(parseFloat(node.attributes.maxScale)*1.000001);}}
layerNames=layerNames.slice(1);var layer=new Carmen.Layer.MapServerGroup(layerNames,providerUrl,msParams,{projection:ctx.getProjection(),units:ctx.getProjectionUnits(),singleTile:true});layer.setVisibility(false);for(var i=0;i<layerNodes.length;i++){var desc=layerNodes[i].attributes.jsonLayerDesc;var lname=desc.Title;var lvis=!(desc.attributes.hidden=="1");layer.addSubLayer(lname,lvis);var hasLabel=desc.attributes.hasLabel=="1";layerNodes[i].attributes.hasLabel=hasLabel;if(hasLabel){var classes=[];if('StyleList'in desc){classes=desc.StyleList.Style instanceof Array?desc.StyleList.Style:[].concat(desc.StyleList.Style);}
var params={};for(var j=0;j<classes.length;j++){layer.params['map.layer['+lname+'].class['+j+']']='LABEL SIZE -1 END';}
labelLayer.addSubLayer(lname,lvis);labelLayer.params['map.layer['+lname+']']='OPACITY 1';}}
return layer;},_buildWMSLayer2:function(layerNodes,providerUrl,ctx){var layerNames="";for(var i=0;i<layerNodes.length;i++){var name=layerNodes[i].attributes.jsonLayerDesc.Title;layerNames=layerNames+','+name;}
layerNames=layerNames.slice(1);firstLayerDesc=layerNodes[0].attributes.jsonLayerDesc;var version=Url.decode(firstLayerDesc.Server.attributes.version);var outputFormat=Url.decode(firstLayerDesc.Extension.wms_format);var projection=Ext.value(Url.decode(firstLayerDesc.Extension.wms_srs),ctx.getProjection(),false);var projUnits=Carmen.Util.getProjectionUnits(projection);var layer=new Carmen.Layer.WMSGroup(layerNames,providerUrl,{LAYERS:'',version:version,format:outputFormat,transparent:true},{isBaseLayer:false,singleTile:true,projection:projection,units:projUnits});layer.setVisibility(false);for(var i=0;i<layerNodes.length;i++){var lname=layerNodes[i].attributes.jsonLayerDesc.Title;var lwmsName=layerNodes[i].attributes.jsonLayerDesc.Extension.wms_name
var lvis=!(layerNodes[i].attributes.jsonLayerDesc.attributes.hidden=="1");layer.addSubLayer(lname,lvis,lwmsName);}
return layer;},_buildWMSCLayer2:function(layerNodes,providerUrl,ctx){var layerNames="";for(var i=0;i<layerNodes.length;i++){var name=layerNodes[i].attributes.jsonLayerDesc.Title;layerNames=layerNames+','+name;}
layerNames=layerNames.slice(1);firstLayerDesc=layerNodes[0].attributes.jsonLayerDesc;var version=firstLayerDesc.Server.attributes.version;var outputFormat=firstLayerDesc.Extension.wms_format;var projection=Ext.value(Url.decode(firstLayerDesc.Extension.wms_srs),ctx.getProjection(),false);var projUnits=Carmen.Util.getProjectionUnits(projection);layerOptions={isBaseLayer:false,buffer:0,tileSize:new OpenLayers.Size(256,256),projection:projection,resolutions:null,units:projUnits};var str_boundingbox=Ext.value(firstLayerDesc.Extension.wmsc_boundingbox,null,false);layerOptions.maxExtent=ctx.getMaxExtent();if(str_boundingbox){var sep=str_boundingbox.indexOf(',')!=-1?',':' ';var bb=Carmen.Util.chompAndSplit(Url.decode(str_boundingbox),sep);layerOptions.maxExtent=new OpenLayers.Bounds(bb[0],bb[1],bb[2],bb[3]);}
var str_res=Ext.value(firstLayerDesc.Extension.wmsc_resolution,null,false);if(str_res!=null){str_res=Url.decode(str_res);var sep=str_res.indexOf(',')!=-1?',':' ';var res=Carmen.Util.chompAndSplit(str_res,sep);if(!isNaN(new Number(res[0]))){layerOptions.resolutions=Carmen.Util.array_map(res,parseFloat);}}
var layer=new Carmen.Layer.WMSGroup(layerNames,providerUrl,{LAYERS:'',version:version,format:outputFormat},layerOptions);layer.setVisibility(false);for(var i=0;i<layerNodes.length;i++){var lname=layerNodes[i].attributes.jsonLayerDesc.Title;var lwmsName=layerNodes[i].attributes.jsonLayerDesc.Extension.wms_name;var lvis=!(layerNodes[i].attributes.jsonLayerDesc.attributes.hidden=="1");layer.addSubLayer(lname,lvis,lwmsName);}
return layer;},_buildLayer2:function(layerNodes,providerGrpId,ctx,labelLayer){var layer=null;var providerUrl=null;if(!layerNodes)
return;firstLayerDesc=layerNodes[0].attributes.jsonLayerDesc;if('DataURL'in firstLayerDesc){providerUrl=firstLayerDesc.DataURL.OnLineResource.attributes.url;var isMapserverLayer=(providerUrl.search(/mapserv/i)>0);if(isMapserverLayer){layer=this._buildMapserverLayer2(layerNodes,providerUrl,ctx,labelLayer);}}
else if('Server'in firstLayerDesc){var service=firstLayerDesc.Server.attributes.service;var providerUrl=firstLayerDesc.Server.OnLineResource.attributes.url;var isWMS=(service.search(/WMS/i)>-1);if(isWMS){layer=this._buildWMSLayer2(layerNodes,providerUrl,ctx);}
var isWMSC=Ext.value(firstLayerDesc.Extension.layerSettings_wmscLayer,"OFF")=="ON";if(isWMSC){layer=this._buildWMSCLayer2(layerNodes,providerUrl,ctx);}}
if(layer!=null){for(var i=0;i<layerNodes.length;i++){var node=layerNodes[i];var layerDesc=layerNodes[i].attributes.jsonLayerDesc;node.attributes.OlLayer=layer;node.addListener('checkchange',function(n,cb_state){var layer=n.attributes.OlLayer;var lname=n.attributes.jsonLayerDesc.Title;layer.setSubLayerVisibility(lname,n.attributes.checked);if(n.attributes.hasLabel){labelLayer.setSubLayerVisibility(lname,n.attributes.checked);}},node);}}
return layer;}});Carmen.Application.CLASS_NAME="Carmen.Application";Carmen.JSONContext=new OpenLayers.Class({jsOws:null,generalExt:null,layer:[],mapProjection:null,mdataTool:null,mdataMap:null,mdataLayer:null,mapExtent:null,maxExtent:null,initialize:function(context){this.jsOws=context;this.generalExt=this.jsOws.OWSContext.General.Extension;if(this.jsOws.OWSContext.ResourceList.Layer)
this.layer=this.jsOws.OWSContext.ResourceList.Layer instanceof Array?this.jsOws.OWSContext.ResourceList.Layer:[].concat(this.jsOws.OWSContext.ResourceList.Layer);this.parseMdata();},getObj:function(){return this.jsOws;},getProjection:function(){if(this.mapProjection==null)
this.mapProjection=this.jsOws.OWSContext.General.BoundingBox.attributes.crs.split('=')[1].toLocaleUpperCase();return this.mapProjection;},getProjectionUnits:function(){if(this.mapProjectionUnits==null)
this.mapProjectionUnits=Carmen.Util.getProjectionUnits(this.getProjection());return this.mapProjectionUnits;},getExtent:function(){if(this.mapExtent==null){this.mapExtent=Carmen.Util.convertContextBBtoolBounds(this.jsOws.OWSContext.General.BoundingBox);}
return this.mapExtent;},getMaxExtent:function(){if(this.maxExtent==null){this.maxExtent=Carmen.Util.convertContextBBtoolBounds(this.jsOws.OWSContext.General.MaxBoundingBox);}
return this.maxExtent;},getTitle:function(){return Url.decode(this.jsOws.OWSContext.General.Title);},getFavoriteAreas:function(){return this.generalExt.GeoBookmark?this.generalExt.GeoBookmark:null;},setExtent:function(bounds){this.jsOws.OWSContext.General.BoundingBox.LowerCorner=bounds.left+" "+bounds.bottom;this.jsOws.OWSContext.General.BoundingBox.UpperCorner=bounds.right+" "+bounds.top;},setLayerVisibility:function(layerIdx,visible){this.jsOws.OWSContext.ResourceList.Layer[layerIdx].attributes.hidden=visible?"0":"1";},setGeneralConfig:function(config){for(p in config)
this.generalExt[p]=config[p];},getGeneralConfig:function(configName){var config=null;if(configName in this.generalExt)
config=this.generalExt[configName];return config;},isToolActiv:function(toolName){var toolValue=Ext.value(this.mdataTool[toolName],"0")
return(toolValue=="1"||toolValue=="ON");},hasLayerWMSC:function(){var found=false;for(var k in this.mdataLayer){if(Ext.value(this.mdataLayer[k].wmscLayer,"OFF",false)=="ON"){found=true;break;}}
return found;},parseMdata:function(){this.mdataTool={};this.mdataMap={};for(var k in this.generalExt){var matched=k.match(/^tool_(.+)$/);if(matched!=null){var toolName=matched[1];this.mdataTool[toolName]=this.generalExt[k];}
else{matched=k.match(/^mapSettings_(.+)$/);if(matched!=null){var setting=matched[1];this.mdataMap[setting]=this.generalExt[k];}
else
this.mdataMap[k]=this.generalExt[k];}}
this.mdataLayer={};if(this.layer){if(this.layer instanceof Array){for(var i=0;i<this.layer.length;i++){var layerName=this.layer[i].Title;this.mdataLayer[layerName]={};for(var k in this.layer[i].Extension){var matched=k.match(/^layerSettings_(.+)$/);var setting=matched!=null?matched[1]:k;this.mdataLayer[layerName][setting]=this.layer[i].Extension[k];}}}
else{var layerName=this.layer.Title;this.mdataLayer[layerName]={};for(var k in this.layer.Extension){var matched=k.match(/^layerSettings_(.+)$/);var setting=matched!=null?matched[1]:k;this.mdataLayer[layerName][setting]=this.layer.Extension[k];}}}},getNextLayerId:function(){return this.layer.length;},addLayerDescs:function(descs){for(var i=0;i<descs.length;i++)
this.layer.push(descs[i]);return(this.layer.length-1);},getLayerDescFromMdataValue:function(attributeName,value){var i=0;for(var k in this.mdataLayer){var v=Ext.value(Url.decode(this.mdataLayer[k][attributeName]),null,false);if(v==value){break;}
i++;}
return i<=(this.layer.length-1)?this.layer[i]:null;}});Carmen.Application.debugDD=function(layerTree,map){var layerNodes=layerTree.collectChildNodes(function(n){return('type'in n.attributes&&(n.attributes.type==Carmen.Control.LayerTreeManager.NODE_LAYER))});for(var i=0;i<layerNodes.length;i++){var node=layerNodes[i];node.setText(map.getLayerIndex(node.attributes.OlLayer)+'  '+
node.attributes.OlLayer.getSubLayerInfo(node.attributes.layerName).index+' '+
node.attributes.layerName);}};Carmen.JSONContext.CLASS_NAME="Carmen.JSONContext";Ext.BLANK_IMAGE_URL=window.CARMEN_URL_SERVER_FRONT+'/IHM/JavaScript/extjs/resources/images/default/s.gif';var app;var mapProjection;init=function(){Ext.QuickTips.init();if(jsOws.OWSContext.General.Extension.mapSettings_pwd){var login=new Ext.FormPanel({labelWidth:80,url:'/services/VerifPassword/index.php',frame:true,bodyStyle:'padding:5px;',defaultType:'textfield',monitorValid:true,items:[{name:'PasswordMsg',xtype:'label',text:'La carte est protégé par un mot de passe. Veuillez le saisir.',width:160},{fieldLabel:'Mot de passe',id:'password',name:'password',inputType:'password',allowBlank:false},{id:'lbError',name:'lbError',xtype:'label',text:'',width:160}],buttons:[{text:'OK',formBind:true,handler:function(){login.getForm().submit({method:'POST',waitTitle:'Connexion en cours...',waitMsg:'envoi des données...',success:function(form,action){if(action&&action.result.verifPassword){var result=action.result.verifPassword;if(result=="Success"){initApp(true);Ext.getCmp("passwordWindow").close();}else{login.getComponent('lbError').setText("mot de passe incorrect");login.getComponent('password').focus();win.getEl().applyStyles("zIndex:20002");}}},failure:function(form,action){login.getComponent('lbError').setText("mot de passe incorrect");login.getComponent('password').focus();}});}}]});var win=new Ext.Window({layout:'fit',id:'passwordWindow',title:'Carte protégée',iconCls:'image_login',width:300,height:150,closable:false,resizable:false,modal:true,plain:true,border:false,items:[login]});win.show();win.getEl().applyStyles("zIndex:20002");}
else{initApp(true);}};clearLoading=function(){Ext.get('loading-mask').fadeOut({remove:true,endOpacity:0.0,easing:'easeOut',duration:0.25,useDisplay:true});Ext.get('loading').fadeOut({remove:true,endOpacity:0.0,easing:'easeOut',duration:0.50,useDisplay:true});};initApp=function(clearLoading){app=new Carmen.Application(jsOws);mapProjection=app.context.getProjection();var maxExtent=app.context.getMaxExtent();var extent=app.context.getExtent();var map=app.getMap();if(clearLoading)
window.clearLoading();};var getLayer=function(jsonLayerList,layerName){var layer=null;if(jsonLayerList instanceof Array){var i=0;while(i<jsonLayerList.length&&jsonLayerList[i].attributes.name!=layerName){i++;}
if(i<jsonLayerList.length){layer=jsonLayerList[i];}}else{if(jsonLayerList.attributes.name!=layerName){layer=jsonLayerList;}}
return layer;};
