var Municipia={singleFileMunicipia:true};(function(){var singleFileMunicipia=(typeof Municipia=="object"&&Municipia.singleFileMunicipia);window.Municipia={_scriptName:(!singleFileMunicipia)?"municipia/Municipia.js":"Municipia.js",_getScriptLocation:function(){var scriptLocation="";var isOL=new RegExp("(^|(.*?\\/))("+Municipia._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 match=src.match(isOL);if(match){scriptLocation=match[1];break;}}}
return scriptLocation;}};if(!singleFileMunicipia){var jsfiles=new Array("municipia/Util.js","municipia/BaseTypes.js","municipia/BaseTypes/Class.js","municipia/BaseTypes/LonLat.js","municipia/BaseTypes/Size.js","municipia/BaseTypes/Pixel.js","municipia/BaseTypes/Element.js","municipia/BaseTypes/Bounds.js","municipia/Map.js","municipia/Icon.js","municipia/Marker.js","municipia/Popup.js","municipia/Handler.js","municipia/Handler/Drag.js","municipia/Handler/Box.js","municipia/o_Control.js","municipia/Ajax.js","municipia/Toolbar.js","municipia/LegendNodeUI.js","municipia/Lang/pt-BR.js","municipia/Lang/pt-PT.js","municipia/Events.js","municipia/Control.js","municipia/Control/DragPan.js","municipia/Control/ZoomBox.js","municipia/Control/Scale.js","municipia/Control/ScaleBar.js","municipia/Control/OverviewMap.js","municipia/Control/LayerSwitcher.js","municipia/Control/PanZoomBar.js","municipia/Control/MousePosition.js","municipia/Control/GetFeatureInfo.js","municipia/Control/GetFeatureInfoWFS.js","municipia/Control/Export2Data.js","municipia/Control/DatumDisplayCoordinates.js","municipia/Control/Footer.js","municipia/Control/Copyright.js","municipia/Control/InfoAdicional.js","municipia/Control/Center.js","municipia/Control/CleanMap.js","municipia/Popup/Anchored.js","municipia/Popup/AnchoredBubble.js","municipia/Popup/POI.js","municipia/Popup/Center.js","municipia/Popup/Top.js","municipia/Popup/Right.js","municipia/Feature.js","municipia/Feature/WFS.js","municipia/Layer/WFS.js","municipia/Layer/VirtualEarth.js","municipia/Layer/TMS.js","municipia/SLD/v1.js","proj4js/proj4js.js","proj4js/defs/EPSG4326.js","proj4js/defs/EPSG2942.js","proj4js/defs/EPSG27492.js","proj4js/defs/EPSG900913.js","proj4js/defs/GOOGLE.js","print/Base.js","print/BaseWidget.js","print/MultiPage.js","print/PrintAction.js","print/PrintPDM.js","print/PrintPIP.js","print/PrintProtocol.js","print/SimpleForm.js","pl_localizacao/Base.js","pl_localizacao/EmissaoForm.js","pl_localizacao/PedidosForm.js","pl_localizacao/LoginForm.js","pl_localizacao/PlantasProtocol.js","estatisticos/Color.js","estatisticos/GeoStat.js","estatisticos/Choropleth.js","estatisticos/ColorForm.js","MapComponent.js");var agent=navigator.userAgent;var docWrite=(agent.match("MSIE")||agent.match("Safari"));if(docWrite){var allScriptTags=new Array(jsfiles.length);}
var host=Municipia._getScriptLocation()+"scripts/lib/";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(""));}}})();Municipia.String={startsWith:function(str,sub){return(str.indexOf(sub)==0);},contains:function(str,sub){return(str.indexOf(sub)!=-1);},trim:function(str){return str.replace(/^\s*(.*?)\s*$/,"$1");},camelize:function(str){var oStringList=str.split('-');var camelizedString=oStringList[0];for(var i=1,len=oStringList.length;i<len;i++){var s=oStringList[i];camelizedString+=s.charAt(0).toUpperCase()+s.substring(1);}
return camelizedString;},format:function(template,context,args){if(!context){context=window;}
var tokens=template.split("${");var item,last,replacement;for(var i=1,len=tokens.length;i<len;i++){item=tokens[i];last=item.indexOf("}");if(last>0){replacement=context[item.substring(0,last)];if(typeof replacement=="function"){replacement=args?replacement.apply(null,args):replacement();}
tokens[i]=replacement+item.substring(++last);}else{tokens[i]="${"+item;}}
return tokens.join("");},numberRegEx:/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/,isNumeric:function(value){return Municipia.String.numberRegEx.test(value);}};if(!String.prototype.startsWith){String.prototype.startsWith=function(sStart){Municipia.Console.warn(Municipia.i18n("methodDeprecated",{'newMethod':'Municipia.String.startsWith'}));return Municipia.String.startsWith(this,sStart);};}
if(!String.prototype.contains){String.prototype.contains=function(str){Municipia.Console.warn(Municipia.i18n("methodDeprecated",{'newMethod':'Municipia.String.contains'}));return Municipia.String.contains(this,str);};}
if(!String.prototype.trim){String.prototype.trim=function(){Municipia.Console.warn(Municipia.i18n("methodDeprecated",{'newMethod':'Municipia.String.trim'}));return Municipia.String.trim(this);};}
if(!String.prototype.camelize){String.prototype.camelize=function(){Municipia.Console.warn(Municipia.i18n("methodDeprecated",{'newMethod':'Municipia.String.camelize'}));return Municipia.String.camelize(this);};}
Municipia.Number={decimalSeparator:".",thousandsSeparator:",",limitSigDigs:function(num,sig){var fig=0;if(sig>0){fig=parseFloat(num.toPrecision(sig));}
return fig;},format:function(num,dec,tsep,dsep){dec=(typeof dec!="undefined")?dec:0;tsep=(typeof tsep!="undefined")?tsep:Municipia.Number.thousandsSeparator;dsep=(typeof dsep!="undefined")?dsep:Municipia.Number.decimalSeparator;if(dec!=null){num=parseFloat(num.toFixed(dec));}
var parts=num.toString().split(".");if(parts.length==1&&dec==null){dec=0;}
var integer=parts[0];if(tsep){var thousands=/(-?[0-9]+)([0-9]{3})/;while(thousands.test(integer)){integer=integer.replace(thousands,"$1"+tsep+"$2");}}
var str;if(dec==0){str=integer;}else{var rem=parts.length>1?parts[1]:"0";if(dec!=null){rem=rem+new Array(dec-rem.length+1).join("0");}
str=integer+dsep+rem;}
return str;}};if(!Number.prototype.limitSigDigs){Number.prototype.limitSigDigs=function(sig){Municipia.Console.warn(Municipia.i18n("methodDeprecated",{'newMethod':'Municipia.Number.limitSigDigs'}));return Municipia.Number.limitSigDigs(this,sig);};}
Municipia.Function={bind:function(func,object){var args=Array.prototype.slice.apply(arguments,[2]);return function(){var newArgs=args.concat(Array.prototype.slice.apply(arguments,[0]));return func.apply(object,newArgs);};},bindAsEventListener:function(func,object){return function(event){return func.call(object,event||window.event);};}};if(!Function.prototype.bind){Function.prototype.bind=function(){Municipia.Console.warn(Municipia.i18n("methodDeprecated",{'newMethod':'Municipia.Function.bind'}));Array.prototype.unshift.apply(arguments,[this]);return Municipia.Function.bind.apply(null,arguments);};}
if(!Function.prototype.bindAsEventListener){Function.prototype.bindAsEventListener=function(object){Municipia.Console.warn(Municipia.i18n("methodDeprecated",{'newMethod':'Municipia.Function.bindAsEventListener'}));return Municipia.Function.bindAsEventListener(this,object);};}
Municipia.Array={filter:function(array,callback,caller){var selected=[];if(Array.prototype.filter){selected=array.filter(callback,caller);}else{var len=array.length;if(typeof callback!="function"){throw new TypeError();}
for(var i=0;i<len;i++){if(i in array){var val=array[i];if(callback.call(caller,val,i,array)){selected.push(val);}}}}
return selected;}};Municipia.Class=function(){var Class=function(){if(arguments&&arguments[0]!=Municipia.Class.isPrototype){this.initialize.apply(this,arguments);}};var extended={};var parent;for(var i=0,len=arguments.length;i<len;++i){if(typeof arguments[i]=="function"){parent=arguments[i].prototype;}else{parent=arguments[i];}
Municipia.Util.extend(extended,parent);}
Class.prototype=extended;return Class;};Municipia.Class.isPrototype=function(){};Municipia.Class.create=function(){return function(){if(arguments&&arguments[0]!=Municipia.Class.isPrototype){this.initialize.apply(this,arguments);}};};Municipia.Class.inherit=function(){var superClass=arguments[0];var proto=new superClass(Municipia.Class.isPrototype);for(var i=1,len=arguments.length;i<len;i++){if(typeof arguments[i]=="function"){var mixin=arguments[i];arguments[i]=new mixin(Municipia.Class.isPrototype);}
Municipia.Util.extend(proto,arguments[i]);}
return proto;};Municipia.Util={};Municipia.Util.getElement=function(){var elements=[];for(var i=0;i<arguments.length;i++){var element=arguments[i];if(typeof element=='string'){element=document.getElementById(element);}
if(arguments.length==1){return element;}
elements.push(element);}
return elements;};if($==null){var $=Municipia.Util.getElement;}
Municipia.Util.extend=function(destination,source){if(destination&&source){for(var property in source){var value=source[property];if(value!==undefined){destination[property]=value;}}
var sourceIsEvt=typeof window.Event=="function"&&source instanceof window.Event;if(!sourceIsEvt&&source.hasOwnProperty&&source.hasOwnProperty('toString')){destination.toString=source.toString;}}
return destination;};Municipia.Util.removeItem=function(array,item){for(var i=array.length-1;i>=0;i--){if(array[i]==item){array.splice(i,1);}}
return array;};Municipia.Util.clearArray=function(array){Municipia.Console.warn(Municipia.i18n("methodDeprecated",{'newMethod':'array = []'}));array.length=0;};Municipia.Util.indexOf=function(array,obj){for(var i=0;i<array.length;i++){if(array[i]==obj){return i;}}
return-1;};Municipia.Util.modifyDOMElement=function(element,id,px,sz,position,border,overflow,opacity){if(id){element.id=id;}
if(px){element.style.left=px.x+"px";element.style.top=px.y+"px";}
if(sz){element.style.width=sz.w+"px";element.style.height=sz.h+"px";}
if(position){element.style.position=position;}
if(border){element.style.border=border;}
if(overflow){element.style.overflow=overflow;}
if(parseFloat(opacity)>=0.0&&parseFloat(opacity)<1.0){element.style.filter='alpha(opacity='+(opacity*100)+')';element.style.opacity=opacity;}else if(parseFloat(opacity)==1.0){element.style.filter='';element.style.opacity='';}};Municipia.Util.createDiv=function(id,px,sz,imgURL,position,border,overflow,opacity){var dom=document.createElement('div');if(imgURL){dom.style.backgroundImage='url('+imgURL+')';}
if(!id){id=Municipia.Util.createUniqueID("MunicipiaDiv");}
if(!position){position="absolute";}
Municipia.Util.modifyDOMElement(dom,id,px,sz,position,border,overflow,opacity);return dom;};Municipia.Util.createImage=function(id,px,sz,imgURL,position,border,opacity,delayDisplay){var image=document.createElement("img");if(!id){id=Municipia.Util.createUniqueID("MunicipiaDiv");}
if(!position){position="relative";}
Municipia.Util.modifyDOMElement(image,id,px,sz,position,border,null,opacity);if(delayDisplay){image.style.display="none";Municipia.Event.observe(image,"load",Municipia.Function.bind(Municipia.Util.onImageLoad,image));Municipia.Event.observe(image,"error",Municipia.Function.bind(Municipia.Util.onImageLoadError,image));}
image.style.alt=id;image.galleryImg="no";if(imgURL){image.src=imgURL;}
return image;};Municipia.Util.setOpacity=function(element,opacity){Municipia.Util.modifyDOMElement(element,null,null,null,null,null,null,opacity);};Municipia.Util.onImageLoad=function(){if(!this.viewRequestID||(this.map&&this.viewRequestID==this.map.viewRequestID)){this.style.backgroundColor=null;this.style.display="";}};Municipia.Util.onImageLoadErrorColor="pink";Municipia.IMAGE_RELOAD_ATTEMPTS=0;Municipia.Util.onImageLoadError=function(){this._attempts=(this._attempts)?(this._attempts+1):1;if(this._attempts<=Municipia.IMAGE_RELOAD_ATTEMPTS){this.src=this.src;}else{this.style.backgroundColor=Municipia.Util.onImageLoadErrorColor;}
this.style.display="";};Municipia.Util.alphaHack=function(){var arVersion=navigator.appVersion.split("MSIE");var version=parseFloat(arVersion[1]);var filter=false;try{filter=!!(document.body.filters);}catch(e){}
return(filter&&(version>=5.5)&&(version<7));};Municipia.Util.modifyAlphaImageDiv=function(div,id,px,sz,imgURL,position,border,sizing,opacity){Municipia.Util.modifyDOMElement(div,id,px,sz,null,null,null,opacity);var img=div.childNodes[0];if(imgURL){img.src=imgURL;}
Municipia.Util.modifyDOMElement(img,div.id+"_innerImage",null,sz,"relative",border);if(Municipia.Util.alphaHack()){div.style.display="inline-block";if(sizing==null){sizing="scale";}
div.style.filter="progid:DXImageTransform.Microsoft"+".AlphaImageLoader(src='"+img.src+"', "+"sizingMethod='"+sizing+"')";if(parseFloat(div.style.opacity)>=0.0&&parseFloat(div.style.opacity)<1.0){div.style.filter+=" alpha(opacity="+div.style.opacity*100+")";}
img.style.filter="alpha(opacity=0)";}};Municipia.Util.createAlphaImageDiv=function(id,px,sz,imgURL,position,border,sizing,opacity,delayDisplay){var div=Municipia.Util.createDiv();var img=Municipia.Util.createImage(null,null,null,null,null,null,null,false);div.appendChild(img);if(delayDisplay){img.style.display="none";Municipia.Event.observe(img,"load",Municipia.Function.bind(Municipia.Util.onImageLoad,div));Municipia.Event.observe(img,"error",Municipia.Function.bind(Municipia.Util.onImageLoadError,div));}
Municipia.Util.modifyAlphaImageDiv(div,id,px,sz,imgURL,position,border,sizing,opacity);return div;};Municipia.Util.upperCaseObject=function(object){var uObject={};for(var key in object){uObject[key.toUpperCase()]=object[key];}
return uObject;};Municipia.Util.applyDefaults=function(to,from){var fromIsEvt=typeof window.Event=="function"&&from instanceof window.Event;for(var key in from){if(to[key]===undefined||(!fromIsEvt&&from.hasOwnProperty&&from.hasOwnProperty(key)&&!to.hasOwnProperty(key))){to[key]=from[key];}}
if(!fromIsEvt&&from.hasOwnProperty&&from.hasOwnProperty('toString')&&!to.hasOwnProperty('toString')){to.toString=from.toString;}
return to;};Municipia.Util.getParameterString=function(params){var paramsArray=[];for(var key in params){var value=params[key];if((value!=null)&&(typeof value!='function')){var encodedValue;if(typeof value=='object'&&value.constructor==Array){var encodedItemArray=[];for(var itemIndex=0;itemIndex<value.length;itemIndex++){encodedItemArray.push(encodeURIComponent(value[itemIndex]));}
encodedValue=encodedItemArray.join(",");}
else{encodedValue=encodeURIComponent(value);}
paramsArray.push(encodeURIComponent(key)+"="+encodedValue);}}
return paramsArray.join("&");};Municipia.ImgPath='';Municipia.Util.getImagesLocation=function(){return Municipia.ImgPath||(Municipia._getScriptLocation()+"img/");};Municipia.Util.Try=function(){var returnValue=null;for(var i=0;i<arguments.length;i++){var lambda=arguments[i];try{returnValue=lambda();break;}catch(e){}}
return returnValue;};Municipia.Util.getNodes=function(p,tagName){var nodes=Municipia.Util.Try(function(){return Municipia.Util._getNodes(p.documentElement.childNodes,tagName);},function(){return Municipia.Util._getNodes(p.childNodes,tagName);});return nodes;};Municipia.Util._getNodes=function(nodes,tagName){var retArray=[];for(var i=0;i<nodes.length;i++){if(nodes[i].nodeName==tagName){retArray.push(nodes[i]);}}
return retArray;};Municipia.Util.getTagText=function(parent,item,index){var result=Municipia.Util.getNodes(parent,item);if(result&&(result.length>0))
{if(!index){index=0;}
if(result[index].childNodes.length>1){return result.childNodes[1].nodeValue;}
else if(result[index].childNodes.length==1){return result[index].firstChild.nodeValue;}}else{return"";}};Municipia.Util.getXmlNodeValue=function(node){var val=null;Municipia.Util.Try(function(){val=node.text;if(!val){val=node.textContent;}
if(!val){val=node.firstChild.nodeValue;}},function(){val=node.textContent;});return val;};Municipia.Util.mouseLeft=function(evt,div){var target=(evt.relatedTarget)?evt.relatedTarget:evt.toElement;while(target!=div&&target!=null){target=target.parentNode;}
return(target!=div);};Municipia.Util.rad=function(x){return x*Math.PI/180;};Municipia.Util.distVincenty=function(p1,p2){var a=6378137,b=6356752.3142,f=1/298.257223563;var L=Municipia.Util.rad(p2.lon-p1.lon);var U1=Math.atan((1-f)*Math.tan(Municipia.Util.rad(p1.lat)));var U2=Math.atan((1-f)*Math.tan(Municipia.Util.rad(p2.lat)));var sinU1=Math.sin(U1),cosU1=Math.cos(U1);var sinU2=Math.sin(U2),cosU2=Math.cos(U2);var lambda=L,lambdaP=2*Math.PI;var iterLimit=20;while(Math.abs(lambda-lambdaP)>1e-12&&--iterLimit>0){var sinLambda=Math.sin(lambda),cosLambda=Math.cos(lambda);var sinSigma=Math.sqrt((cosU2*sinLambda)*(cosU2*sinLambda)+
(cosU1*sinU2-sinU1*cosU2*cosLambda)*(cosU1*sinU2-sinU1*cosU2*cosLambda));if(sinSigma==0){return 0;}
var cosSigma=sinU1*sinU2+cosU1*cosU2*cosLambda;var sigma=Math.atan2(sinSigma,cosSigma);var alpha=Math.asin(cosU1*cosU2*sinLambda/sinSigma);var cosSqAlpha=Math.cos(alpha)*Math.cos(alpha);var cos2SigmaM=cosSigma-2*sinU1*sinU2/cosSqAlpha;var C=f/16*cosSqAlpha*(4+f*(4-3*cosSqAlpha));lambdaP=lambda;lambda=L+(1-C)*f*Math.sin(alpha)*(sigma+C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)));}
if(iterLimit==0){return NaN;}
var uSq=cosSqAlpha*(a*a-b*b)/(b*b);var A=1+uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)));var B=uSq/1024*(256+uSq*(-128+uSq*(74-47*uSq)));var deltaSigma=B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-
B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)));var s=b*A*(sigma-deltaSigma);var d=s.toFixed(3)/1000;return d;};Municipia.Util.getParameters=function(url){url=url||window.location.href;var paramsString="";if(Municipia.String.contains(url,'?')){var start=url.indexOf('?')+1;var end=Municipia.String.contains(url,"#")?url.indexOf('#'):url.length;paramsString=url.substring(start,end);}
var parameters={};var pairs=paramsString.split(/[&;]/);for(var i=0;i<pairs.length;++i){var keyValue=pairs[i].split('=');if(keyValue[0]){var key=decodeURIComponent(keyValue[0]);var value=keyValue[1]||'';value=value.split(",");for(var j=0;j<value.length;j++){value[j]=decodeURIComponent(value[j]);}
if(value.length==1){value=value[0];}
parameters[key]=value;}}
return parameters;};Municipia.Util.getArgs=function(url){Municipia.Console.warn(Municipia.i18n("methodDeprecated",{'newMethod':'Municipia.Util.getParameters'}));return Municipia.Util.getParameters(url);};Municipia.Util.lastSeqID=0;Municipia.Util.createUniqueID=function(prefix){if(prefix==null){prefix="id_";}
Municipia.Util.lastSeqID+=1;return prefix+Municipia.Util.lastSeqID;};Municipia.INCHES_PER_UNIT={'inches':1.0,'ft':12.0,'mi':63360.0,'m':39.3701,'km':39370.1,'dd':4374754,'yd':36};Municipia.INCHES_PER_UNIT["in"]=Municipia.INCHES_PER_UNIT.inches;Municipia.INCHES_PER_UNIT["degrees"]=Municipia.INCHES_PER_UNIT.dd;Municipia.INCHES_PER_UNIT["nmi"]=1852*Municipia.INCHES_PER_UNIT.m;Municipia.DOTS_PER_INCH=72;Municipia.Util.normalizeScale=function(scale){var normScale=(scale>1.0)?(1.0/scale):scale;return normScale;};Municipia.Util.getResolutionFromScale=function(scale,units){if(units==null){units="degrees";}
var normScale=Municipia.Util.normalizeScale(scale);var resolution=1/(normScale*Municipia.INCHES_PER_UNIT[units]*Municipia.DOTS_PER_INCH);return resolution;};Municipia.Util.getScaleFromResolution=function(resolution,units){if(units==null){units="degrees";}
var scale=resolution*Municipia.INCHES_PER_UNIT[units]*Municipia.DOTS_PER_INCH;return scale;};Municipia.Util.safeStopPropagation=function(evt){Municipia.Event.stop(evt,true);};Municipia.Util.pagePosition=function(forElement){var valueT=0,valueL=0;var element=forElement;var child=forElement;while(element){if(element==document.body){if(child&&child.style&&Municipia.Element.getStyle(child,'position')=='absolute'){break;}}
valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;child=element;try{element=element.offsetParent;}catch(e){Municipia.Console.error(Municipia.i18n("pagePositionFailed",{'elemId':element.id}));break;}}
element=forElement;while(element){valueT-=element.scrollTop||0;valueL-=element.scrollLeft||0;element=element.parentNode;}
return[valueL,valueT];};Municipia.Util.isEquivalentUrl=function(url1,url2,options){options=options||{};Municipia.Util.applyDefaults(options,{ignoreCase:true,ignorePort80:true,ignoreHash:true});var urlObj1=Municipia.Util.createUrlObject(url1,options);var urlObj2=Municipia.Util.createUrlObject(url2,options);for(var key in urlObj1){if(options.test){alert(key+"\n1:"+urlObj1[key]+"\n2:"+urlObj2[key]);}
var val1=urlObj1[key];var val2=urlObj2[key];switch(key){case"args":break;case"host":case"port":case"protocol":if((val1=="")||(val2=="")){break;}
default:if((key!="args")&&(urlObj1[key]!=urlObj2[key])){return false;}
break;}}
for(var key in urlObj1.args){if(urlObj1.args[key]!=urlObj2.args[key]){return false;}
delete urlObj2.args[key];}
for(var key in urlObj2.args){return false;}
return true;};Municipia.Util.createUrlObject=function(url,options){options=options||{};var urlObject={};if(options.ignoreCase){url=url.toLowerCase();}
var a=document.createElement('a');a.href=url;urlObject.host=a.host;var port=a.port;if(port.length<=0){var newHostLength=urlObject.host.length-(port.length);urlObject.host=urlObject.host.substring(0,newHostLength);}
urlObject.protocol=a.protocol;urlObject.port=((port=="80")&&(options.ignorePort80))?"":port;urlObject.hash=(options.ignoreHash)?"":a.hash;var queryString=a.search;if(!queryString){var qMark=url.indexOf("?");queryString=(qMark!=-1)?url.substr(qMark):"";}
urlObject.args=Municipia.Util.getParameters(queryString);if(((urlObject.protocol=="file:")&&(url.indexOf("file:")!=-1))||((urlObject.protocol!="file:")&&(urlObject.host!=""))){urlObject.pathname=a.pathname;var qIndex=urlObject.pathname.indexOf("?");if(qIndex!=-1){urlObject.pathname=urlObject.pathname.substring(0,qIndex);}}else{var relStr=Municipia.Util.removeTail(url);var backs=0;do{var index=relStr.indexOf("../");if(index==0){backs++;relStr=relStr.substr(3);}else if(index>=0){var prevChunk=relStr.substr(0,index-1);var slash=prevChunk.indexOf("/");prevChunk=(slash!=-1)?prevChunk.substr(0,slash+1):"";var postChunk=relStr.substr(index+3);relStr=prevChunk+postChunk;}}while(index!=-1)
var windowAnchor=document.createElement("a");var windowUrl=window.location.href;if(options.ignoreCase){windowUrl=windowUrl.toLowerCase();}
windowAnchor.href=windowUrl;urlObject.protocol=windowAnchor.protocol;var splitter=(windowAnchor.pathname.indexOf("/")!=-1)?"/":"\\";var dirs=windowAnchor.pathname.split(splitter);dirs.pop();while((backs>0)&&(dirs.length>0)){dirs.pop();backs--;}
relStr=dirs.join("/")+"/"+relStr;urlObject.pathname=relStr;}
if((urlObject.protocol=="file:")||(urlObject.protocol=="")){urlObject.host="localhost";}
return urlObject;};Municipia.Util.removeTail=function(url){var head=null;var qMark=url.indexOf("?");var hashMark=url.indexOf("#");if(qMark==-1){head=(hashMark!=-1)?url.substr(0,hashMark):url;}else{head=(hashMark!=-1)?url.substr(0,Math.min(qMark,hashMark)):url.substr(0,qMark);}
return head;};Municipia.Util.getBrowserName=function(){var browserName="";var ua=navigator.userAgent.toLowerCase();if(ua.indexOf("opera")!=-1){browserName="opera";}else if(ua.indexOf("msie")!=-1){browserName="msie";}else if(ua.indexOf("safari")!=-1){browserName="safari";}else if(ua.indexOf("mozilla")!=-1){if(ua.indexOf("firefox")!=-1){browserName="firefox";}else{browserName="mozilla";}}
return browserName;};Municipia.Util.getRenderedDimensions=function(contentHTML,size){var w=h=null;var container=document.createElement("div");container.style.overflow="";container.style.position="absolute";container.style.left="-9999px";if(size){if(size.w){w=container.style.width=size.w;}else if(size.h){h=container.style.height=size.h;}}
var content=document.createElement("div");content.innerHTML=contentHTML;container.appendChild(content);document.body.appendChild(container);if(!w){w=parseInt(content.scrollWidth);container.style.width=w+"px";}
if(!h){h=parseInt(content.scrollHeight);}
container.removeChild(content);document.body.removeChild(container);return new Municipia.Size(w,h);};Municipia.Util.getScrollbarWidth=function(){var scrollbarWidth=Municipia.Util._scrollbarWidth;if(scrollbarWidth==null){var scr=null;var inn=null;var wNoScroll=0;var wScroll=0;scr=document.createElement('div');scr.style.position='absolute';scr.style.top='-1000px';scr.style.left='-1000px';scr.style.width='100px';scr.style.height='50px';scr.style.overflow='hidden';inn=document.createElement('div');inn.style.width='100%';inn.style.height='200px';scr.appendChild(inn);document.body.appendChild(scr);wNoScroll=inn.offsetWidth;scr.style.overflow='scroll';wScroll=inn.offsetWidth;document.body.removeChild(document.body.lastChild);Municipia.Util._scrollbarWidth=(wNoScroll-wScroll);scrollbarWidth=Municipia.Util._scrollbarWidth;}
return scrollbarWidth;};Municipia.Util.sum=function(array){for(var i=0,sum=0;i<array.length;sum+=array[i++]);return sum;};Municipia.Util.max=function(array){return Math.max.apply({},array);};Municipia.Util.min=function(array){return Math.min.apply({},array);};Municipia.Util.getIconUrl=function(wmsUrl,options){if(!options.layer){OpenLayers.Console.warn('Missing required layer option in Municipia.Util.getIconUrl');return'';}
if(!options.rule){options.rule=options.layer;}
if(wmsUrl.indexOf("?")<0){wmsUrl+="?";}else if(wmsUrl.lastIndexOf('&')!=(wmsUrl.length-1)){if(wmsUrl.indexOf("?")!=(wmsUrl.length-1)){wmsUrl+="&";}}
var options=OpenLayers.Util.extend({layer:"",rule:"",service:"WMS",version:"1.1.1",request:"GetLegendGraphic",format:"image/png",width:16,height:16},options);options=OpenLayers.Util.upperCaseObject(options);return wmsUrl+OpenLayers.Util.getParameterString(options);};Municipia.Util.arrayEqual=function(a,b){if(a==null||b==null)
return false;if(typeof(a)!='object'||typeof(b)!='object')
return false;if(a.length!=b.length)
return false;for(var i=0;i<a.length;i++){if(typeof(a[i])!=typeof(b[i]))
return false;if(a[i]!=b[i])
return false;}
return true;};Municipia.Util.isIE7=function(){var ua=navigator.userAgent.toLowerCase();return ua.indexOf("msie 7")>-1;};Municipia.Util.relativeToAbsoluteURL=function(source){if(/^\w+:/.test(source)||!source){return source;}
var h=location.protocol+"//"+location.host;if(source.indexOf("/")==0){return h+source;}
var p=location.pathname.replace(/\/[^\/]*$/,'');return h+p+"/"+source;};Municipia.Util.fixArray=function(subs){if(subs==''||subs==null){return[];}else if(subs instanceof Array){return subs;}else{return subs.split(',');}};Municipia.Util.getProperty=function(layer,prop){var property=prop;var result="";if(layer[property]!=undefined)
result=layer[property];else if(layer.params!=null&&layer.params[property]!=undefined)
result=layer.params[property];else if(layer.params!=null&&layer.params[property.toUpperCase()]!=undefined)
result=layer.params[property.toUpperCase()];return result;};﻿
OpenLayers.Map.prototype.uniqueObjects=null;OpenLayers.Map.prototype.initialize=function(div,options){if(arguments.length===1&&typeof div==="object"){options=div;div=options&&options.div;}
this.uniqueObjects={};this.tileSize=new OpenLayers.Size(OpenLayers.Map.TILE_WIDTH,OpenLayers.Map.TILE_HEIGHT);this.maxExtent=new OpenLayers.Bounds(-180,-90,180,90);this.paddingForPopups=new OpenLayers.Bounds(15,15,15,15);OpenLayers.Util.extend(this,options);this.id=OpenLayers.Util.createUniqueID("OpenLayers_Map_");this.div=OpenLayers.Util.getElement(div);if(!this.div){this.div=document.createElement("div");this.div.style.height="1px";this.div.style.width="1px";}
OpenLayers.Element.addClass(this.div,'olMap');var id=this.div.id+"_OpenLayers_ViewPort";this.viewPortDiv=OpenLayers.Util.createDiv(id,null,null,null,"relative",null,"hidden");this.viewPortDiv.style.width="100%";this.viewPortDiv.style.height="100%";this.viewPortDiv.className="olMapViewport";this.div.appendChild(this.viewPortDiv);id=this.div.id+"_OpenLayers_Container";this.layerContainerDiv=OpenLayers.Util.createDiv(id);this.layerContainerDiv.style.zIndex=this.Z_INDEX_BASE['Popup']-1;this.viewPortDiv.appendChild(this.layerContainerDiv);this.events=new OpenLayers.Events(this,this.div,this.EVENT_TYPES,this.fallThrough,{includeXY:true});this.updateSize();if(this.eventListeners instanceof Object){this.events.on(this.eventListeners);}
this.events.register("movestart",this,this.updateSize);if(OpenLayers.String.contains(navigator.appName,"Microsoft")){this.events.register("resize",this,function(){this.updateSize(true);});}else{this.updateSizeDestroy=OpenLayers.Function.bind(function(){this.updateSize(true);},this);OpenLayers.Event.observe(window,'resize',this.updateSizeDestroy);}
if(this.theme){var addNode=true;var nodes=document.getElementsByTagName('link');for(var i=0,len=nodes.length;i<len;++i){if(OpenLayers.Util.isEquivalentUrl(nodes.item(i).href,this.theme)){addNode=false;break;}}
if(addNode){var cssNode=document.createElement('link');cssNode.setAttribute('rel','stylesheet');cssNode.setAttribute('type','text/css');cssNode.setAttribute('href',this.theme);document.getElementsByTagName('head')[0].appendChild(cssNode);}}
this.layers=[];if(this.controls==null){if(OpenLayers.Control!=null){this.controls=[new OpenLayers.Control.Navigation(),new OpenLayers.Control.PanZoom(),new OpenLayers.Control.ArgParser(),new OpenLayers.Control.Attribution()];}else{this.controls=[];}}
for(var i=0,len=this.controls.length;i<len;i++){this.addControlToMap(this.controls[i]);}
this.popups=[];this.unloadDestroy=OpenLayers.Function.bind(this.destroy,this);OpenLayers.Event.observe(window,'unload',this.unloadDestroy);};OpenLayers.Map.prototype.getCurrentSize=function(){var size=new OpenLayers.Size(this.div.clientWidth,this.div.clientHeight);if(size.w==0&&size.h==0||isNaN(size.w)&&isNaN(size.h)){var dim=OpenLayers.Element.getDimensions(this.div);size.w=dim.width;size.h=dim.height;}
if(size.w==0&&size.h==0||isNaN(size.w)&&isNaN(size.h)){size.w=parseInt(this.div.style.width);size.h=parseInt(this.div.style.height);}
return size;};Ext.namespace("GeoExt","GeoExt.data");GeoExt.data.LayerReader=function(meta,recordType){meta=meta||{};if(!(recordType instanceof Function)){recordType=GeoExt.data.LayerRecord.create(recordType||meta.fields||{});}
GeoExt.data.LayerReader.superclass.constructor.call(this,meta,recordType);};Ext.extend(GeoExt.data.LayerReader,Ext.data.DataReader,{totalRecords:null,readRecords:function(layers){var records=[];if(layers){var recordType=this.recordType,fields=recordType.prototype.fields;var i,lenI,j,lenJ,layer,values,field,v;for(i=0,lenI=layers.length;i<lenI;i++){layer=layers[i];values={};for(j=0,lenJ=fields.length;j<lenJ;j++){field=fields.items[j];v=layer[field.mapping||field.name]||field.defaultValue;v=field.convert(v);values[field.name]=v;}
values.layer=layer;records[records.length]=new recordType(values,layer.id);}}
return{records:records,totalRecords:this.totalRecords!=null?this.totalRecords:records.length};}});Ext.namespace("GeoExt.data");GeoExt.data.LayerRecord=Ext.data.Record.create([{name:"layer"},{name:"title",type:"string",mapping:"name"}]);GeoExt.data.LayerRecord.create=function(o){var f=Ext.extend(GeoExt.data.LayerRecord,{});var p=f.prototype;p.fields=new Ext.util.MixedCollection(false,function(field){return field.name;});GeoExt.data.LayerRecord.prototype.fields.each(function(f){p.fields.add(f);});if(o){for(var i=0,len=o.length;i<len;i++){p.fields.add(new Ext.data.Field(o[i]));}}
f.getField=function(name){return p.fields.get(name);};return f;};Ext.namespace("GeoExt.data");GeoExt.data.LayerStoreMixin={map:null,reader:null,constructor:function(config){config=config||{};config.reader=config.reader||new GeoExt.data.LayerReader({},config.fields);delete config.fields;var map=config.map instanceof GeoExt.MapPanel?config.map.map:config.map;delete config.map;if(config.layers){config.data=config.layers;}
delete config.layers;var options={initDir:config.initDir};delete config.initDir;arguments.callee.superclass.constructor.call(this,config);if(map){this.bind(map,options);}},bind:function(map,options){if(this.map){return;}
this.map=map;options=options||{};var initDir=options.initDir;if(options.initDir==undefined){initDir=GeoExt.data.LayerStore.MAP_TO_STORE|GeoExt.data.LayerStore.STORE_TO_MAP;}
var layers=map.layers.slice(0);if(initDir&GeoExt.data.LayerStore.STORE_TO_MAP){this.each(function(record){this.map.addLayer(record.get("layer"));},this);}
if(initDir&GeoExt.data.LayerStore.MAP_TO_STORE){this.loadData(layers,true);}
map.events.on({"changelayer":this.onChangeLayer,"addlayer":this.onAddLayer,"removelayer":this.onRemoveLayer,scope:this});this.on({"load":this.onLoad,"clear":this.onClear,"add":this.onAdd,"remove":this.onRemove,"update":this.onUpdate,scope:this});this.data.on({"replace":this.onReplace,scope:this});},unbind:function(){if(this.map){this.map.events.un({"changelayer":this.onChangeLayer,"addlayer":this.onAddLayer,"removelayer":this.onRemoveLayer,scope:this});this.un("load",this.onLoad,this);this.un("clear",this.onClear,this);this.un("add",this.onAdd,this);this.un("remove",this.onRemove,this);this.data.un("replace",this.onReplace,this);this.map=null;}},onChangeLayer:function(evt){var layer=evt.layer;var recordIndex=this.findBy(function(rec,id){return rec.get("layer")===layer;});if(recordIndex>-1){var record=this.getAt(recordIndex);if(evt.property==="order"){if(!this._adding&&!this._removing){var layerIndex=this.map.getLayerIndex(layer);if(layerIndex!==recordIndex){this._removing=true;this.remove(record);delete this._removing;this._adding=true;this.insert(layerIndex,[record]);delete this._adding;}}}else if(evt.property==="name"){record.set("title",layer.name);}else{this.fireEvent("update",this,record,Ext.data.Record.EDIT);}}},onAddLayer:function(evt){if(!this._adding){var layer=evt.layer;this._adding=true;this.loadData([layer],true);delete this._adding;}},onRemoveLayer:function(evt){if(this.map.unloadDestroy){if(!this._removing){var layer=evt.layer;this._removing=true;this.remove(this.getById(layer.id));delete this._removing;}}else{this.unbind();}},onLoad:function(store,records,options){if(!Ext.isArray(records)){records=[records];}
if(options&&!options.add){this._removing=true;for(var i=this.map.layers.length-1;i>=0;i--){this.map.removeLayer(this.map.layers[i]);}
delete this._removing;var len=records.length;if(len>0){var layers=new Array(len);for(var j=0;j<len;j++){layers[j]=records[j].get("layer");}
this._adding=true;this.map.addLayers(layers);delete this._adding;}}},onClear:function(store){this._removing=true;for(var i=this.map.layers.length-1;i>=0;i--){this.map.removeLayer(this.map.layers[i]);}
delete this._removing;},onAdd:function(store,records,index){if(!this._adding){this._adding=true;var layer;for(var i=records.length-1;i>=0;--i){layer=records[i].get("layer");this.map.addLayer(layer);if(index!==this.map.layers.length-1){this.map.setLayerIndex(layer,index);}}
delete this._adding;}},onRemove:function(store,record,index){if(!this._removing){var layer=record.get("layer");if(this.map.getLayer(layer.id)!=null){this._removing=true;this.removeMapLayer(record);delete this._removing;}}},onUpdate:function(store,record,operation){if(operation===Ext.data.Record.EDIT){var layer=record.get("layer");var title=record.get("title");if(title!==layer.name){layer.setName(title);}}},removeMapLayer:function(record){this.map.removeLayer(record.get("layer"));},onReplace:function(key,oldRecord,newRecord){this.removeMapLayer(oldRecord);},destroy:function(){this.unbind();GeoExt.data.LayerStore.superclass.destroy.call(this);}};GeoExt.data.LayerStore=Ext.extend(Ext.data.Store,GeoExt.data.LayerStoreMixin);GeoExt.data.LayerStore.MAP_TO_STORE=1;GeoExt.data.LayerStore.STORE_TO_MAP=2;Ext.namespace("GeoExt");GeoExt.MapPanel=Ext.extend(Ext.Panel,{map:null,layers:null,center:null,zoom:null,extent:null,initComponent:function(){if(!(this.map instanceof OpenLayers.Map)){this.map=new OpenLayers.Map(Ext.applyIf(this.map||{},{allOverlays:true}));}
var layers=this.layers;if(!layers||layers instanceof Array){this.layers=new GeoExt.data.LayerStore({layers:layers,map:this.map});}
if(typeof this.center=="string"){this.center=OpenLayers.LonLat.fromString(this.center);}else if(this.center instanceof Array){this.center=new OpenLayers.LonLat(this.center[0],this.center[1]);}
if(typeof this.extent=="string"){this.extent=OpenLayers.Bounds.fromString(this.extent);}else if(this.extent instanceof Array){this.extent=OpenLayers.Bounds.fromArray(this.extent);}
GeoExt.MapPanel.superclass.initComponent.call(this);},updateMapSize:function(){if(this.map){this.map.updateSize();}},renderMap:function(){var map=this.map;var setCenter=map.setCenter;map.setCenter=function(){};map.render(this.body.dom);map.setCenter=setCenter;if(map.layers.length>0){if(this.center||this.zoom!=null){map.setCenter(this.center,this.zoom);}else if(this.extent){map.zoomToExtent(this.extent);}else{map.zoomToMaxExtent();}}},afterRender:function(){GeoExt.MapPanel.superclass.afterRender.apply(this,arguments);if(!this.ownerCt){this.renderMap();}else{this.ownerCt.on("move",this.updateMapSize,this);this.ownerCt.on({"afterlayout":{fn:this.renderMap,scope:this,single:true}});}},onResize:function(){GeoExt.MapPanel.superclass.onResize.apply(this,arguments);this.updateMapSize();},onBeforeAdd:function(item){if(typeof item.addToMapPanel==="function"){item.addToMapPanel(this);}
GeoExt.MapPanel.superclass.onBeforeAdd.apply(this,arguments);},remove:function(item,autoDestroy){if(typeof item.removeFromMapPanel==="function"){item.removeFromMapPanel(this);}
GeoExt.MapPanel.superclass.remove.apply(this,arguments);},beforeDestroy:function(){if(this.ownerCt){this.ownerCt.un("move",this.updateMapSize,this);}
if(!this.initialConfig.map||!(this.initialConfig.map instanceof OpenLayers.Map)){if(this.map&&this.map.destroy){this.map.destroy();}}
delete this.map;GeoExt.MapPanel.superclass.beforeDestroy.apply(this,arguments);}});GeoExt.MapPanel.guess=function(){return Ext.ComponentMgr.all.find(function(o){return o instanceof GeoExt.MapPanel;});};Ext.reg('gx_mappanel',GeoExt.MapPanel);Municipia.ProxyHost="";Municipia.nullHandler=function(request){Municipia.Console.userError(Municipia.i18n("unhandledRequest",{'statusText':request.statusText}));};Municipia.loadURL=function(uri,params,caller,onComplete,onFailure){if(typeof params=='string'){params=Municipia.Util.getParameters(params);}
var success=(onComplete)?onComplete:Municipia.nullHandler;var failure=(onFailure)?onFailure:Municipia.nullHandler;return Municipia.Request.GET({url:uri,params:params,success:success,failure:failure,scope:caller});};Municipia.parseXMLString=function(text){var index=text.indexOf('<');if(index>0){text=text.substring(index);}
var ajaxResponse=Municipia.Util.Try(function(){var xmldom=new ActiveXObject('Microsoft.XMLDOM');xmldom.loadXML(text);return xmldom;},function(){return new DOMParser().parseFromString(text,'text/xml');},function(){var req=new XMLHttpRequest();req.open("GET","data:"+"text/xml"+";charset=utf-8,"+encodeURIComponent(text),false);if(req.overrideMimeType){req.overrideMimeType("text/xml");}
req.send(null);return req.responseXML;});return ajaxResponse;};Municipia.Ajax={emptyFunction:function(){},getTransport:function(){return Municipia.Util.Try(function(){return new XMLHttpRequest();},function(){return new ActiveXObject('Msxml2.XMLHTTP');},function(){return new ActiveXObject('Microsoft.XMLHTTP');})||false;},activeRequestCount:0};Municipia.Ajax.Responders={responders:[],register:function(responderToAdd){for(var i=0;i<this.responders.length;i++){if(responderToAdd==this.responders[i]){return;}}
this.responders.push(responderToAdd);},unregister:function(responderToRemove){Municipia.Util.removeItem(this.reponders,responderToRemove);},dispatch:function(callback,request,transport){var responder;for(var i=0;i<this.responders.length;i++){responder=this.responders[i];if(responder[callback]&&typeof responder[callback]=='function'){try{responder[callback].apply(responder,[request,transport]);}catch(e){}}}}};Municipia.Ajax.Responders.register({onCreate:function(){Municipia.Ajax.activeRequestCount++;},onComplete:function(){Municipia.Ajax.activeRequestCount--;}});Municipia.Ajax.Base=Municipia.Class({initialize:function(options){this.options={method:'post',asynchronous:true,contentType:'application/xml',parameters:''};Municipia.Util.extend(this.options,options||{});this.options.method=this.options.method.toLowerCase();if(typeof this.options.parameters=='string'){this.options.parameters=Municipia.Util.getParameters(this.options.parameters);}}});Municipia.Ajax.Request=Municipia.Class(Municipia.Ajax.Base,{_complete:false,initialize:function(url,options){Municipia.Ajax.Base.prototype.initialize.apply(this,[options]);if(Municipia.ProxyHost&&Municipia.String.startsWith(url,"http")){url=Municipia.ProxyHost+encodeURIComponent(url);}
this.transport=Municipia.Ajax.getTransport();this.request(url);},request:function(url){this.url=url;this.method=this.options.method;var params=Municipia.Util.extend({},this.options.parameters);if(this.method!='get'&&this.method!='post'){params['_method']=this.method;this.method='post';}
this.parameters=params;if(params=Municipia.Util.getParameterString(params)){if(this.method=='get'){this.url+=((this.url.indexOf('?')>-1)?'&':'?')+params;}else if(/Konqueror|Safari|KHTML/.test(navigator.userAgent)){params+='&_=';}}
try{var response=new Municipia.Ajax.Response(this);if(this.options.onCreate){this.options.onCreate(response);}
Municipia.Ajax.Responders.dispatch('onCreate',this,response);this.transport.open(this.method.toUpperCase(),this.url,this.options.asynchronous);if(this.options.asynchronous){window.setTimeout(Municipia.Function.bind(this.respondToReadyState,this,1),10);}
this.transport.onreadystatechange=Municipia.Function.bind(this.onStateChange,this);this.setRequestHeaders();this.body=this.method=='post'?(this.options.postBody||params):null;this.transport.send(this.body);if(!this.options.asynchronous&&this.transport.overrideMimeType){this.onStateChange();}}catch(e){this.dispatchException(e);}},onStateChange:function(){var readyState=this.transport.readyState;if(readyState>1&&!((readyState==4)&&this._complete)){this.respondToReadyState(this.transport.readyState);}},setRequestHeaders:function(){var headers={'X-Requested-With':'XMLHttpRequest','Accept':'text/javascript, text/html, application/xml, text/xml, */*','Municipia':true};if(this.method=='post'){headers['Content-type']=this.options.contentType+
(this.options.encoding?'; charset='+this.options.encoding:'');if(this.transport.overrideMimeType&&(navigator.userAgent.match(/Gecko\/(\d{4})/)||[0,2005])[1]<2005){headers['Connection']='close';}}
if(typeof this.options.requestHeaders=='object'){var extras=this.options.requestHeaders;if(typeof extras.push=='function'){for(var i=0,length=extras.length;i<length;i+=2){headers[extras[i]]=extras[i+1];}}else{for(var i in extras){headers[i]=extras[i];}}}
for(var name in headers){this.transport.setRequestHeader(name,headers[name]);}},success:function(){var status=this.getStatus();return!status||(status>=200&&status<300);},getStatus:function(){try{return this.transport.status||0;}catch(e){return 0;}},respondToReadyState:function(readyState){var state=Municipia.Ajax.Request.Events[readyState];var response=new Municipia.Ajax.Response(this);if(state=='Complete'){try{this._complete=true;(this.options['on'+response.status]||this.options['on'+(this.success()?'Success':'Failure')]||Municipia.Ajax.emptyFunction)(response);}catch(e){this.dispatchException(e);}
var contentType=response.getHeader('Content-type');}
try{(this.options['on'+state]||Municipia.Ajax.emptyFunction)(response);Municipia.Ajax.Responders.dispatch('on'+state,this,response);}catch(e){this.dispatchException(e);}
if(state=='Complete'){this.transport.onreadystatechange=Municipia.Ajax.emptyFunction;}},getHeader:function(name){try{return this.transport.getResponseHeader(name);}catch(e){return null;}},dispatchException:function(exception){var handler=this.options.onException;if(handler){handler(this,exception);Municipia.Ajax.Responders.dispatch('onException',this,exception);}else{var listener=false;var responders=Municipia.Ajax.Responders.responders;for(var i=0;i<responders.length;i++){if(responders[i].onException){listener=true;break;}}
if(listener){Municipia.Ajax.Responders.dispatch('onException',this,exception);}else{throw exception;}}}});Municipia.Ajax.Request.Events=['Uninitialized','Loading','Loaded','Interactive','Complete'];Municipia.Ajax.Response=Municipia.Class({status:0,statusText:'',initialize:function(request){this.request=request;var transport=this.transport=request.transport,readyState=this.readyState=transport.readyState;if((readyState>2&&!(!!(window.attachEvent&&!window.opera)))||readyState==4){this.status=this.getStatus();this.statusText=this.getStatusText();this.responseText=transport.responseText==null?'':String(transport.responseText);}
if(readyState==4){var xml=transport.responseXML;this.responseXML=xml===undefined?null:xml;}},getStatus:Municipia.Ajax.Request.prototype.getStatus,getStatusText:function(){try{return this.transport.statusText||'';}catch(e){return'';}},getHeader:Municipia.Ajax.Request.prototype.getHeader,getResponseHeader:function(name){return this.transport.getResponseHeader(name);}});Municipia.Ajax.getElementsByTagNameNS=function(parentnode,nsuri,nsprefix,tagname){var elem=null;if(parentnode.getElementsByTagNameNS){elem=parentnode.getElementsByTagNameNS(nsuri,tagname);}else{elem=parentnode.getElementsByTagName(nsprefix+':'+tagname);}
return elem;};Municipia.Ajax.serializeXMLToString=function(xmldom){var serializer=new XMLSerializer();var data=serializer.serializeToString(xmldom);return data;};Municipia.Bounds=Municipia.Class({left:null,bottom:null,right:null,top:null,initialize:function(left,bottom,right,top){if(left!=null){this.left=parseFloat(left);}
if(bottom!=null){this.bottom=parseFloat(bottom);}
if(right!=null){this.right=parseFloat(right);}
if(top!=null){this.top=parseFloat(top);}},clone:function(){return new Municipia.Bounds(this.left,this.bottom,this.right,this.top);},equals:function(bounds){var equals=false;if(bounds!=null){equals=((this.left==bounds.left)&&(this.right==bounds.right)&&(this.top==bounds.top)&&(this.bottom==bounds.bottom));}
return equals;},toString:function(){return("left-bottom=("+this.left+","+this.bottom+")"
+" right-top=("+this.right+","+this.top+")");},toArray:function(){return[this.left,this.bottom,this.right,this.top];},toBBOX:function(decimal){if(decimal==null){decimal=6;}
var mult=Math.pow(10,decimal);var bbox=Math.round(this.left*mult)/mult+","+
Math.round(this.bottom*mult)/mult+","+
Math.round(this.right*mult)/mult+","+
Math.round(this.top*mult)/mult;return bbox;},toGeometry:function(){return new Municipia.Geometry.Polygon([new Municipia.Geometry.LinearRing([new Municipia.Geometry.Point(this.left,this.bottom),new Municipia.Geometry.Point(this.right,this.bottom),new Municipia.Geometry.Point(this.right,this.top),new Municipia.Geometry.Point(this.left,this.top)])]);},getWidth:function(){return(this.right-this.left);},getHeight:function(){return(this.top-this.bottom);},getSize:function(){return new Municipia.Size(this.getWidth(),this.getHeight());},getCenterPixel:function(){return new Municipia.Pixel((this.left+this.right)/2,(this.bottom+this.top)/2);},getCenterLonLat:function(){return new Municipia.LonLat((this.left+this.right)/2,(this.bottom+this.top)/2);},scale:function(ratio,origin){if(origin==null){origin=this.getCenterLonLat();}
var bounds=[];var origx,origy;if(origin.CLASS_NAME=="Municipia.LonLat"){origx=origin.lon;origy=origin.lat;}else{origx=origin.x;origy=origin.y;}
var left=(this.left-origx)*ratio+origx;var bottom=(this.bottom-origy)*ratio+origy;var right=(this.right-origx)*ratio+origx;var top=(this.top-origy)*ratio+origy;return new Municipia.Bounds(left,bottom,right,top);},add:function(x,y){if((x==null)||(y==null)){var msg=Municipia.i18n("boundsAddError");Municipia.Console.error(msg);return null;}
return new Municipia.Bounds(this.left+x,this.bottom+y,this.right+x,this.top+y);},extend:function(object){var bounds=null;if(object){switch(object.CLASS_NAME){case"Municipia.LonLat":bounds=new Municipia.Bounds(object.lon,object.lat,object.lon,object.lat);break;case"Municipia.Geometry.Point":bounds=new Municipia.Bounds(object.x,object.y,object.x,object.y);break;case"Municipia.Bounds":bounds=object;break;}
if(bounds){if((this.left==null)||(bounds.left<this.left)){this.left=bounds.left;}
if((this.bottom==null)||(bounds.bottom<this.bottom)){this.bottom=bounds.bottom;}
if((this.right==null)||(bounds.right>this.right)){this.right=bounds.right;}
if((this.top==null)||(bounds.top>this.top)){this.top=bounds.top;}}}},containsLonLat:function(ll,inclusive){return this.contains(ll.lon,ll.lat,inclusive);},containsPixel:function(px,inclusive){return this.contains(px.x,px.y,inclusive);},contains:function(x,y,inclusive){if(inclusive==null){inclusive=true;}
var contains=false;if(inclusive){contains=((x>=this.left)&&(x<=this.right)&&(y>=this.bottom)&&(y<=this.top));}else{contains=((x>this.left)&&(x<this.right)&&(y>this.bottom)&&(y<this.top));}
return contains;},intersectsBounds:function(bounds,inclusive){if(inclusive==null){inclusive=true;}
var inBottom=(bounds.bottom==this.bottom&&bounds.top==this.top)?true:(((bounds.bottom>this.bottom)&&(bounds.bottom<this.top))||((this.bottom>bounds.bottom)&&(this.bottom<bounds.top)));var inTop=(bounds.bottom==this.bottom&&bounds.top==this.top)?true:(((bounds.top>this.bottom)&&(bounds.top<this.top))||((this.top>bounds.bottom)&&(this.top<bounds.top)));var inRight=(bounds.right==this.right&&bounds.left==this.left)?true:(((bounds.right>this.left)&&(bounds.right<this.right))||((this.right>bounds.left)&&(this.right<bounds.right)));var inLeft=(bounds.right==this.right&&bounds.left==this.left)?true:(((bounds.left>this.left)&&(bounds.left<this.right))||((this.left>bounds.left)&&(this.left<bounds.right)));return(this.containsBounds(bounds,true,inclusive)||bounds.containsBounds(this,true,inclusive)||((inTop||inBottom)&&(inLeft||inRight)));},containsBounds:function(bounds,partial,inclusive){if(partial==null){partial=false;}
if(inclusive==null){inclusive=true;}
var inLeft;var inTop;var inRight;var inBottom;if(inclusive){inLeft=(bounds.left>=this.left)&&(bounds.left<=this.right);inTop=(bounds.top>=this.bottom)&&(bounds.top<=this.top);inRight=(bounds.right>=this.left)&&(bounds.right<=this.right);inBottom=(bounds.bottom>=this.bottom)&&(bounds.bottom<=this.top);}else{inLeft=(bounds.left>this.left)&&(bounds.left<this.right);inTop=(bounds.top>this.bottom)&&(bounds.top<this.top);inRight=(bounds.right>this.left)&&(bounds.right<this.right);inBottom=(bounds.bottom>this.bottom)&&(bounds.bottom<this.top);}
return(partial)?(inTop||inBottom)&&(inLeft||inRight):(inTop&&inLeft&&inBottom&&inRight);},determineQuadrant:function(lonlat){var quadrant="";var center=this.getCenterLonLat();quadrant+=(lonlat.lat<center.lat)?"b":"t";quadrant+=(lonlat.lon<center.lon)?"l":"r";return quadrant;},transform:function(source,dest){var ll=Municipia.Projection.transform({'x':this.left,'y':this.bottom},source,dest);var lr=Municipia.Projection.transform({'x':this.right,'y':this.bottom},source,dest);var ul=Municipia.Projection.transform({'x':this.left,'y':this.top},source,dest);var ur=Municipia.Projection.transform({'x':this.right,'y':this.top},source,dest);this.left=Math.min(ll.x,ul.x);this.bottom=Math.min(ll.y,lr.y);this.right=Math.max(lr.x,ur.x);this.top=Math.max(ul.y,ur.y);return this;},wrapDateLine:function(maxExtent,options){options=options||{};var leftTolerance=options.leftTolerance||0;var rightTolerance=options.rightTolerance||0;var newBounds=this.clone();if(maxExtent){while(newBounds.left<maxExtent.left&&(newBounds.right-rightTolerance)<=maxExtent.left){newBounds=newBounds.add(maxExtent.getWidth(),0);}
while((newBounds.left+leftTolerance)>=maxExtent.right&&newBounds.right>maxExtent.right){newBounds=newBounds.add(-maxExtent.getWidth(),0);}}
return newBounds;},CLASS_NAME:"Municipia.Bounds"});Municipia.Bounds.fromString=function(str){var bounds=str.split(",");return Municipia.Bounds.fromArray(bounds);};Municipia.Bounds.fromArray=function(bbox){return new Municipia.Bounds(parseFloat(bbox[0]),parseFloat(bbox[1]),parseFloat(bbox[2]),parseFloat(bbox[3]));};Municipia.Bounds.fromSize=function(size){return new Municipia.Bounds(0,size.h,size.w,0);};Municipia.Bounds.oppositeQuadrant=function(quadrant){var opp="";opp+=(quadrant.charAt(0)=='t')?'b':'t';opp+=(quadrant.charAt(1)=='l')?'r':'l';return opp;};Municipia.Element={visible:function(element){return Municipia.Util.getElement(element).style.display!='none';},toggle:function(){for(var i=0,len=arguments.length;i<len;i++){var element=Municipia.Util.getElement(arguments[i]);var display=Municipia.Element.visible(element)?'hide':'show';Municipia.Element[display](element);}},hide:function(){for(var i=0,len=arguments.length;i<len;i++){var element=Municipia.Util.getElement(arguments[i]);element.style.display='none';}},show:function(){for(var i=0,len=arguments.length;i<len;i++){var element=Municipia.Util.getElement(arguments[i]);element.style.display='';}},remove:function(element){element=Municipia.Util.getElement(element);element.parentNode.removeChild(element);},getHeight:function(element){element=Municipia.Util.getElement(element);return element.offsetHeight;},getDimensions:function(element){element=Municipia.Util.getElement(element);if(Municipia.Element.getStyle(element,'display')!='none'){return{width:element.offsetWidth,height:element.offsetHeight};}
var els=element.style;var originalVisibility=els.visibility;var originalPosition=els.position;els.visibility='hidden';els.position='absolute';els.display='';var originalWidth=element.clientWidth;var originalHeight=element.clientHeight;els.display='none';els.position=originalPosition;els.visibility=originalVisibility;return{width:originalWidth,height:originalHeight};},hasClass:function(element,name){var names=element.className;return(!!names&&new RegExp("(^|\\s)"+name+"(\\s|$)").test(names));},addClass:function(element,name){if(!Municipia.Element.hasClass(element,name)){element.className+=(element.className?" ":"")+name;}
return element;},removeClass:function(element,name){var names=element.className;if(names){element.className=Municipia.String.trim(names.replace(new RegExp("(^|\\s+)"+name+"(\\s+|$)")," "));}
return element;},toggleClass:function(element,name){if(Municipia.Element.hasClass(element,name)){Municipia.Element.removeClass(element,name);}else{Municipia.Element.addClass(element,name);}
return element;},getStyle:function(element,style){element=Municipia.Util.getElement(element);var value=null;if(element&&element.style){value=element.style[Municipia.String.camelize(style)];if(!value){if(document.defaultView&&document.defaultView.getComputedStyle){var css=document.defaultView.getComputedStyle(element,null);value=css?css.getPropertyValue(style):null;}else if(element.currentStyle){value=element.currentStyle[Municipia.String.camelize(style)];}}
var positions=['left','top','right','bottom'];if(window.opera&&(Municipia.Util.indexOf(positions,style)!=-1)&&(Municipia.Element.getStyle(element,'position')=='static')){value='auto';}}
return value=='auto'?null:value;}};Municipia.LonLat=Municipia.Class({lon:0.0,lat:0.0,initialize:function(lon,lat){this.lon=parseFloat(lon);this.lat=parseFloat(lat);},toString:function(){return("lon="+this.lon+",lat="+this.lat);},toShortString:function(){return(this.lon+", "+this.lat);},clone:function(){return new Municipia.LonLat(this.lon,this.lat);},add:function(lon,lat){if((lon==null)||(lat==null)){var msg=Municipia.i18n("lonlatAddError");Municipia.Console.error(msg);return null;}
return new Municipia.LonLat(this.lon+lon,this.lat+lat);},equals:function(ll){var equals=false;if(ll!=null){equals=((this.lon==ll.lon&&this.lat==ll.lat)||(isNaN(this.lon)&&isNaN(this.lat)&&isNaN(ll.lon)&&isNaN(ll.lat)));}
return equals;},transform:function(source,dest){var point=Municipia.Projection.transform({'x':this.lon,'y':this.lat},source,dest);this.lon=point.x;this.lat=point.y;return this;},wrapDateLine:function(maxExtent){var newLonLat=this.clone();if(maxExtent){while(newLonLat.lon<maxExtent.left){newLonLat.lon+=maxExtent.getWidth();}
while(newLonLat.lon>maxExtent.right){newLonLat.lon-=maxExtent.getWidth();}}
return newLonLat;},CLASS_NAME:"Municipia.LonLat"});Municipia.LonLat.fromString=function(str){var pair=str.split(",");return new Municipia.LonLat(parseFloat(pair[0]),parseFloat(pair[1]));};Municipia.Pixel=Municipia.Class({x:0.0,y:0.0,initialize:function(x,y){this.x=parseFloat(x);this.y=parseFloat(y);},toString:function(){return("x="+this.x+",y="+this.y);},clone:function(){return new Municipia.Pixel(this.x,this.y);},equals:function(px){var equals=false;if(px!=null){equals=((this.x==px.x&&this.y==px.y)||(isNaN(this.x)&&isNaN(this.y)&&isNaN(px.x)&&isNaN(px.y)));}
return equals;},add:function(x,y){if((x==null)||(y==null)){var msg=Municipia.i18n("pixelAddError");Municipia.Console.error(msg);return null;}
return new Municipia.Pixel(this.x+x,this.y+y);},offset:function(px){var newPx=this.clone();if(px){newPx=this.add(px.x,px.y);}
return newPx;},CLASS_NAME:"Municipia.Pixel"});Municipia.Size=Municipia.Class({w:0.0,h:0.0,initialize:function(w,h){this.w=parseFloat(w);this.h=parseFloat(h);},toString:function(){return("w="+this.w+",h="+this.h);},clone:function(){return new Municipia.Size(this.w,this.h);},equals:function(sz){var equals=false;if(sz!=null){equals=((this.w==sz.w&&this.h==sz.h)||(isNaN(this.w)&&isNaN(this.h)&&isNaN(sz.w)&&isNaN(sz.h)));}
return equals;},CLASS_NAME:"Municipia.Size"});Municipia.Control=Municipia.Class({id:null,map:null,div:null,type:null,allowSelection:false,displayClass:"",title:"",active:null,handler:null,eventListeners:null,events:null,EVENT_TYPES:["activate","deactivate"],initialize:function(options){this.displayClass=this.CLASS_NAME.replace("Municipia.","ol").replace(/\./g,"");Municipia.Util.extend(this,options);this.events=new Municipia.Events(this,null,this.EVENT_TYPES);if(this.eventListeners instanceof Object){this.events.on(this.eventListeners);}
if(this.id==null){this.id=Municipia.Util.createUniqueID(this.CLASS_NAME+"_");}},destroy:function(){if(this.events){if(this.eventListeners){this.events.un(this.eventListeners);}
this.events.destroy();this.events=null;}
this.eventListeners=null;if(this.handler){this.handler.destroy();this.handler=null;}
if(this.handlers){for(var key in this.handlers){if(this.handlers.hasOwnProperty(key)&&typeof this.handlers[key].destroy=="function"){this.handlers[key].destroy();}}
this.handlers=null;}
if(this.map){this.map.removeControl(this);this.map=null;}},setMap:function(map){this.map=map;if(this.handler){this.handler.setMap(map);}},draw:function(px){if(this.div==null){this.div=Municipia.Util.createDiv(this.id);this.div.className=this.displayClass;if(!this.allowSelection){this.div.className+=" olControlNoSelect";this.div.setAttribute("unselectable","on",0);this.div.onselectstart=function(){return(false);};}
if(this.title!=""){this.div.title=this.title;}}
if(px!=null){this.position=px.clone();}
this.moveTo(this.position);return this.div;},moveTo:function(px){if((px!=null)&&(this.div!=null)){this.div.style.left=px.x+"px";this.div.style.top=px.y+"px";}},activate:function(){if(this.active){return false;}
if(this.handler){this.handler.activate();}
this.active=true;this.events.triggerEvent("activate");return true;},deactivate:function(){if(this.active){if(this.handler){this.handler.deactivate();}
this.active=false;this.events.triggerEvent("deactivate");return true;}
return false;},CLASS_NAME:"Municipia.Control"});Municipia.Control.TYPE_BUTTON=1;Municipia.Control.TYPE_TOGGLE=2;Municipia.Control.TYPE_TOOL=3;﻿
OpenLayers.Control.Center=OpenLayers.Class(OpenLayers.Control,{type:OpenLayers.Control.TYPE_TOOL,draw:function(){this.handler=new OpenLayers.Handler.Click(this,{click:this.centrar});},activate:function(){return OpenLayers.Control.prototype.activate.apply(this,arguments);},deactivate:function(){return OpenLayers.Control.prototype.deactivate.apply(this,arguments);},centrar:function(event){if(event&&event.xy){this.map.setCenter(this.map.getLonLatFromPixel(event.xy),this.map.getZoom());}},CLASS_NAME:"OpenLayers.Control.Center"});OpenLayers.Control.CleanMap=OpenLayers.Class(OpenLayers.Control,{type:OpenLayers.Control.TYPE_BUTTON,layers:[],initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,arguments);},trigger:function(){if(this.layers.length==0){return;}
for(var i=0;i<this.layers.length;i++){var layer=this.layers[i];layer.destroyFeatures();}
removeLayerHighlight();},CLASS_NAME:"OpenLayers.Control.CleanMap"});OpenLayers.Control.Copyright=OpenLayers.Class(OpenLayers.Control,{element:null,text:"",initialize:function(options){OpenLayers.Control.prototype.initialize.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.element.innerHTML=this.text;return this.div;},CLASS_NAME:"OpenLayers.Control.Copyright"});OpenLayers.Control.DatumDisplayCoordinates=OpenLayers.Class(OpenLayers.Control,{element:null,initialize:function(options){OpenLayers.Control.prototype.initialize.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.updateDatumDisplay();return this.div;},updateDatumDisplay:function(){if(this.displayProjection.proj.title!=null)
this.element.innerHTML=this.displayProjection.proj.title;},CLASS_NAME:"OpenLayers.Control.DatumDisplayCoordinates"});﻿
OpenLayers.Control.DragPan.prototype.handlerOptions=null;OpenLayers.Control.DragPan.prototype.draw=function(){this.handlerOptions=OpenLayers.Util.extend({interval:this.interval},this.handlerOptions);this.handler=new OpenLayers.Handler.Drag(this,{"move":this.panMap,"done":this.panMapDone},this.handlerOptions);};OpenLayers.Control.Export2Data=OpenLayers.Class(OpenLayers.Control,{type:OpenLayers.Control.TYPE_BUTTON,layers:[],includeBaseLayers:false,includeVisibleOnly:false,printing:false,url:null,outputformat:'GML2',initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,arguments);},trigger:function(){if(!this.printing){if(this.map.baseLayer.numZoomLevels-this.map.getZoom()>2){Ext.Msg.alert(OpenLayers.i18n('export.information'),OpenLayers.i18n("export.not_zoom_correct"));return;}
Ext.MessageBox.confirm(OpenLayers.i18n("export.confirm"),OpenLayers.i18n("export.confirm_message")+" "+this.outputformat+"?",this.exportData,this);}},exportData:function(btn){if(btn=='yes'){var parameters={};var url,layerFullUrl,n,layer,gfiParams,layerList;if(this.layers.length==0){this.layers=this.map.layers;}
n=this.layers.length;layerList=[];var geometry_column="";for(var i=0;i<n;i++){layer=this.layers[i];var queryable=false;queryable=this.getProperty(layer,"export_data");if(((!this.includeBaseLayers&&!layer.isBaseLayer)||this.includeBaseLayers)&&((this.includeVisibleOnly&&layer.getVisibility()&&queryable&&layer.displayInLayerSwitcher)||(!this.includeVisibleOnly&&queryable)))
{var nameLayer="";nameLayer=this.getProperty(layer,"typename")||this.getProperty(layer,"layers");layerList.push(nameLayer);var column=this.getProperty(layer,"geometry_column");if(geometry_column==""&&column!="")
geometry_column=this.getProperty(layer,"geometry_column");}}
if(layerList.length>0){try{var charset="UTF-8";var params=OpenLayers.Util.applyDefaults({},this.params);var bbox=this.map.calculateBounds().left+","+this.map.calculateBounds().bottom+" "+this.map.calculateBounds().right+","+this.map.calculateBounds().top;OpenLayers.Request.POST({url:'GeocidMadeira.asmx/exportData',data:"{\"appID\":\""+app.appID+"\", \"sessionID\": \""+app.sessionID+"\", \"typename\": \""+layerList.join(',')+"\", \"gColumn\":\""+geometry_column+"\", \"bbox\":\""+bbox+"\", \"srs\": \""+((this.map.getProjection()=="none")?"EPSG:4326":this.map.getProjection())+"\", \"outputformat\": \""+this.outputformat+"\"}",params:params,headers:{'Content-type':"application/json",'Content-length':1,'Connection':"close"},callback:function(request){if(request.status>=200&&request.status<300){var json=new OpenLayers.Format.JSON();var answer=json.read(eval(request.responseText))
if(answer==null&&request.responseXML!=null&&request.responseXML.firstChild!=null&&request.responseXML.firstChild.nextSibling!=null){answer=json.read(request.responseXML.firstChild.nextSibling.text);}
if(answer&&answer.getURL){this.openData(answer,request);}else{this.onFailure(request);}}else{this.onFailure(request);}},scope:this});}catch(err){OpenLayers.Console.warn("Cannot request the print service by AJAX. You must set the 'OpenLayers.ProxyHost' variable. Fallback to GET method");}
this.printing=true;loadFn(true,'map-toolbar');}else{Ext.Msg.alert(OpenLayers.i18n('export.information'),OpenLayers.i18n("export.not_found_theme"));}}},openData:function(answer){this.printing=false;loadFn(false,'map-toolbar');OpenLayers.Console.info(answer.getURL);window.open(answer.getURL,'_blank');},onFailure:function(request){this.printing=false;Ext.Msg.alert(OpenLayers.i18n('export.error'),OpenLayers.i18n('export.unableToExport'));loadFn(false,'map-toolbar');if(this.mask)
this.mask.hide();},getProperty:function(layer,prop){var property=prop;var result="";if(layer[property]!=undefined)
result=layer[property];else if(layer.params!=null&&layer.params[property]!=undefined)
result=layer.params[property];else if(layer.params!=null&&layer.params[property.toUpperCase()]!=undefined)
result=layer.params[property.toUpperCase()];return result;},CLASS_NAME:"OpenLayers.Control.Export2Data"});OpenLayers.Control.Footer=OpenLayers.Class(OpenLayers.Control,{element:null,initialize:function(element,options){OpenLayers.Control.prototype.initialize.apply(this,[options]);this.element=OpenLayers.Util.getElement(element);},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);if(!this.element){this.element=document.createElement("div");this.element.className=this.displayClass;this.div.appendChild(this.element);}
return this.div;},CLASS_NAME:"OpenLayers.Control.Footer"});OpenLayers.Control.GetFeatureInfo=OpenLayers.Class(OpenLayers.Control,{type:OpenLayers.Control.TYPE_TOOL,layers:[],includeBaseLayers:false,includeVisibleOnly:true,maxFeatures:3,radius:15,infoFormat:"text/plain",popupInfoX:null,popupInfoY:null,onSuccess:function(request){var popup_info="";var doc=request.responseXML;if(!doc||!doc.documentElement){doc=request.responseText;}
var options={'extractAttributes':true};OpenLayers.Util.extend(options,this.formatOptions);var gml=new OpenLayers.Format.GML(options);var features=gml.read(doc);if(!(features instanceof Array)){features=[features];}
if(features.length==0){loadFn(false,'map-toolbar');Ext.Msg.alert(OpenLayers.i18n('print.information'),OpenLayers.i18n('info.No topics to display'));return}
var className=features.length>1?'callout_big':'callout_small';var sizePopup=features.length>1?new OpenLayers.Size(214,180):new OpenLayers.Size(142,105);var leftBtnFechar=features.length>1?'196px':'124px';var listTipos=new Array();var tipo="";var popup_info="<div class='"+className+"'><div class='callout_desc'><div><h1>Propriedades</h1></br></br>";for(var i=0,len=features.length;i<len;i++){var feature=features[i];var atributos=feature.attributes;if(atributos.DESIGNACAO){var subtipo=atributos.DESIGNACAO;if(atributos.TIPO!=tipo){tipo=atributos.TIPO;if(!listTipos[tipo]){listTipos.push(tipo);listTipos[tipo]=new Array();}
popup_info+="<p><span style='font-weight:bolder;'>"+tipo+":</span></br></p>";}
var listsubtipo=listTipos[tipo];var exist=false;for(var x=0;x<listsubtipo.length;x++)
{if(listsubtipo[x]===subtipo){exist=true;break;}}
if(!exist){listsubtipo.push(subtipo);popup_info+="<p style='padding-left:4px;font-size:9px;'><span>- "+subtipo+"</span></p>";}}else{if(atributos.TIPO!=tipo){tipo=atributos.TIPO;if(!listTipos[tipo]){listTipos.push(tipo);listTipos[tipo]=new Array();}
popup_info+="<p style='padding-left:4px;font-size:9px;'><span>- "+tipo+"</span></p>";}}}
popup_info+="</div></div></div>";popup_info+="<div style='border: 0px none ; overflow: hidden; position: absolute; top: 7px; left: "+leftBtnFechar+"; width: 20px; height: 15px;'><a href='javascript:popupDestroy()'><img src='images/popup/bot_fechar.gif' title='Fechar'/></a></div>";if(app.popupInfo!=null){app.popupInfo.destroy();app.popupInfo=null;}
app.popupInfo=new Municipia.Popup.Center("FeatureInfo",app.map.getLonLatFromPixel(new OpenLayers.Pixel(this.popupInfoX,this.popupInfoY)),sizePopup,popup_info,null,false);app.popupInfo.autoSize=false;app.popupInfo.closeOnMove=false;app.popupInfo.panMapIfOutOfView=true;app.popupInfo.overClass="featureMouseOver";app.popupInfo.setBackgroundColor('Transparent');app.map.addPopup(app.popupInfo);app.popupInfo.show();loadFn(false,'map-toolbar');},onFailure:function(response){},xOffset:0,yOffset:0,url:null,initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,[options]);this.handler=new OpenLayers.Handler.Click(this,{click:this.identify});},activate:function(){return OpenLayers.Control.prototype.activate.apply(this,arguments);},deactivate:function(){return OpenLayers.Control.prototype.deactivate.apply(this,arguments);},identify:function(ev){var parameters={};var url,layerFullUrl,n,layer,gfiParams,layerList;if(this.layers.length==0){this.layers=this.map.layers;}
n=this.layers.length;layerList=[];for(var i=0;i<n;i++){layer=this.layers[i];var queryable=false;queryable=this.getProperty(layer,"queryable");if(((!this.includeBaseLayers&&!layer.isBaseLayer)||this.includeBaseLayers)&&((this.includeVisibleOnly&&layer.getVisibility()&&queryable&&layer.displayInLayerSwitcher)||!this.includeVisibleOnly))
{var nameLayer="";nameLayer=this.getProperty(layer,"typename")||this.getProperty(layer,"layers");layerList.push(nameLayer);}}
if(layerList.length>0){gfiParams={SERVICE:"WMS",VERSION:"1.1.1",REQUEST:"GetFeatureInfo",EXCEPTIONS:"application/vnd.ogc.se_xml",SRS:(this.map.getProjection()=="none")?null:this.map.getProjection(),BBOX:layer.map.calculateBounds().toBBOX(),X:ev.xy.x+this.xOffset,Y:ev.xy.y+this.yOffset,INFO_FORMAT:this.infoFormat,STYLES:'',LAYERS:layerList.join(','),QUERY_LAYERS:layerList.join(','),WIDTH:layer.map.size.w,HEIGHT:layer.map.size.h,FEATURE_COUNT:this.maxFeatures}
if(this.url==null){Ext.Msg.alert(OpenLayers.i18n('print.information'),OpenLayers.i18n("URL not found."));return;}
layerFullUrl=OpenLayers.Layer.HTTPRequest.prototype.getFullRequestString(gfiParams," ");parameters=OpenLayers.Util.getParameters(layerFullUrl);this.popupInfoX=ev.xy.x;this.popupInfoY=ev.xy.y;loadFn(true,'map-toolbar');OpenLayers.Request.GET({url:this.url,params:parameters,success:this.onSuccess,failure:this.onFailure,scope:this});}else{Ext.Msg.alert(OpenLayers.i18n('print.information'),OpenLayers.i18n("Theme no found"));}},getProperty:function(layer,prop){var property=prop;var result="";if(layer[property]!=undefined)
result=layer[property];else if(layer.params!=null&&layer.params[property]!=undefined)
result=layer.params[property];else if(layer.params!=null&&layer.params[property.toUpperCase()]!=undefined)
result=layer.params[property.toUpperCase()];return result;},CLASS_NAME:"OpenLayers.Control.GetFeatureInfo"});OpenLayers.Control.GetFeatureInfoWFS=OpenLayers.Class(OpenLayers.Control,{type:OpenLayers.Control.TYPE_TOGGLE,map:null,selectFeatureControl:null,initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,[options]);var selectOptions={multiple:false,hover:false,onSelect:function(feature){onPopupClose();app.selectedFeature=feature;if(feature.attributes){var atributos=feature.attributes;var popup=null;var popup_info="";popup_info="<div class='callout_big'><div class='callout_desc'><div><h1>"+atributos.DESIGNACAO+"</h1></br></br><p><span>"+atributos.MORADA+"</span></br></br><span>"+atributos.LUGAR+"</span></p></div></div></div>";popup_info+="<div style='border: 0px none ; overflow: hidden; position: absolute; top: 7px; left: 196px; width: 20px; height: 15px;'><a href='javascript:onPopupClose()'><img src='http://js.sapo.pt/Assets/Maps/Images/bot_fechar.gif' title='Fechar'/></a></div>";app.popupInfo=new Municipia.Popup.Center("FeatureInfo",feature.geometry.getBounds().getCenterLonLat(),new OpenLayers.Size(214,180),popup_info,null,false);app.popupInfo.autoSize=false;app.popupInfo.closeOnMove=false;app.popupInfo.panMapIfOutOfView=true;app.popupInfo.overClass="featureMouseOver";app.popupInfo.setBackgroundColor('Transparent');feature.popup=app.popupInfo;feature.layer.map.addPopup(app.popupInfo);app.popupInfo.show();}},onUnselect:function(feature){feature.layer.map.removePopup(feature.popup);feature.popup.destroy();feature.popup=null;app.selectedFeature=null;app.popupInfo=null;}};var layers=[];for(var i=0;i<this.map.getNumLayers();i++){if(this.map.layers[i].CLASS_NAME=="OpenLayers.Layer.WFS"&&this.map.layers[i].featureClass==null){layers.push(this.map.layers[i]);}}
if(layers.length>0){this.selectFeatureControl=new OpenLayers.Control.SelectFeature(layers,selectOptions);this.map.addControl(this.selectFeatureControl);}},activate:function(){if(this.selectFeatureControl!=null){this.selectFeatureControl.activate();}
return OpenLayers.Control.prototype.activate.apply(this,arguments);},deactivate:function(){if(this.selectFeatureControl!=null){this.selectFeatureControl.deactivate();}
return OpenLayers.Control.prototype.deactivate.apply(this,arguments);},CLASS_NAME:"OpenLayers.Control.GetFeatureInfoWFS"});OpenLayers.Control.InfoAdicional=OpenLayers.Class(OpenLayers.Control,{element:null,text:"",initialize:function(options){OpenLayers.Control.prototype.initialize.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.element.innerHTML=this.text;return this.div;},CLASS_NAME:"OpenLayers.Control.InfoAdicional"});OpenLayers.Control.MousePosition.prototype.formatOutput=function(lonLat){var digits=parseInt(this.numDigits);if(this.displayProjection.proj.units!=null){if(this.displayProjection.proj.units=="m"){digits=parseInt(1);this.prefix="E (X) ";this.separator=" "+this.displayProjection.proj.units+"<br>N (Y) ";}else{this.prefix="E (Lon) ";this.separator=" "+this.displayProjection.proj.units+"<br>N (Lat) ";}
this.suffix=" "+this.displayProjection.proj.units;}
var newHtml=this.prefix+
lonLat.lon.toFixed(digits)+
this.separator+
lonLat.lat.toFixed(digits)+
this.suffix;return newHtml;};﻿
OpenLayers.Control.PanZoomBar.prototype._addZoomBar=function(centered){var imgLocation=OpenLayers.Util.getImagesLocation();var id="OpenLayers_Control_PanZoomBar_Slider"+this.map.id;var zoomsToEnd=this.map.getNumZoomLevels()-1-this.map.getZoom();var slider=OpenLayers.Util.createAlphaImageDiv(id,centered.add(-1,zoomsToEnd*this.zoomStopHeight),new OpenLayers.Size(20,9),imgLocation+"slider.png","absolute");slider.className="olControlPanZoomBarSlider";this.slider=slider;this.sliderEvents=new OpenLayers.Events(this,slider,null,true,{includeXY:true});this.sliderEvents.on({"mousedown":this.zoomBarDown,"mousemove":this.zoomBarDrag,"mouseup":this.zoomBarUp,"dblclick":this.doubleClick,"click":this.doubleClick});var sz=new OpenLayers.Size();sz.h=this.zoomStopHeight*this.map.getNumZoomLevels();sz.w=this.zoomStopWidth;var div=null;if(OpenLayers.Util.alphaHack()){var id="OpenLayers_Control_PanZoomBar"+this.map.id;div=OpenLayers.Util.createAlphaImageDiv(id,centered,new OpenLayers.Size(sz.w,this.zoomStopHeight),imgLocation+"zoombar.png","absolute",null,"crop");div.style.height=sz.h+"px";}else{div=OpenLayers.Util.createDiv('OpenLayers_Control_PanZoomBar_Zoombar'+this.map.id,centered,sz,imgLocation+"zoombar.png");}
div.className="olControlPanZoomBarra";this.zoombarDiv=div;this.divEvents=new OpenLayers.Events(this,div,null,true,{includeXY:true});this.divEvents.on({"mousedown":this.divClick,"mousemove":this.passEventToSlider,"dblclick":this.doubleClick,"click":this.doubleClick});this.div.appendChild(div);this.startTop=parseInt(div.style.top);this.div.appendChild(slider);this.map.events.register("zoomend",this,this.moveZoomBar);centered=centered.add(0,sz.h+2*this.zoomStopHeight-1);return centered;return centered;};OpenLayers.Control.PanZoomBar.prototype._addButton=function(id,img,xy,sz){var imgLocation=OpenLayers.Util.getImagesLocation()+img;var btn=OpenLayers.Util.createAlphaImageDiv("OpenLayers_Control_PanZoom_"+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;if(!this.slideRatio){var slideFactorPixels=this.slideFactor;var getSlideFactor=function(){return slideFactorPixels;};}else{var slideRatio=this.slideRatio;var getSlideFactor=function(dim){return this.map.getSize()[dim]*slideRatio;};}
btn.getSlideFactor=getSlideFactor;this.buttons.push(btn);return btn;};﻿
OpenLayers.Control.Scale.prototype.updateScale=function(){var scale=this.map.getScale();if(!scale){return;}
if(scale>=9500&&scale<=950000){scale=Math.round(scale/1000)+"K";}else if(scale>=950000){scale=Math.round(scale/1000000)+"M";}else{scale=Math.round(scale);}
this.element.innerText=OpenLayers.i18n("scale",{'scaleDenom':scale});};OpenLayers.Control.ScaleBar=OpenLayers.Class(OpenLayers.Control,{element:null,scale:1,displaySystem:'metric',minWidth:100,maxWidth:200,divisions:2,subdivisions:2,showMinorMeasures:false,abbreviateLabel:false,singleLine:false,align:'left',div:null,scaleText:"scale 1:",thousandsSeparator:"",measurementProperties:{english:{units:[OpenLayers.i18n('miles'),OpenLayers.i18n('feet'),OpenLayers.i18n('inches')],abbr:['mi','ft','in'],inches:[63360,12,1]},metric:{units:[OpenLayers.i18n('kilometers'),OpenLayers.i18n('meters'),OpenLayers.i18n('centimeters')],abbr:['km','m','cm'],inches:[39370.07874,39.370079,0.393701]}},limitedStyle:false,customStyles:null,defaultStyles:{Bar:{height:11,top:12,borderLeftWidth:0,borderRightWidth:0},BarAlt:{height:11,top:12,borderLeftWidth:0,borderRightWidth:0},MarkerMajor:{height:13,width:13,top:12,borderLeftWidth:0,borderRightWidth:0},MarkerMinor:{height:13,width:13,top:12,borderLeftWidth:0,borderRightWidth:0},NumbersBox:{height:13,width:40,top:24},LabelBox:{height:15,top:-2},LabelBoxSingleLine:{height:15,width:35,top:5,left:10}},appliedStyles:null,initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,[options]);if(!document.styleSheets){this.limitedStyle=true;}
if(this.limitedStyle){this.appliedStyles=OpenLayers.Util.extend({},this.defaultStyles);OpenLayers.Util.extend(this.appliedStyles,this.customStyles);}
this.element=document.createElement('div');this.element.style.position='relative';this.element.className=this.displayClass+'Wrapper';this.labelContainer=document.createElement('div');this.labelContainer.className=this.displayClass+'Units';this.labelContainer.style.position='absolute';this.graphicsContainer=document.createElement('div');this.graphicsContainer.style.position='absolute';this.graphicsContainer.className=this.displayClass+'Graphics';this.numbersContainer=document.createElement('div');this.numbersContainer.style.position='absolute';this.numbersContainer.className=this.displayClass+'Numbers';this.element.appendChild(this.graphicsContainer);this.element.appendChild(this.labelContainer);this.element.appendChild(this.numbersContainer);},destroy:function(){this.map.events.unregister('moveend',this,this.onMoveend);this.div.innerHTML="";OpenLayers.Control.prototype.destroy.apply(this);},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);this.dxMarkerMajor=(this.styleValue('MarkerMajor','borderLeftWidth')+
this.styleValue('MarkerMajor','width')+
this.styleValue('MarkerMajor','borderRightWidth'))/2;this.dxMarkerMinor=(this.styleValue('MarkerMinor','borderLeftWidth')+
this.styleValue('MarkerMinor','width')+
this.styleValue('MarkerMinor','borderRightWidth'))/2;this.dxBar=(this.styleValue('Bar','borderLeftWidth')+
this.styleValue('Bar','borderRightWidth'))/2;this.dxBarAlt=(this.styleValue('BarAlt','borderLeftWidth')+
this.styleValue('BarAlt','borderRightWidth'))/2;this.dxNumbersBox=this.styleValue('NumbersBox','width')/2;var classNames=['Bar','BarAlt','MarkerMajor','MarkerMinor'];if(this.singleLine){classNames.push('LabelBoxSingleLine');}else{classNames.push('NumbersBox','LabelBox');}
var vertDisp=0;for(var classIndex=0;classIndex<classNames.length;++classIndex){var cls=classNames[classIndex];vertDisp=Math.max(vertDisp,this.styleValue(cls,'top')+this.styleValue(cls,'height'));}
this.element.style.height=vertDisp+'px';this.xOffsetSingleLine=this.styleValue('LabelBoxSingleLine','width')+
this.styleValue('LabelBoxSingleLine','left');this.div.appendChild(this.element);this.map.events.register('moveend',this,this.onMoveend);this.update();return this.div;},onMoveend:function(){this.update();},update:function(scale){if(this.map.baseLayer==null||!this.map.getScale()){return;}
this.scale=(scale!=undefined)?scale:this.map.getScale();this.element.title=this.scaleText+OpenLayers.Number.format(this.scale);this.element.style.width=this.maxWidth+'px';var comp=this.getComp();this.setSubProps(comp);this.labelContainer.innerHTML="";this.graphicsContainer.innerHTML="";this.numbersContainer.innerHTML="";var numDiv=this.divisions*this.subdivisions;var alignmentOffset={left:0+(this.singleLine?0:this.dxNumbersBox),center:(this.maxWidth/2)-
(numDiv*this.subProps.pixels/2)-
(this.singleLine?this.xOffsetSingleLine/2:0),right:this.maxWidth-
(numDiv*this.subProps.pixels)-
(this.singleLine?this.xOffsetSingleLine:this.dxNumbersBox)}
var xPos,measure,divNum,cls,left;for(var di=0;di<this.divisions;++di){xPos=di*this.subdivisions*this.subProps.pixels+
alignmentOffset[this.align];this.graphicsContainer.appendChild(this.createElement("MarkerMajor"," ",xPos-this.dxMarkerMajor));if(!this.singleLine){measure=(di==0)?0:OpenLayers.Number.format((di*this.subdivisions)*this.subProps.length,this.subProps.dec,this.thousandsSeparator);this.numbersContainer.appendChild(this.createElement("NumbersBox",measure,xPos-this.dxNumbersBox));}
for(var si=0;si<this.subdivisions;++si){if((si%2)==0){cls="Bar";left=xPos-this.dxBar;}else{cls="BarAlt";left=xPos-this.dxBarAlt;}
this.graphicsContainer.appendChild(this.createElement(cls," ",left,this.subProps.pixels));if(si<this.subdivisions-1){divNum=(di*this.subdivisions)+si+1;xPos=divNum*this.subProps.pixels+
alignmentOffset[this.align];this.graphicsContainer.appendChild(this.createElement("MarkerMinor"," ",xPos-this.dxMarkerMinor));if(this.showMinorMeasures&&!this.singleLine){measure=divNum*this.subProps.length;this.numbersContainer.appendChild(this.createElement("NumbersBox",measure,xPos-this.dxNumbersBox));}}}}
xPos=numDiv*this.subProps.pixels;xPos+=alignmentOffset[this.align];this.graphicsContainer.appendChild(this.createElement("MarkerMajor"," ",xPos-this.dxMarkerMajor));measure=OpenLayers.Number.format(numDiv*this.subProps.length,this.subProps.dec,this.thousandsSeparator);if(!this.singleLine){this.numbersContainer.appendChild(this.createElement("NumbersBox",measure,xPos-this.dxNumbersBox));}
var labelBox=document.createElement('div');labelBox.style.position='absolute';var labelText;if(this.singleLine){labelText=measure;labelBox.className=this.displayClass+'LabelBoxSingleLine';labelBox.style.left=Math.round(xPos+this.styleValue('LabelBoxSingleLine','left'))+'px';}else{labelText='';labelBox.className=this.displayClass+'LabelBox';labelBox.style.textAlign='center';labelBox.style.width=Math.round(numDiv*this.subProps.pixels)+'px'
labelBox.style.left=Math.round(alignmentOffset[this.align])+'px';labelBox.style.overflow='hidden';}
if(this.abbreviateLabel){labelText+=' '+this.subProps.abbr;}else{labelText+=' '+this.subProps.units;}
labelBox.appendChild(document.createTextNode(labelText));this.labelContainer.appendChild(labelBox);},createElement:function(cls,text,left,width){var element=document.createElement("div");element.className=this.displayClass+cls;OpenLayers.Util.extend(element.style,{position:"absolute",textAlign:"center",overflow:"hidden",left:Math.round(left)+"px"});element.appendChild(document.createTextNode(text));if(width){element.style.width=Math.round(width)+"px";}
return element;},getComp:function(){var system=this.measurementProperties[this.displaySystem];var numUnits=system.units.length;var comp=new Array(numUnits);var numDiv=this.divisions*this.subdivisions;for(var unitIndex=0;unitIndex<numUnits;++unitIndex){comp[unitIndex]={};var ppdu=OpenLayers.DOTS_PER_INCH*system.inches[unitIndex]/this.scale;var minSDDisplayLength=((this.minWidth-this.dxNumbersBox)/ppdu)/numDiv;var maxSDDisplayLength=((this.maxWidth-this.dxNumbersBox)/ppdu)/numDiv;for(var vi=0;vi<numDiv;++vi){var minNumber=minSDDisplayLength*(vi+1);var maxNumber=maxSDDisplayLength*(vi+1);var num=this.getHandsomeNumber(minNumber,maxNumber);var compNum={value:(num.value/(vi+1)),score:0,tie:0,dec:0,displayed:0};for(var vi2=0;vi2<numDiv;++vi2){var position=num.value*(vi2+1)/(vi+1);var num2=this.getHandsomeNumber(position,position);var major=((vi2+1)%this.subdivisions==0);var last=((vi2+1)==numDiv);if((this.singleLine&&last)||(!this.singleLine&&(major||this.showMinorMeasures))){compNum.score+=num2.score;compNum.tie+=num2.tie;compNum.dec=Math.max(compNum.dec,num2.dec);compNum.displayed+=1;}else{compNum.score+=num2.score/this.subdivisions;compNum.tie+=num2.tie/this.subdivisions;}}
compNum.score*=(unitIndex+1)*compNum.tie/compNum.displayed;comp[unitIndex][vi]=compNum;}}
return comp;},setSubProps:function(comp){var system=this.measurementProperties[this.displaySystem];var score=Number.POSITIVE_INFINITY;var tie=Number.POSITIVE_INFINITY;for(var unitIndex=0;unitIndex<comp.length;++unitIndex){var ppdu=OpenLayers.DOTS_PER_INCH*system.inches[unitIndex]/this.scale;for(var vi in comp[unitIndex]){var compNum=comp[unitIndex][vi];if((compNum.score<score)||((compNum.score==score)&&(compNum.tie<tie))){this.subProps={length:compNum.value,pixels:ppdu*compNum.value,units:system.units[unitIndex],abbr:system.abbr[unitIndex],dec:compNum.dec};score=compNum.score;tie=compNum.tie;}}}},styleValue:function(selector,key){var value=0;if(this.limitedStyle){value=this.appliedStyles[selector][key];}else{selector="."+this.displayClass+selector;rules:for(var i=document.styleSheets.length-1;i>=0;--i){var sheet=document.styleSheets[i];if(!sheet.disabled){var allRules;try{if(typeof(sheet.cssRules)=='undefined'){if(typeof(sheet.rules)=='undefined'){continue;}else{allRules=sheet.rules;}}else{allRules=sheet.cssRules;}}catch(err){continue;}
for(var ruleIndex=0;ruleIndex<allRules.length;++ruleIndex){var rule=allRules[ruleIndex];if(rule.selectorText&&(rule.selectorText.toLowerCase()==selector.toLowerCase())){if(rule.style[key]!=''){value=parseInt(rule.style[key]);break rules;}}}}}}
return value?value:0;},getHandsomeNumber:function(small,big,sigFigs){sigFigs=(sigFigs==null)?10:sigFigs;var num={value:small,score:Number.POSITIVE_INFINITY,tie:Number.POSITIVE_INFINITY,dec:3};var cmult,max,dec,tmult,multiplier,score,tie;for(var hexp=0;hexp<3;++hexp){cmult=Math.pow(2,(-1*hexp));max=Math.floor(Math.log(big/cmult)/Math.LN10);for(var texp=max;texp>(max-sigFigs+1);--texp){dec=Math.max(hexp-texp,0);tmult=cmult*Math.pow(10,texp);if((tmult*Math.floor(big/tmult))>=small){if(small%tmult==0){multiplier=small/tmult;}else{multiplier=Math.floor(small/tmult)+1;}
score=multiplier+(2*hexp);tie=(texp<0)?(Math.abs(texp)+1):texp;if((score<num.score)||((score==num.score)&&(tie<num.tie))){num.value=parseFloat((tmult*multiplier).toFixed(dec));num.score=score;num.tie=tie;num.dec=dec;}}}}
return num;},CLASS_NAME:"OpenLayers.Control.ScaleBar"});﻿
OpenLayers.Control.ZoomBox.prototype.activate=function(){return OpenLayers.Control.prototype.activate.apply(this,arguments);};OpenLayers.Control.ZoomBox.prototype.deactivate=function(){return OpenLayers.Control.prototype.deactivate.apply(this,arguments);};Municipia.Event={observers:false,KEY_BACKSPACE:8,KEY_TAB:9,KEY_RETURN:13,KEY_ESC:27,KEY_LEFT:37,KEY_UP:38,KEY_RIGHT:39,KEY_DOWN:40,KEY_DELETE:46,element:function(event){return event.target||event.srcElement;},isLeftClick:function(event){return(((event.which)&&(event.which==1))||((event.button)&&(event.button==1)));},isRightClick:function(event){return(((event.which)&&(event.which==3))||((event.button)&&(event.button==2)));},stop:function(event,allowDefault){if(!allowDefault){if(event.preventDefault){event.preventDefault();}else{event.returnValue=false;}}
if(event.stopPropagation){event.stopPropagation();}else{event.cancelBubble=true;}},findElement:function(event,tagName){var element=Municipia.Event.element(event);while(element.parentNode&&(!element.tagName||(element.tagName.toUpperCase()!=tagName.toUpperCase()))){element=element.parentNode;}
return element;},observe:function(elementParam,name,observer,useCapture){var element=Municipia.Util.getElement(elementParam);useCapture=useCapture||false;if(name=='keypress'&&(navigator.appVersion.match(/Konqueror|Safari|KHTML/)||element.attachEvent)){name='keydown';}
if(!this.observers){this.observers={};}
if(!element._eventCacheID){var idPrefix="eventCacheID_";if(element.id){idPrefix=element.id+"_"+idPrefix;}
element._eventCacheID=Municipia.Util.createUniqueID(idPrefix);}
var cacheID=element._eventCacheID;if(!this.observers[cacheID]){this.observers[cacheID]=[];}
this.observers[cacheID].push({'element':element,'name':name,'observer':observer,'useCapture':useCapture});if(element.addEventListener){element.addEventListener(name,observer,useCapture);}else if(element.attachEvent){element.attachEvent('on'+name,observer);}},stopObservingElement:function(elementParam){var element=Municipia.Util.getElement(elementParam);var cacheID=element._eventCacheID;this._removeElementObservers(Municipia.Event.observers[cacheID]);},_removeElementObservers:function(elementObservers){if(elementObservers){for(var i=elementObservers.length-1;i>=0;i--){var entry=elementObservers[i];var args=new Array(entry.element,entry.name,entry.observer,entry.useCapture);var removed=Municipia.Event.stopObserving.apply(this,args);}}},stopObserving:function(elementParam,name,observer,useCapture){useCapture=useCapture||false;var element=Municipia.Util.getElement(elementParam);var cacheID=element._eventCacheID;if(name=='keypress'){if(navigator.appVersion.match(/Konqueror|Safari|KHTML/)||element.detachEvent){name='keydown';}}
var foundEntry=false;var elementObservers=Municipia.Event.observers[cacheID];if(elementObservers){var i=0;while(!foundEntry&&i<elementObservers.length){var cacheEntry=elementObservers[i];if((cacheEntry.name==name)&&(cacheEntry.observer==observer)&&(cacheEntry.useCapture==useCapture)){elementObservers.splice(i,1);if(elementObservers.length==0){delete Municipia.Event.observers[cacheID];}
foundEntry=true;break;}
i++;}}
if(foundEntry){if(element.removeEventListener){element.removeEventListener(name,observer,useCapture);}else if(element&&element.detachEvent){element.detachEvent('on'+name,observer);}}
return foundEntry;},unloadCache:function(){if(Municipia.Event&&Municipia.Event.observers){for(var cacheID in Municipia.Event.observers){var elementObservers=Municipia.Event.observers[cacheID];Municipia.Event._removeElementObservers.apply(this,[elementObservers]);}
Municipia.Event.observers=false;}},CLASS_NAME:"Municipia.Event"};Municipia.Event.observe(window,'unload',Municipia.Event.unloadCache,false);if(window.Event){Municipia.Util.applyDefaults(window.Event,Municipia.Event);}else{var Event=Municipia.Event;}
Municipia.Events=Municipia.Class({BROWSER_EVENTS:["mouseover","mouseout","mousedown","mouseup","mousemove","click","dblclick","rightclick","dblrightclick","resize","focus","blur"],listeners:null,object:null,element:null,eventTypes:null,eventHandler:null,fallThrough:null,includeXY:false,initialize:function(object,element,eventTypes,fallThrough,options){Municipia.Util.extend(this,options);this.object=object;this.fallThrough=fallThrough;this.listeners={};this.eventHandler=Municipia.Function.bindAsEventListener(this.handleBrowserEvent,this);this.eventTypes=[];if(eventTypes!=null){for(var i=0,len=eventTypes.length;i<len;i++){this.addEventType(eventTypes[i]);}}
if(element!=null){this.attachToElement(element);}},destroy:function(){if(this.element){Municipia.Event.stopObservingElement(this.element);}
this.element=null;this.listeners=null;this.object=null;this.eventTypes=null;this.fallThrough=null;this.eventHandler=null;},addEventType:function(eventName){if(!this.listeners[eventName]){this.eventTypes.push(eventName);this.listeners[eventName]=[];}},attachToElement:function(element){if(this.element){Municipia.Event.stopObservingElement(this.element);}
this.element=element;for(var i=0,len=this.BROWSER_EVENTS.length;i<len;i++){var eventType=this.BROWSER_EVENTS[i];this.addEventType(eventType);Municipia.Event.observe(element,eventType,this.eventHandler);}
Municipia.Event.observe(element,"dragstart",Municipia.Event.stop);},on:function(object){for(var type in object){if(type!="scope"){this.register(type,object.scope,object[type]);}}},register:function(type,obj,func){if((func!=null)&&(Municipia.Util.indexOf(this.eventTypes,type)!=-1)){if(obj==null){obj=this.object;}
var listeners=this.listeners[type];listeners.push({obj:obj,func:func});}},registerPriority:function(type,obj,func){if(func!=null){if(obj==null){obj=this.object;}
var listeners=this.listeners[type];if(listeners!=null){listeners.unshift({obj:obj,func:func});}}},un:function(object){for(var type in object){if(type!="scope"){this.unregister(type,object.scope,object[type]);}}},unregister:function(type,obj,func){if(obj==null){obj=this.object;}
var listeners=this.listeners[type];if(listeners!=null){for(var i=0,len=listeners.length;i<len;i++){if(listeners[i].obj==obj&&listeners[i].func==func){listeners.splice(i,1);break;}}}},remove:function(type){if(this.listeners[type]!=null){this.listeners[type]=[];}},triggerEvent:function(type,evt){var listeners=this.listeners[type];if(!listeners||listeners.length==0){return;}
if(evt==null){evt={};}
evt.object=this.object;evt.element=this.element;if(!evt.type){evt.type=type;}
var listeners=listeners.slice(),continueChain;for(var i=0,len=listeners.length;i<len;i++){var callback=listeners[i];continueChain=callback.func.apply(callback.obj,[evt]);if((continueChain!=undefined)&&(continueChain==false)){break;}}
if(!this.fallThrough){Municipia.Event.stop(evt,true);}
return continueChain;},handleBrowserEvent:function(evt){if(this.includeXY){evt.xy=this.getMousePosition(evt);}
this.triggerEvent(evt.type,evt);},clearMouseCache:function(){this.element.scrolls=null;this.element.lefttop=null;this.element.offsets=null;},getMousePosition:function(evt){if(!this.includeXY){this.clearMouseCache();}else if(!this.element.hasScrollEvent){Municipia.Event.observe(window,'scroll',Municipia.Function.bind(this.clearMouseCache,this));this.element.hasScrollEvent=true;}
if(!this.element.scrolls){this.element.scrolls=[(document.documentElement.scrollLeft||document.body.scrollLeft),(document.documentElement.scrollTop||document.body.scrollTop)];}
if(!this.element.lefttop){this.element.lefttop=[(document.documentElement.clientLeft||0),(document.documentElement.clientTop||0)];}
if(!this.element.offsets){this.element.offsets=Municipia.Util.pagePosition(this.element);this.element.offsets[0]+=this.element.scrolls[0];this.element.offsets[1]+=this.element.scrolls[1];}
return new Municipia.Pixel((evt.clientX+this.element.scrolls[0])-this.element.offsets[0]
-this.element.lefttop[0],(evt.clientY+this.element.scrolls[1])-this.element.offsets[1]
-this.element.lefttop[1]);},CLASS_NAME:"Municipia.Events"});﻿
OpenLayers.Handler.cursorClasses=null;OpenLayers.Handler.previousFunctionName=null;OpenLayers.Handler.prototype.initialize=function(control,callbacks,options){this.cursorClasses=null;this.previousFunctionName=null;OpenLayers.Util.extend(this,options);this.control=control;this.callbacks=callbacks;if(control.map){this.setMap(control.map);}
OpenLayers.Util.extend(this,options);this.id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_");};OpenLayers.Handler.prototype.activate=function(){if(this.active){return false;}
if(this.previousFunctionName){OpenLayers.Element.removeClass(this.map.div,this.cursorClasses[this.previousFunctionName]);}
var events=OpenLayers.Events.prototype.BROWSER_EVENTS;for(var i=0,len=events.length;i<len;i++){if(this[events[i]]){this.register(events[i],this[events[i]]);}}
this.active=true;return true;};OpenLayers.Handler.prototype.deactivate=function(){if(!this.active){return false;}
if(this.previousFunctionName){OpenLayers.Element.removeClass(this.map.div,this.cursorClasses[this.previousFunctionName]);}
var events=OpenLayers.Events.prototype.BROWSER_EVENTS;for(var i=0,len=events.length;i<len;i++){if(this[events[i]]){this.unregister(events[i],this[events[i]]);}}
this.active=false;return true;};﻿
OpenLayers.Handler.Box.prototype.setCursor=function(functionName){if(this.previousFunctionName){OpenLayers.Element.removeClass(this.map.div,this.cursorClasses[this.previousFunctionName]);}
if(this.cursorClasses&&this.cursorClasses[functionName]){OpenLayers.Element.addClass(this.map.div,this.cursorClasses[functionName]);this.previousFunctionName=functionName;}};﻿
OpenLayers.Handler.Drag.prototype.mousedown=function(evt){var propagate=true;this.dragging=false;if(this.checkModifiers(evt)&&OpenLayers.Event.isLeftClick(evt)){this.started=true;this.start=evt.xy;this.last=evt.xy;this.setCursor('mousedown');this.down(evt);this.callback("down",[evt.xy]);OpenLayers.Event.stop(evt);if(!this.oldOnselectstart){this.oldOnselectstart=(document.onselectstart)?document.onselectstart:function(){return true;};document.onselectstart=function(){return false;};}
propagate=!this.stopDown;}else{this.started=false;this.start=null;this.last=null;}
return propagate;};OpenLayers.Handler.Drag.prototype.mouseup=function(evt){if(this.started){var dragged=(this.start!=this.last);this.started=false;this.dragging=false;this.setCursor('mouseup');this.up(evt);this.callback("up",[evt.xy]);if(dragged){this.callback("done",[evt.xy]);}
document.onselectstart=this.oldOnselectstart;}
return true;};OpenLayers.Handler.Drag.prototype.mouseout=function(evt){if(this.started&&OpenLayers.Util.mouseLeft(evt,this.map.div)){var dragged=(this.start!=this.last);this.started=false;this.dragging=false;this.setCursor('mouseout');this.out(evt);this.callback("out",[]);if(dragged){this.callback("done",[evt.xy]);}
if(document.onselectstart){document.onselectstart=this.oldOnselectstart;}}
return true;};OpenLayers.Handler.Drag.prototype.setCursor=function(functionName){if(this.previousFunctionName){OpenLayers.Element.removeClass(this.map.div,this.cursorClasses[this.previousFunctionName]);}
if(this.cursorClasses&&this.cursorClasses[functionName]){OpenLayers.Element.addClass(this.map.div,this.cursorClasses[functionName]);this.previousFunctionName=functionName;}};Municipia.Icon=Municipia.Class({url:null,size:null,offset:null,calculateOffset:null,imageDiv:null,px:null,initialize:function(url,size,offset,calculateOffset){this.url=url;this.size=(size)?size:new Municipia.Size(20,20);this.offset=offset?offset:new Municipia.Pixel(-(this.size.w/2),-(this.size.h/2));this.calculateOffset=calculateOffset;var id=Municipia.Util.createUniqueID("OL_Icon_");this.imageDiv=Municipia.Util.createAlphaImageDiv(id);},destroy:function(){Municipia.Event.stopObservingElement(this.imageDiv.firstChild);this.imageDiv.innerHTML="";this.imageDiv=null;},clone:function(){return new Municipia.Icon(this.url,this.size,this.offset,this.calculateOffset);},setSize:function(size){if(size!=null){this.size=size;}
this.draw();},setUrl:function(url){if(url!=null){this.url=url;}
this.draw();},draw:function(px){Municipia.Util.modifyAlphaImageDiv(this.imageDiv,null,null,this.size,this.url,"absolute");this.moveTo(px);return this.imageDiv;},setOpacity:function(opacity){Municipia.Util.modifyAlphaImageDiv(this.imageDiv,null,null,null,null,null,null,null,opacity);},moveTo:function(px){if(px!=null){this.px=px;}
if(this.imageDiv!=null){if(this.px==null){this.display(false);}else{if(this.calculateOffset){this.offset=this.calculateOffset(this.size);}
var offsetPx=this.px.offset(this.offset);Municipia.Util.modifyAlphaImageDiv(this.imageDiv,null,offsetPx);}}},display:function(display){this.imageDiv.style.display=(display)?"":"none";},isDrawn:function(){var isDrawn=(this.imageDiv&&this.imageDiv.parentNode&&(this.imageDiv.parentNode.nodeType!=11));return isDrawn;},CLASS_NAME:"Municipia.Icon"});OpenLayers.Lang["pt-BR"]={'unhandledRequest':"A requisição retornou um erro não tratado: ${statusText}",'permalink':"Link para essa página",'overlays':"Camadas de Sobreposição",'baseLayer':"Camada Base",'sameProjection':"O mapa de referência só funciona quando ele está na mesma projeção do mapa principal",'readNotImplemented':"Leitura não implementada.",'writeNotImplemented':"Escrita não implementada.",'noFID':"Não é possível atualizar uma feição que não tenha um FID.",'errorLoadingGML':"Erro ao carregar o arquivo GML ${url}",'browserNotSupported':"Seu navegador não suporta renderização de vetores. Os renderizadores suportados atualmente são:\n${renderers}",'componentShouldBe':"addFeatures: o componente deve ser do tipo ${geomType}",'getFeatureError':"getFeatureFromEvent foi executado mas nenhum renderizador foi encontrado. "+"Isso pode indicar que você destruiu uma camana, mas não o handler associado a ela.",'minZoomLevelError':"A propriedade minZoomLevel é de uso restrito das camadas "+"descendentes de FixedZoomLevels. A verificação dessa propriedade "+"pelas camadas wfs é um resíduo do passado. Não podemos, entretanto "+"não é possível removê-la sem possívelmente quebrar o funcionamento "+"de aplicações OL que possuem depência com ela. Portanto estamos "+"tornando seu uso obsoleto -- a verificação desse atributo será "+"removida na versão 3.0. Ao invés, use as opções de resolução "+"min/max como descrito em: "+"http://trac.openlayers.org/wiki/SettingZoomLevels",'commitSuccess':"Transação WFS : SUCESSO ${response}",'commitFailed':"Transação WFS : ERRO ${response}",'googleWarning':"Não foi possível carregar a camada Google corretamente.<br><br>"+"Para se livrar dessa mensagem, selecione uma nova Camada Base, "+"na ferramenta de alternação de camadas localização do canto "+"superior direito.<br><br>"+"Muito provavelmente, isso foi causado porque o script da "+"biblioteca do Google Maps não foi incluído, ou porque ele não "+"contém a chave correta da API para o seu site.<br><br>"+"Desenvolvedores: Para obter ajuda em solucionar esse problema "+"<a href='http://trac.openlayers.org/wiki/Google' "+"target='_blank'>cliquem aqui</a>",'getLayerWarning':"Não foi possível carregar a camada ${layerType} corretamente.<br><br>"+"Para se livrar dessa mensagem, selecione uma nova Camada Base, "+"na ferramenta de alternação de camadas localização do canto "+"superior direito.<br><br>"+"Muito provavelmente, isso foi causado porque o script da "+"biblioteca ${layerLib} não foi incluído corretamente.<br><br>"+"Desenvolvedores: Para obter ajuda em solucionar esse problema "+"<a href='http://trac.openlayers.org/wiki/${layerLib}' "+"target='_blank'>cliquem aqui</a>",'scale':"Escala = 1 : ${scaleDenom}",'layerAlreadyAdded':"Você tentou adicionar a camada: ${layerName} ao mapa, mas ela já foi adicionada",'reprojectDeprecated':"Você está usando a opção 'reproject' na camada ${layerName}. "+"Essa opção está obsoleta: seu uso foi projetado para suportar "+"a visualização de dados sobre bases de mapas comerciais, "+"entretanto essa funcionalidade deve agora ser alcançada usando "+"o suporte à projeção Mercator. Mais informação está disponível em: "+"http://trac.openlayers.org/wiki/SphericalMercator.",'methodDeprecated':"Esse método está obsoleto e será removido na versão 3.0. "+"Ao invés, por favor use ${newMethod}.",'boundsAddError':"Você deve informar ambos os valores x e y para a função add.",'lonlatAddError':"Você deve informar ambos os valores lon e lat para a função add.",'pixelAddError':"Você deve informar ambos os valores x e y para a função add.",'unsupportedGeometryType':"Tipo geométrico não suportado: ${geomType}.",'pagePositionFailed':"OpenLayers.Util.pagePosition falhou: o elemento de id ${elemId} deve estar fora do lugar.",'end':''};OpenLayers.Lang["pt"]={'unhandledRequest':"A requisição retornou um erro não tratado: ${statusText}",'permalink':"Link para essa página",'overlays':"Pontos de Interesse",'baseLayer':"Cartografia Base",'sameProjection':"O mapa de referência só funciona quando ele está na mesma projeção do mapa principal",'readNotImplemented':"Leitura não implementada.",'writeNotImplemented':"Escrita não implementada.",'noFID':"Não é possível atualizar uma feição que não tenha um FID.",'errorLoadingGML':"Erro ao carregar o arquivo GML ${url}",'browserNotSupported':"Seu navegador não suporta renderização de vetores. Os renderizadores suportados atualmente são:\n${renderers}",'componentShouldBe':"addFeatures: o componente deve ser do tipo ${geomType}",'getFeatureError':"getFeatureFromEvent foi executado mas nenhum renderizador foi encontrado. "+"Isso pode indicar que você destruiu uma camana, mas não o handler associado a ela.",'minZoomLevelError':"A propriedade minZoomLevel é de uso restrito das camadas "+"descendentes de FixedZoomLevels. A verificação dessa propriedade "+"pelas camadas wfs é um resíduo do passado. Não podemos, entretanto "+"não é possível removê-la sem possívelmente quebrar o funcionamento "+"de aplicações OL que possuem depência com ela. Portanto estamos "+"tornando seu uso obsoleto -- a verificação desse atributo será "+"removida na versão 3.0. Ao invés, use as opções de resolução "+"min/max como descrito em: "+"http://trac.openlayers.org/wiki/SettingZoomLevels",'commitSuccess':"Transação WFS : SUCESSO ${response}",'commitFailed':"Transação WFS : ERRO ${response}",'googleWarning':"Não foi possível carregar a camada Google corretamente.<br><br>"+"Para se livrar dessa mensagem, selecione uma nova Camada Base, "+"na ferramenta de alternação de camadas localização do canto "+"superior direito.<br><br>"+"Muito provavelmente, isso foi causado porque o script da "+"biblioteca do Google Maps não foi incluído, ou porque ele não "+"contém a chave correta da API para o seu site.<br><br>"+"Desenvolvedores: Para obter ajuda em solucionar esse problema "+"<a href='http://trac.openlayers.org/wiki/Google' "+"target='_blank'>cliquem aqui</a>",'getLayerWarning':"Não foi possível carregar a camada ${layerType} corretamente.<br><br>"+"Para se livrar dessa mensagem, selecione uma nova Camada Base, "+"na ferramenta de alternação de camadas localização do canto "+"superior direito.<br><br>"+"Muito provavelmente, isso foi causado porque o script da "+"biblioteca ${layerLib} não foi incluído corretamente.<br><br>"+"Desenvolvedores: Para obter ajuda em solucionar esse problema "+"<a href='http://trac.openlayers.org/wiki/${layerLib}' "+"target='_blank'>cliquem aqui</a>",'scale':"Escala = 1 : ${scaleDenom}",'Scale 1:':"Escala 1:",'Scales':"Escalas",'layerAlreadyAdded':"Você tentou adicionar a camada: ${layerName} ao mapa, mas ela já foi adicionada",'reprojectDeprecated':"Você está usando a opção 'reproject' na camada ${layerName}. "+"Essa opção está obsoleta: seu uso foi projetado para suportar "+"a visualização de dados sobre bases de mapas comerciais, "+"entretanto essa funcionalidade deve agora ser alcançada usando "+"o suporte à projeção Mercator. Mais informação está disponível em: "+"http://trac.openlayers.org/wiki/SphericalMercator.",'methodDeprecated':"Esse método está obsoleto e será removido na versão 3.0. "+"Ao invés, por favor use ${newMethod}.",'boundsAddError':"Você deve informar ambos os valores x e y para a função add.",'lonlatAddError':"Você deve informar ambos os valores lon e lat para a função add.",'pixelAddError':"Você deve informar ambos os valores x e y para a função add.",'unsupportedGeometryType':"Tipo geométrico não suportado: ${geomType}.",'pagePositionFailed':"OpenLayers.Util.pagePosition falhou: o elemento de id ${elemId} deve estar fora do lugar.",'Text right click':"C.M.V.P.A. \nCâmara Municipal de Vila Pouca de Aguiar",'Text copyright':"© C.M.V.P.A. Todos os direitos reservados. Desenvolvido por Municipia, S.A.",'Search requires a minimum of 2 characters.':"Pesquisa com o minimo de 2 caracteres",'Search':"Pesquisa",'Search: ':"Pesquisar: ",'Help':"Ajuda",'OverviewMap':"Janela de Enquadramento",'TitleOverviewMap':"Enquadramento",'Legend':"Temas",'Theme no found':"Não existe nenhum tema pesquisável seleccionado.\t Consulte na ajuda quais os temas pesquisáveis.",'URL not found.':"Não está definido o URL para a pesquisa.",'Loading...':"A Carregar...",'nif.error':"Número de contribuinte inválido!",'View':"Configuração",'Modules':"Módulos",'Information':"Identificar ponto nos temas pesquisáveis",'Zoom In':"Aproximar Mapa",'Zoom Out':"Afastar Mapa",'Pan Map':"Arrastar Mapa",'Previous View':"Vista Anterior",'Next View':"Vista Posterior",'Initial Map':"Mapa Inicial",'Print':"Imprimir",'Tools':"Navegação",'Title optionsMenu':"Seleccionar unidades de medida.",'Choose Units':"Sistema de Coordenadas",'Choose a Theme':"Layout da Aplicação",'Display Units of Map':"Sistema Coord.",'Metric':"Cartesianas (M, P)",'Degrees':"Geográficas (Lat, Long)",'Center':"Centrar Mapa",'Distance Measurement':"Medição da Distância (double-click para terminar)",'Area Measurement':"Medição da Área (double-click para terminar)",'Measure':"Valor da Medição",'Draw Polygon':"Desenhar Polígono Auxiliar (double-click para terminar)",'Erase Polygon':"Apagar Polígono",'Clean Map':"Limpar Mapa",'miles':"Milhas",'feet':"Pés",'inches':"Polegadas",'kilometers':"Kilómetros",'meters':"Metros",'centimeters':"Centímetros",'info.No topics to display':"Nenhum registo encontrado.",'info.error':"Não foi possível mostrar o resultado da pesquisa.",'No topics to display':"Nenhum registo encontrado.",'{0} - {1} of {2}':"{0} - {1} de {2}",'Page':"Página",'of {0}':"de {0}",'First Page':"Primeira página",'Last page':"Última página",'Next page':"Próxima página",'Prev page':"Página anterior",'Refresh':"Actualizar",'Places':"Lugares",'Streets':"Ruas",'Addresses':"Ruas e Moradas",'Businesses':"Actividade Económica",'Points of Interest':"Pontos de Interesse",'Equipments':"Equipamentos e Empresas",'emptyFieldCity':" Localidades...",'Title Detail Window':"Informação",'Zoom to Element':'Click para efectuar Zoom.','CALHETA_CARTOGRAFIA':"Cartografia",'CALHETA_CONDICIONANTES':"Condicionantes",'CALHETA_ORDENAMENTO':"Ordenamento",'CALHETA_PLANEAMENTO':"Planeamento",'CAMARA_LOBOS_CARTOGRAFIA':"Cartografia",'CAMARA_LOBOS_CONDICIONANTES':"Condicionantes",'CAMARA_LOBOS_ORDENAMENTO':"Ordenamento",'CAMARA_LOBOS_PLANEAMENTO':"Planeamento",'FUNCHAL_CARTOGRAFIA':"Cartografia",'FUNCHAL_CONDICIONANTES':"Condicionantes",'FUNCHAL_ORDENAMENTO':"Ordenamento",'FUNCHAL_PLANEAMENTO':"Planeamento",'PONTA_SOL_CARTOGRAFIA':"Cartografia",'PONTA_SOL_CONDICIONANTES':"Condicionantes",'PONTA_SOL_ORDENAMENTO':"Ordenamento",'PONTA_SOL_PLANEAMENTO':"Planeamento",'PORTO_MONIZ_CARTOGRAFIA':"Cartografia",'PORTO_MONIZ_CONDICIONANTES':"Condicionantes",'PORTO_MONIZ_ORDENAMENTO':"Ordenamento",'PORTO_MONIZ_PLANEAMENTO':"Planeamento",'RIBEIRA_BRAVA_CARTOGRAFIA':"Cartografia",'RIBEIRA_BRAVA_CONDICIONANTES':"Condicionantes",'RIBEIRA_BRAVA_ORDENAMENTO':"Ordenamento",'RIBEIRA_BRAVA_PLANEAMENTO':"Planeamento",'SANTANA_CARTOGRAFIA':"Cartografia",'SANTANA_CONDICIONANTES':"Condicionantes",'SANTANA_ORDENAMENTO':"Ordenamento",'SANTANA_PLANEAMENTO':"Planeamento",'SANTA_CRUZ_CARTOGRAFIA':"Cartografia",'SANTA_CRUZ_CONDICIONANTES':"Condicionantes",'SANTA_CRUZ_ORDENAMENTO':"Ordenamento",'SANTA_CRUZ_PLANEAMENTO':"Planeamento",'SAO_VICENTE_CARTOGRAFIA':"Cartografia",'SAO_VICENTE_CONDICIONANTES':"Condicionantes",'SAO_VICENTE_ORDENAMENTO':"Ordenamento",'SAO_VICENTE_PLANEAMENTO':"Planeamento",'PORTO_SANTO_CARTOGRAFIA':"Cartografia",'PORTO_SANTO_CONDICIONANTES':"Condicionantes",'PORTO_SANTO_ORDENAMENTO':"Ordenamento",'PORTO_SANTO_PLANEAMENTO':"Planeamento",'MACHICO_CARTOGRAFIA':"Cartografia",'MACHICO_CONDICIONANTES':"Condicionantes",'MACHICO_ORDENAMENTO':"Ordenamento",'MACHICO_PLANEAMENTO':"Planeamento",'PDM_ORDENAMENTO':"Ordenamento",'print.information':"Informação",'print.error':"Erro",'print.pdfReady':"Resultado da Impressão",'print.mapTitle':"Título",'print.comments':"Comentários",'print.loadingConfig':"A Carregar Configuração",'print.print':"Imprimir",'print.print-tooltip':"Imprimir Área Visível",'print.scale':"Escala",'print.dpi':"DPI",'print.layout':"Layout",'print.rotation':"Rotação",'print.resetPos':"Posição Inicial",'print.addPage':"Adicionar Página",'print.remove':"Remover Página",'print.clearAll':"Remover Tudo",'print.noPage':"Sem Página",'print.generatingPDF':"A Gerar Impressão...",'print.popupBlocked':"Popups Bloqueados",'print.unableToPrint':"Impossível Efectuar Impressão",'print.titlePIP':"Pedido de Informação Simples",'print.print-tooltipPIP':'Imprimir Pedido de Informação Simples','print.intersections':"Informação Simples",'print.missfeaturesintersection':"É necessário desenhar a área de intersecção.",'print.pdm.fieldset':"Plantas do PDM:",'print.pdm.btnprint':"Imprimir",'print.pdm.btncancel':"Cancelar",'print.pdm.nolayers':"Não existem plantas definidas para a impressão do PDM!",'print.print-pdm':"Imprimir PDM",'print.pip.errorFeature':"Por favor, desenhe um polígono com a àrea da pretensão pretendida para intersectar a Carta de Ordenamento.",'print.pdfView':"Visualizar Impressão",'print.name-pdf':"Impressão",'print.acrobat-reader-msg':"Necessita do plugin do Acrobat Reader para poder visualizar a impressão de plantas. Pode obter o plugin do Acrobat reader <a href='http://www.adobe.com' target='_blank'>aqui</a>.",'plantas.title':"Plantas",'plantas.local':"Local da Obra",'plantas.freguesia':"Freguesia",'plantas.freguesia.emptytext':"Seleccione Freguesia...",'plantas.freguesia.invalidText':"Freguesia inválida",'plantas.nome':"Nome",'plantas.contribuinte':"NIF",'plantas.n_planta':"Nº Planta",'plantas.gerar':"Emitir Plantas",'plantas.loadingConfig':"A Carregar Configuração",'plantas.natobra':"Tipo de Obra",'plantas.natobra.tipo':"Tipo",'plantas.natobra.grupo':"Grupo",'plantas.fieldsetnatobra':"Finalidade",'plantas.fieldsetrequerente':"Dados do Requerente",'plantas.fieldsetDates':"Data de Emissão",'plantas.emptyTipoNatObra':"Tipos de Obra...",'plantas.emptyGrupoNatObra':"Grupo de Obra...",'plantas.information':"Informação",'plantas.generatingPDF':"A Emitir Plantas...",'plantas.pdfReady':"Resultado da Emissão de Plantas",'print.acrobat-reader-msg':"Necessita do plugin do Acrobat Reader para poder visualizar a impressão de plantas. Pode obter o plugin do Acrobat reader <a href='http://www.adobe.com' target='_blank'>aqui</a>.",'print.pdfView':"Visualizar Plantas de Localização",'plantas.error':"Erro",'plantas.unableToPrint':"Impossível Efectuar a Emissão das Plantas de Localização",'plantas.local.blankText':"Local da Obra é necessário",'plantas.nome.blankText':"Nome do Requerente é necessário",'plantas.contribuinte.blankText':"Nº Contribuinte é necessário",'plantas.contribuinte.invalidText':"Nº Contribuinte inválido",'plantas.gobra.blankText':"Grupo de Obra é necessário",'plantas.gobra.invalidText':"Grupo de Obra inválido",'plantas.tobra.blankText':"Tipo de Obra é necessário",'plantas.tobra.invalidText':"Tipo de Obra inválido",'plantas.name-pdf':"Impressão de 'Plantas de Localização'",'plantas.emissao.title':"Emitir Plantas",'plantas.pedidos.title':"Pesquisar Pedidos",'plantas.pedidos.pesquisar':"Pesquisar",'plantas.pedidos.imprimir':"Imprimir",'plantas.pedidos.deleteFeatureWKT':"Deverá seleccionar o pedido pretendido.",'plantas.pedidos.errorFeatureWKT':"Por favor, desenhe o polígono para a pretensão pretendida.",'plantas.pedidos.selectPedido':"Click para Seleccionar Pedido",'plantas.pedidos.generatingPDF':"A Imprimir Planta",'plantas.username':"Utilizador",'plantas.password':"Password",'plantas.fieldsetlogin':"Autenticação",'plantas.login':"Login",'plantas.msgLogin':"A Verificar Autenticação...",'plantas.login.failed':"Login Incorrecto.",'plantas.pretensao':"Pretensão",'plantas.emptyPretensao':"Tipos de Pretensão...",'plantas.pretensao.invalidText':"Pretensão inválida",'estatisticos.title':"Informação Estatística",'estatisticos.censos':"Censos",'estatisticos.basegeografica':"Base Geográfica",'estatisticos.emptytext_basegeografica':"Seleccione Base Geográfica...",'estatisticos.fs_basegeografica':"Base Geográfica",'estatisticos.distrito':"Distrito",'estatisticos.emptytext_distrito':"Seleccione um Distrito...",'estatisticos.por':"por",'estatisticos.emptytext_por':"---",'estatisticos.concelho':"Concelho",'estatisticos.emptytext_concelho':"Seleccione um Concelho...",'estatisticos.freguesia':"Freguesia",'estatisticos.emptytext_freguesia':"Seleccione uma Freguesia...",'estatisticos.lugares':"Lugar",'estatisticos.emptytext_lugares':"Seleccione um Lugar...",'estatisticos.grupo':"Grupo",'estatisticos.emptytext_grupo':"Seleccione um Grupo",'estatisticos.variavel':"Variável",'estatisticos.emptytext_variavel':"Seleccione uma Variável",'estatisticos.fs_variavel':"Variáveis",'estatisticos.fs_classes':"Classes",'estatisticos.metodo':"Método",'estatisticos.emptytext_metodo':"Seleccione o Método...",'estatisticos.metodo.intervalo_igual':"Intervalos Iguais",'estatisticos.metodo.quantidades':"Quantis",'estatisticos.n_classes':"Nº de Classes",'estatisticos.cor_1':"Côr Classe 1",'estatisticos.cor_2':"Côr Classe n",'estatisticos.error':"Erro",'estatisticos.information':"Informação",'estatisticos.export2CSV':"Exportar para CSV",'estatisticos.export2PDF':"Exportar para PDF",'estatisticos.pais':"País",'estatisticos.distrito':"Distrito",'estatisticos.concelho':"Concelho",'estatisticos.freguesia':"Freguesia",'estatisticos.seccao':"Secção",'estatisticos.lugar':"Lugar",'estatisticos.subseccao':"Sub-Secção",'estatisticos.generatingMapa':"A Gerar Mapa Estatístico...",'estatisticos.resultErrorMapa':"Não foi possível gerar o mapa estatístico.",'estatisticos.empty_bg':"Deve seleccionar a Base Geográfica.",'estatisticos.empty_variavel':"Deve seleccionar uma variável.",'estatisticos.empty_indicador':"Deve seleccionar um método.",'estatisticos.empty_layer':"Falta o tema correspondente.",'estatisticos.btn':"Gerar Mapa",'classesEspaco.classes':"Classes de Espaço",'classesEspaco.classesLabel':"Classes:",'classesEspaco.emptyFieldClasses':"Classes de Espaço...",'classesEspaco.invalidText':"Classe de Espaço Inválida",'cadastrorustico.folha':"Folha:",'cadastrorustico.predio':"Artigo:",'cadastrorustico.title':"Cadastro Rústico",'proximidade.title':"Proximidade",'(meters)':"(metros)",'Find POIs':"Encontrar POIs e Serviços",'Next to: (ex: liberdade,10)':"Perto de: (ex: liberdade,10)",'proximdade.msg.loadMask.center':"A usar centro do Mapa...",'proximdade.msg.loadMask.default':"A pesquisar...",'proximidade.btn.cancel':"Cancelar",'proximidade.information':"Informação",'export.btn':"Exportar Àrea de Impressão para",'export.information':"Informação",'export.error':"Erro",'export.unableToExport':"Não foi possível exportar os dados.",'export.not_found_theme':"Não existe nenhum tema definido para exportação.",'export.not_zoom_correct':"Esta funcionalidade só é permitida a partir da escala 1:2000",'export.confirm':"Confirmar",'export.confirm_message':"Pretende exportar a àrea de impressão para",'end':''};OpenLayers.Layer.VirtualEarth5Plus=OpenLayers.Class(OpenLayers.Layer.EventPane,OpenLayers.Layer.FixedZoomLevels,{MIN_ZOOM_LEVEL:0,MAX_ZOOM_LEVEL:19,RESOLUTIONS:[1.40625,0.703125,0.3515625,0.17578125,0.087890625,0.0439453125,0.02197265625,0.010986328125,0.0054931640625,0.00274658203125,0.001373291015625,0.0006866455078125,0.00034332275390625,0.000171661376953125,0.0000858306884765625,0.00004291534423828125,0.00002145767211914062,0.00001072883605957031,0.00000536441802978515,0.00000268220901489257],type:null,sphericalMercator:false,initialize:function(name,options){OpenLayers.Layer.EventPane.prototype.initialize.apply(this,arguments);OpenLayers.Layer.FixedZoomLevels.prototype.initialize.apply(this,arguments);if(this.sphericalMercator){OpenLayers.Util.extend(this,OpenLayers.Layer.SphericalMercator);this.initMercatorParameters();}},loadMapObject:function(){var veDiv=OpenLayers.Util.createDiv(this.name);var sz=this.map.getSize();veDiv.style.width=sz.w;veDiv.style.height=sz.h;this.div.appendChild(veDiv);try{this.mapObject=new VEMap(this.name);}catch(e){}
if(this.mapObject!=null){this.mapObject.LoadMap(null,null,this.type);this.mapObject.HideDashboard();}},getWarningHTML:function(){var html="";html+="The VE Layer was unable to load correctly.<br>";html+="<br>";html+="To get rid of this message, select a new BaseLayer "
html+="in the layer switcher in the upper-right corner.<br>";html+="<br>";html+="Most likely, this is because the VE library";html+=" script was either not correctly included.<br>";html+="<br>";html+="Developers: For help getting this working correctly, ";html+="<a href='http://trac.openlayers.org/wiki/VirtualEarth5Plus' "
html+="target='_blank'>";html+="click here";html+="</a>";return html;},onMapResize:function(){if(this.visibility){var sz=this.map.getSize();this.mapObject.Resize(sz.w,sz.h);}else{this.windowResized=true;}},display:function(display){if(this.div.style.display!="block"){var sz=this.map.getSize();this.mapObject.Resize(sz.w,sz.h);this.windowResized=false;}
OpenLayers.Layer.EventPane.prototype.display.apply(this,arguments);},setMapObjectCenter:function(center,zoom){this.mapObject.SetCenterAndZoom(center,zoom);},getMapObjectCenter:function(){return this.mapObject.GetCenter();},getMapObjectZoom:function(){return this.mapObject.GetZoomLevel();},getMapObjectLonLatFromMapObjectPixel:function(moPixel){return this.mapObject.PixelToLatLong(new VEPixel(moPixel.x,moPixel.y));},getMapObjectPixelFromMapObjectLonLat:function(moLonLat){return this.mapObject.LatLongToPixel(new VELatLong(moLonLat.Latitude,moLonLat.Longitude));},getLongitudeFromMapObjectLonLat:function(moLonLat){return this.sphericalMercator?this.forwardMercator(moLonLat.Longitude,moLonLat.Latitude).lon:moLonLat.Longitude;},getLatitudeFromMapObjectLonLat:function(moLonLat){return this.sphericalMercator?this.forwardMercator(moLonLat.Longitude,moLonLat.Latitude).lat:moLonLat.Latitude;},getMapObjectLonLatFromLonLat:function(lon,lat){var veLatLong;if(this.sphericalMercator){var lonlat=this.inverseMercator(lon,lat);veLatLong=new VELatLong(lonlat.lat,lonlat.lon);}else{veLatLong=new VELatLong(lat,lon);}
return veLatLong;},getXFromMapObjectPixel:function(moPixel){return moPixel.x;},getYFromMapObjectPixel:function(moPixel){return moPixel.y;},getMapObjectPixelFromXY:function(x,y){return new VEPixel(x,y);},CLASS_NAME:"OpenLayers.Layer.VirtualEarth5Plus"});﻿
﻿
OpenLayers.Layer.TMS.prototype.initialize=function(name,url,options,params){var newArguments=[];OpenLayers.Util.extend(options,params)
newArguments.push(name,url,{},options);OpenLayers.Layer.Grid.prototype.initialize.apply(this,newArguments);};﻿
OpenLayers.Layer.VirtualEarth.prototype.onMapResize=function(){if(this.mapObject){if(this.visibility){var sz=this.map.getSize();this.mapObject.Resize(sz.w,sz.h);}else{this.windowResized=true;}}};OpenLayers.Layer.VirtualEarth.prototype.display=function(display){OpenLayers.Layer.EventPane.prototype.display.apply(this,arguments);if(this.div.style.display=="block"&&this.windowResized){var sz=this.map.getSize();this.mapObject.Resize(sz.w,sz.h);this.windowResized=false;}};OpenLayers.Layer.VirtualEarth5Plus=OpenLayers.Class(OpenLayers.Layer.EventPane,OpenLayers.Layer.FixedZoomLevels,{MIN_ZOOM_LEVEL:1,MAX_ZOOM_LEVEL:17,RESOLUTIONS:[1.40625,0.703125,0.3515625,0.17578125,0.087890625,0.0439453125,0.02197265625,0.010986328125,0.0054931640625,0.00274658203125,0.001373291015625,0.0006866455078125,0.00034332275390625,0.000171661376953125,0.0000858306884765625,0.00004291534423828125,0.00002145767211914062],type:null,sphericalMercator:false,initialize:function(name,options){OpenLayers.Layer.EventPane.prototype.initialize.apply(this,arguments);OpenLayers.Layer.FixedZoomLevels.prototype.initialize.apply(this,arguments);if(this.sphericalMercator){OpenLayers.Util.extend(this,OpenLayers.Layer.SphericalMercator);this.initMercatorParameters();}},loadMapObject:function(){var veDiv=OpenLayers.Util.createDiv(this.name);var sz=this.map.getSize();veDiv.style.width=sz.w+"px";veDiv.style.height=sz.h+"px";this.div.appendChild(veDiv);try{this.mapObject=new VEMap(this.name);}catch(e){}
if(this.mapObject!=null){try{this.mapObject.LoadMap(null,null,this.type,true);this.mapObject.AttachEvent("onmousedown",function(){return true;});}catch(e){}
this.mapObject.HideDashboard();}
if(!this.mapObject||!this.mapObject.vemapcontrol||!this.mapObject.vemapcontrol.PanMap||(typeof this.mapObject.vemapcontrol.PanMap!="function")){this.dragPanMapObject=null;}},getWarningHTML:function(){return OpenLayers.i18n("getLayerWarning",{'layerType':'VE','layerLib':'VirtualEarth5Plus'});},setMapObjectCenter:function(center,zoom){this.mapObject.SetCenterAndZoom(center,zoom);},getMapObjectCenter:function(){return this.mapObject.GetCenter();},dragPanMapObject:function(dX,dY){this.mapObject.vemapcontrol.PanMap(dX,-dY);},getMapObjectZoom:function(){return this.mapObject.GetZoomLevel();},getMapObjectLonLatFromMapObjectPixel:function(moPixel){return(typeof VEPixel!='undefined')?this.mapObject.PixelToLatLong(moPixel):this.mapObject.PixelToLatLong(moPixel.x,moPixel.y);},getMapObjectPixelFromMapObjectLonLat:function(moLonLat){return this.mapObject.LatLongToPixel(moLonLat);},onMapResize:function(){if(this.visibility){var sz=this.map.getSize();this.mapObject.Resize(sz.w,sz.h);}else{this.windowResized=true;}},display:function(display){if(this.div.style.display=="block"){var sz=this.map.getSize();this.mapObject.Resize(sz.w,sz.h);this.windowResized=false;}
OpenLayers.Layer.EventPane.prototype.display.apply(this,arguments);},getLongitudeFromMapObjectLonLat:function(moLonLat){return this.sphericalMercator?this.forwardMercator(moLonLat.Longitude,moLonLat.Latitude).lon:moLonLat.Longitude;},getLatitudeFromMapObjectLonLat:function(moLonLat){return this.sphericalMercator?this.forwardMercator(moLonLat.Longitude,moLonLat.Latitude).lat:moLonLat.Latitude;},getMapObjectLonLatFromLonLat:function(lon,lat){var veLatLong;if(this.sphericalMercator){var lonlat=this.inverseMercator(lon,lat);veLatLong=new VELatLong(lonlat.lat,lonlat.lon);}else{veLatLong=new VELatLong(lat,lon);}
return veLatLong;},getXFromMapObjectPixel:function(moPixel){return moPixel.x;},getYFromMapObjectPixel:function(moPixel){return moPixel.y;},getMapObjectPixelFromXY:function(x,y){return(typeof VEPixel!='undefined')?new VEPixel(x,y):new Msn.VE.Pixel(x,y);},CLASS_NAME:"OpenLayers.Layer.VirtualEarth5Plus"});﻿
OpenLayers.Layer.WFS.prototype.useBbox=true;OpenLayers.Layer.WFS.prototype.useFilterBbox=false;OpenLayers.Layer.WFS.prototype.useFilterFid=false;OpenLayers.Layer.WFS.prototype.useFilterTipo=false;OpenLayers.Layer.WFS.prototype.filterFid=null;OpenLayers.Layer.WFS.prototype.sld=null;OpenLayers.Layer.WFS.prototype.initialize=function(name,url,params,options){if(options==undefined){options={};}
if(options.featureClass||!OpenLayers.Layer.Vector||!OpenLayers.Feature.Vector){this.vectorMode=false;}
OpenLayers.Util.extend(options,{'reportError':false});var newArguments=[];newArguments.push(name,options);OpenLayers.Layer.Vector.prototype.initialize.apply(this,newArguments);if(!this.renderer||!this.vectorMode){this.vectorMode=false;if(!options.featureClass){options.featureClass=OpenLayers.Feature.WFS;}
OpenLayers.Layer.Markers.prototype.initialize.apply(this,newArguments);}
if(this.params&&this.params.typename&&!this.options.typename){this.options.typename=this.params.typename;}
if(!this.options.geometry_column){this.options.geometry_column="the_geom";}
if(this.options.useBbox){this.useBbox=this.options.useBbox;}
if(this.options.useFilterBbox){this.useFilterBbox=this.options.useFilterBbox;}
if(this.options.useFilterFid){this.useFilterFid=this.options.useFilterFid;}
if(this.options.useFilterTipo){this.useFilterTipo=this.options.useFilterTipo;}
this.params=OpenLayers.Util.applyDefaults(params,OpenLayers.Util.upperCaseObject(this.DEFAULT_PARAMS));this.url=url;if(this.options.sld_wfs){OpenLayers.loadURL(this.options.sld_wfs,'',this,this.stylesLoadComplete,this.stylesLoadFailure);}};OpenLayers.Layer.WFS.prototype.stylesLoadComplete=function(request){var format=new OpenLayers.Format.SLD();var sld=format.read(request.responseXML||request.responseText);for(var namedLayer in sld.namedLayers){break;}
var style=sld.namedLayers[namedLayer].userStyles[0];var styleMap=new OpenLayers.StyleMap({"default":style});this.styleMap=styleMap;};OpenLayers.Layer.WFS.prototype.stylesLoadFailure=function(request){OpenLayers.Console.error('Ajax request STYLES failed');};OpenLayers.Layer.WFS.prototype.moveTo=function(bounds,zoomChanged,dragging){if(this.vectorMode){OpenLayers.Layer.Vector.prototype.moveTo.apply(this,arguments);}else{OpenLayers.Layer.Markers.prototype.moveTo.apply(this,arguments);}
if(dragging){return false;}
if(zoomChanged){if(this.vectorMode){this.renderer.clear();}}
if(this.options.minZoomLevel){OpenLayers.Console.warn(OpenLayers.i18n('minZoomLevelError'));if(this.map.getZoom()<this.options.minZoomLevel){return null;}}
if(bounds==null){bounds=this.map.getExtent();}
var firstRendering=(this.tile==null);var outOfBounds=(!firstRendering&&!this.tile.bounds.containsBounds(bounds));if(zoomChanged||firstRendering||(!dragging&&outOfBounds)){var center=bounds.getCenterLonLat();var tileWidth=bounds.getWidth()*this.ratio;var tileHeight=bounds.getHeight()*this.ratio;var tileBounds=new OpenLayers.Bounds(center.lon-(tileWidth/2),center.lat-(tileHeight/2),center.lon+(tileWidth/2),center.lat+(tileHeight/2));var tileSize=this.map.getSize();tileSize.w=tileSize.w*this.ratio;tileSize.h=tileSize.h*this.ratio;var ul=new OpenLayers.LonLat(tileBounds.left,tileBounds.top);var pos=this.map.getLayerPxFromLonLat(ul);var url=this.getFullRequestString();var params={};var projectionBBOX=this.map.getProjectionObject();var projectedBounds=tileBounds.clone();if(this.map&&!this.projection.equals(this.map.getProjectionObject())){projectedBounds.transform(this.map.getProjectionObject(),this.projection);projectionBBOX=this.projection;}
if(this.useBbox){params={BBOX:this.encodeBBOX?projectedBounds.toBBOX():projectedBounds.toArray()}
params.BBOX+=","+projectionBBOX;};var filter="(<ogc:Filter xmlns:ogc='http://www.opengis.net/ogc'  xmlns:gml='http://www.opengis.net/gml' >";if(this.useFilterBbox){if(this.useFilterFid||this.useFilterTipo){filter+="<ogc:And>"}
filter+="<ogc:BBOX>";filter+="<ogc:PropertyName>";filter+=this.options.geometry_column
filter+="</ogc:PropertyName>"
filter+="<gml:Box srsName='"+this.map.getProjectionObject()+"' >";filter+="<gml:coordinates>"+projectedBounds.left+","+projectedBounds.bottom+" "+projectedBounds.right+","+projectedBounds.top+"</gml:coordinates>";filter+="</gml:Box>";filter+="</ogc:BBOX>";}
if(this.useFilterFid){if(this.useFilterTipo){filter+="<ogc:And>"}
filter+=" <ogc:FeatureId fid='"+this.options.typename+"."+this.filterFid+"'/>";if(this.useFilterBbox||this.useFilterTipo){filter+="</ogc:And>"}}
if(this.useFilterTipo){filter+="<ogc:PropertyIsEqualTo>";filter+="<ogc:PropertyName>";filter+=this.options.tipo_column;filter+="</ogc:PropertyName>";filter+="<ogc:Literal>";filter+=this.params.tipoid;filter+="</ogc:Literal>";filter+="</ogc:PropertyIsEqualTo>";if(this.useFilterBbox||this.useFilterFid){filter+="</ogc:And>"}}
if(this.useFilterFid||this.useFilterBbox||this.useFilterTipo){filter+="</ogc:Filter>)";params.FILTER=filter;params.ALEATORIO=Math.random();}
url+="&"+OpenLayers.Util.getParameterString(params);if(!this.tile){this.tile=new OpenLayers.Tile.WFS(this,pos,tileBounds,url,tileSize);this.addTileMonitoringHooks(this.tile);this.tile.draw();}else{if(this.vectorMode){this.destroyFeatures();this.renderer.clear();}else{this.clearMarkers();}
this.removeTileMonitoringHooks(this.tile);this.tile.destroy();this.tile=null;this.tile=new OpenLayers.Tile.WFS(this,pos,tileBounds,url,tileSize);this.addTileMonitoringHooks(this.tile);this.tile.draw();}}};Municipia.LayerSwitcher=Municipia.Class({map:null,initialize:function(init){for(var arg in init){this[arg]=init[arg];}
this.map=this.map;this.div=OpenLayers.Util.getElement(this.div);var id=this.div.id+"_LayerSwitcher_ViewPort";this.viewPortDiv=OpenLayers.Util.createDiv(id,null,null,null,"relative",null,"hidden");this.viewPortDiv.style.width="100%";this.viewPortDiv.style.height="100%";this.div.appendChild(this.viewPortDiv);this.makelayerSwitcherer();this.map.events.register("moveend",this,this.onZoomend);Municipia.LayerSwitcher.currentInstance=this;},makelayerSwitcherer:function(){},onZoomend:function(map){var tt="";},CLASS_NAME:"Municipia.LayerSwitcher"});﻿Ext.namespace('Municipia.LegendNodeUI');Municipia.LegendNodeUI=function(node){Municipia.LegendNodeUI.superclass.constructor.call(this,node);};Ext.extend(Municipia.LegendNodeUI,Ext.tree.TreeNodeUI,{renderElements:function(n,a,targetNode,bulkRender){this.indentMarkup=n.parentNode?n.parentNode.ui.getChildIndent():'';var cb=typeof a.checked=='boolean';var href=a.href?a.href:Ext.isGecko?"":"#";var buf=['<li class="x-tree-node"><div ext:tree-node-id="',n.id,'" class="x-tree-node-el x-tree-node-leaf x-unselectable ',a.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="',a.icon||this.emptyIcon,'" class="',(a.icon?" x-tree-node-inline-icon":""),(a.iconCls?" "+a.iconCls:""),'" unselectable="on" />',cb?('<input class="x-tree-node-cb" type="checkbox" '+(a.checked?'checked="checked" />':'/>')):'','<a hidefocus="on" class="x-tree-node-anchor" href="',href,'" tabIndex="1" ',a.hrefTarget?' target="'+a.hrefTarget+'"':"",'><span unselectable="on">',n.text,"</span></a></div>",'<ul class="x-tree-node-ct" style="display:none;"></ul>',"</li>"].join('');var nel;if(bulkRender!==true&&n.nextSibling&&(nel=n.nextSibling.ui.getEl())){this.wrap=Ext.DomHelper.insertHtml("beforeBegin",nel,buf);}else{this.wrap=Ext.DomHelper.insertHtml("beforeEnd",targetNode,buf);}
this.elNode=this.wrap.childNodes[0];this.ctNode=this.wrap.childNodes[1];var cs=this.elNode.childNodes;this.indentNode=cs[0];this.ecNode=cs[1];this.iconNode=cs[2];var index=3;if(cb){this.checkbox=cs[3];this.checkbox.defaultChecked=this.checkbox.checked;index++;}
this.anchor=cs[index];this.textNode=cs[index].firstChild;},onOver:function(e){},onOut:function(e){}});Municipia.Marker=Municipia.Class({icon:null,lonlat:null,events:null,map:null,initialize:function(lonlat,icon){this.lonlat=lonlat;var newIcon=(icon)?icon:OpenLayers.Marker.defaultIcon();if(this.icon==null){this.icon=newIcon;}else{this.icon.url=newIcon.url;this.icon.size=newIcon.size;this.icon.offset=newIcon.offset;this.icon.calculateOffset=newIcon.calculateOffset;}
this.events=new OpenLayers.Events(this,this.icon.imageDiv,null);},destroy:function(){this.map=null;this.events.destroy();this.events=null;if(this.icon!=null){this.icon.destroy();this.icon=null;}},draw:function(px){return this.icon.draw(px);},moveTo:function(px){if((px!=null)&&(this.icon!=null)){this.icon.moveTo(px);}
this.lonlat=this.map.getLonLatFromLayerPx(px);},isDrawn:function(){var isDrawn=(this.icon&&this.icon.isDrawn());return isDrawn;},onScreen:function(){var onScreen=false;if(this.map){var screenBounds=this.map.getExtent();onScreen=screenBounds.containsLonLat(this.lonlat);}
return onScreen;},inflate:function(inflate){if(this.icon){var newSize=new OpenLayers.Size(this.icon.size.w*inflate,this.icon.size.h*inflate);this.icon.setSize(newSize);}},setOpacity:function(opacity){this.icon.setOpacity(opacity);},setUrl:function(url){this.icon.setUrl(url);},display:function(display){this.icon.display(display);},CLASS_NAME:"Municipia.Marker"});Municipia.Marker.defaultIcon=function(){var url=OpenLayers.Util.getImagesLocation()+"marker.png";var size=new OpenLayers.Size(21,25);var calculateOffset=function(size){return new OpenLayers.Pixel(-(size.w/2),-size.h);};return new OpenLayers.Icon(url,size,null,calculateOffset);};Municipia.Popup=Municipia.Class({events:null,id:"",lonlat:null,div:null,contentSize:null,size:null,contentHTML:null,backgroundColor:"",opacity:"",border:"",contentDiv:null,groupDiv:null,closeDiv:null,autoSize:false,minSize:null,maxSize:null,displayClass:"olPopup",contentDisplayClass:"olPopupContent",padding:0,fixPadding:function(){if(typeof this.padding=="number"){this.padding=new Municipia.Bounds(this.padding,this.padding,this.padding,this.padding);}},panMapIfOutOfView:false,keepInMap:false,closeOnMove:false,map:null,initialize:function(id,lonlat,contentSize,contentHTML,closeBox,closeBoxCallback){if(id==null){id=Municipia.Util.createUniqueID(this.CLASS_NAME+"_");}
this.id=id;this.lonlat=lonlat;this.contentSize=(contentSize!=null)?contentSize:new Municipia.Size(Municipia.Popup.WIDTH,Municipia.Popup.HEIGHT);if(contentHTML!=null){this.contentHTML=contentHTML;}
this.backgroundColor=Municipia.Popup.COLOR;this.opacity=Municipia.Popup.OPACITY;this.border=Municipia.Popup.BORDER;this.div=Municipia.Util.createDiv(this.id,null,null,null,null,null,"hidden");this.div.className=this.displayClass;var groupDivId=this.id+"_GroupDiv";this.groupDiv=Municipia.Util.createDiv(groupDivId,null,null,null,"relative",null,"hidden");var id=this.div.id+"_contentDiv";this.contentDiv=Municipia.Util.createDiv(id,null,this.contentSize.clone(),null,"relative");this.contentDiv.className=this.contentDisplayClass;this.groupDiv.appendChild(this.contentDiv);this.div.appendChild(this.groupDiv);if(closeBox){this.addCloseBox(closeBoxCallback);}
this.registerEvents();},destroy:function(){try
{this.id=null;this.lonlat=null;this.size=null;this.contentHTML=null;this.backgroundColor=null;this.opacity=null;this.border=null;if(this.closeOnMove&&this.map){this.map.events.unregister("movestart",this,this.hide);}
if(this.events!=null)
this.events.destroy();this.events=null;if(this.closeDiv){Municipia.Event.stopObservingElement(this.closeDiv);this.groupDiv.removeChild(this.closeDiv);}
this.closeDiv=null;this.div.removeChild(this.groupDiv);this.groupDiv=null;if(this.map!=null){this.map.removePopup(this);}
this.map=null;this.div=null;this.autoSize=null;this.minSize=null;this.maxSize=null;this.padding=null;this.panMapIfOutOfView=null;}
catch(err)
{}},draw:function(px){if(px==null){if((this.lonlat!=null)&&(this.map!=null)){px=this.map.getLayerPxFromLonLat(this.lonlat);}}
if(this.closeOnMove){this.map.events.register("movestart",this,this.hide);}
if(Municipia.Util.getBrowserName()=='firefox'){this.map.events.register("movestart",this,function(){var style=document.defaultView.getComputedStyle(this.contentDiv,null);var currentOverflow=style.getPropertyValue("overflow");if(currentOverflow!="hidden"){this.contentDiv._oldOverflow=currentOverflow;this.contentDiv.style.overflow="hidden";}});this.map.events.register("moveend",this,function(){var oldOverflow=this.contentDiv._oldOverflow;if(oldOverflow){this.contentDiv.style.overflow=oldOverflow;this.contentDiv._oldOverflow=null;}});}
this.moveTo(px);if(!this.autoSize&&!this.size){this.setSize(this.contentSize);}
this.setBackgroundColor();this.setOpacity();this.setBorder();this.setContentHTML();if(this.panMapIfOutOfView){this.panIntoView();}
return this.div;},updatePosition:function(){if((this.lonlat)&&(this.map)){var px=this.map.getLayerPxFromLonLat(this.lonlat);if(px){this.moveTo(px);}}},moveTo:function(px){if((px!=null)&&(this.div!=null)){this.div.style.left=px.x+"px";this.div.style.top=px.y+"px";}},visible:function(){return Municipia.Element.visible(this.div);},toggle:function(){if(this.visible()){this.hide();}else{this.show();}},show:function(){Municipia.Element.show(this.div);if(this.panMapIfOutOfView){this.panIntoView();}},hide:function(){Municipia.Element.hide(this.div);},setSize:function(contentSize){this.size=contentSize.clone();var contentDivPadding=this.getContentDivPadding();var wPadding=contentDivPadding.left+contentDivPadding.right;var hPadding=contentDivPadding.top+contentDivPadding.bottom;this.fixPadding();wPadding+=this.padding.left+this.padding.right;hPadding+=this.padding.top+this.padding.bottom;if(this.closeDiv){var closeDivWidth=parseInt(this.closeDiv.style.width);wPadding+=closeDivWidth+contentDivPadding.right;}
this.size.w+=wPadding;this.size.h+=hPadding;if(Municipia.Util.getBrowserName()=="msie"){this.contentSize.w+=contentDivPadding.left+contentDivPadding.right;this.contentSize.h+=contentDivPadding.bottom+contentDivPadding.top;}
if(this.div!=null){this.div.style.width=this.size.w+"px";this.div.style.height=this.size.h+"px";}
if(this.contentDiv!=null){this.contentDiv.style.width=contentSize.w+"px";this.contentDiv.style.height=contentSize.h+"px";}},updateSize:function(){var preparedHTML="<div class='"+this.contentDisplayClass+"'>"+
this.contentDiv.innerHTML+"<div>";var containerElement=(this.map)?this.map.layerContainerDiv:document.body;var realSize=Municipia.Util.getRenderedDimensions(preparedHTML,null,{displayClass:this.displayClass,containerElement:containerElement});var safeSize=this.getSafeContentSize(realSize);var newSize=null;if(safeSize.equals(realSize)){newSize=realSize;}else{var fixedSize=new Municipia.Size();fixedSize.w=(safeSize.w<realSize.w)?safeSize.w:null;fixedSize.h=(safeSize.h<realSize.h)?safeSize.h:null;if(fixedSize.w&&fixedSize.h){newSize=safeSize;}else{var clippedSize=Municipia.Util.getRenderedDimensions(preparedHTML,fixedSize,{displayClass:this.contentDisplayClass,containerElement:containerElement});var currentOverflow=Municipia.Element.getStyle(this.contentDiv,"overflow");if((currentOverflow!="hidden")&&(clippedSize.equals(safeSize))){var scrollBar=Municipia.Util.getScrollbarWidth();if(fixedSize.w){clippedSize.h+=scrollBar;}else{clippedSize.w+=scrollBar;}}
newSize=this.getSafeContentSize(clippedSize);}}
this.setSize(newSize);},setBackgroundColor:function(color){if(color!=undefined){this.backgroundColor=color;}
if(this.div!=null){this.div.style.backgroundColor=this.backgroundColor;}},setOpacity:function(opacity){if(opacity!=undefined){this.opacity=opacity;}
if(this.div!=null){this.div.style.opacity=this.opacity;this.div.style.filter='alpha(opacity='+this.opacity*100+')';}},setBorder:function(border){if(border!=undefined){this.border=border;}
if(this.div!=null){this.div.style.border=this.border;}},setContentHTML:function(contentHTML){if(contentHTML!=null){this.contentHTML=contentHTML;}
if((this.contentDiv!=null)&&(this.contentHTML!=null)&&(this.contentHTML!=this.contentDiv.innerHTML)){this.contentDiv.innerHTML=this.contentHTML;if(this.autoSize){this.registerImageListeners();this.updateSize();}}},registerImageListeners:function(){var onImgLoad=function(){this.popup.updateSize();if(this.popup.visible()&&this.popup.panMapIfOutOfView){this.popup.panIntoView();}
Municipia.Event.stopObserving(this.img,"load",this.img._onImageLoad);};var images=this.contentDiv.getElementsByTagName("img");for(var i=0,len=images.length;i<len;i++){var img=images[i];if(img.width==0||img.height==0){var context={'popup':this,'img':img};img._onImgLoad=Municipia.Function.bind(onImgLoad,context);Municipia.Event.observe(img,'load',img._onImgLoad);}}},getSafeContentSize:function(size){var safeContentSize=size.clone();var contentDivPadding=this.getContentDivPadding();var wPadding=contentDivPadding.left+contentDivPadding.right;var hPadding=contentDivPadding.top+contentDivPadding.bottom;this.fixPadding();wPadding+=this.padding.left+this.padding.right;hPadding+=this.padding.top+this.padding.bottom;if(this.closeDiv){var closeDivWidth=parseInt(this.closeDiv.style.width);wPadding+=closeDivWidth+contentDivPadding.right;}
if(this.minSize){safeContentSize.w=Math.max(safeContentSize.w,(this.minSize.w-wPadding));safeContentSize.h=Math.max(safeContentSize.h,(this.minSize.h-hPadding));}
if(this.maxSize){safeContentSize.w=Math.min(safeContentSize.w,(this.maxSize.w-wPadding));safeContentSize.h=Math.min(safeContentSize.h,(this.maxSize.h-hPadding));}
if(this.map&&this.map.size){var extraX=0,extraY=0;if(this.keepInMap&&!this.panMapIfOutOfView){var px=this.map.getPixelFromLonLat(this.lonlat);switch(this.relativePosition){case"tr":extraX=px.x;extraY=this.map.size.h-px.y;break;case"tl":extraX=this.map.size.w-px.x;extraY=this.map.size.h-px.y;break;case"bl":extraX=this.map.size.w-px.x;extraY=px.y;break;case"br":extraX=px.x;extraY=px.y;break;default:extraX=px.x;extraY=this.map.size.h-px.y;break;}}
var maxY=this.map.size.h-
this.map.paddingForPopups.top-
this.map.paddingForPopups.bottom-
hPadding-extraY;var maxX=this.map.size.w-
this.map.paddingForPopups.left-
this.map.paddingForPopups.right-
wPadding-extraX;safeContentSize.w=Math.min(safeContentSize.w,maxX);safeContentSize.h=Math.min(safeContentSize.h,maxY);}
return safeContentSize;},getContentDivPadding:function(){var contentDivPadding=this._contentDivPadding;if(!contentDivPadding){if(this.div.parentNode==null){this.div.style.display="none";document.body.appendChild(this.div);}
contentDivPadding=new Municipia.Bounds(Municipia.Element.getStyle(this.contentDiv,"padding-left"),Municipia.Element.getStyle(this.contentDiv,"padding-bottom"),Municipia.Element.getStyle(this.contentDiv,"padding-right"),Municipia.Element.getStyle(this.contentDiv,"padding-top"));this._contentDivPadding=contentDivPadding;if(this.div.parentNode==document.body){document.body.removeChild(this.div);this.div.style.display="";}}
return contentDivPadding;},addCloseBox:function(callback){this.closeDiv=Municipia.Util.createDiv(this.id+"_close",null,new Municipia.Size(17,17));this.closeDiv.className="olPopupCloseBox";var contentDivPadding=this.getContentDivPadding();this.closeDiv.style.right=contentDivPadding.right+"px";this.closeDiv.style.top=contentDivPadding.top+"px";this.groupDiv.appendChild(this.closeDiv);var closePopup=callback||function(e){this.hide();Municipia.Event.stop(e);};Municipia.Event.observe(this.closeDiv,"click",Municipia.Function.bindAsEventListener(closePopup,this));},panIntoView:function(){var mapSize=this.map.getSize();var origTL=this.map.getViewPortPxFromLayerPx(new Municipia.Pixel(parseInt(this.div.style.left),parseInt(this.div.style.top)));var newTL=origTL.clone();if(origTL.x<this.map.paddingForPopups.left){newTL.x=this.map.paddingForPopups.left;}else
if((origTL.x+this.size.w)>(mapSize.w-this.map.paddingForPopups.right)){newTL.x=mapSize.w-this.map.paddingForPopups.right-this.size.w;}
if(origTL.y<this.map.paddingForPopups.top){newTL.y=this.map.paddingForPopups.top;}else
if((origTL.y+this.size.h)>(mapSize.h-this.map.paddingForPopups.bottom)){newTL.y=mapSize.h-this.map.paddingForPopups.bottom-this.size.h;}
var dx=origTL.x-newTL.x;var dy=origTL.y-newTL.y;this.map.pan(dx,dy);},registerEvents:function(){this.events=new Municipia.Events(this,this.div,null,true);this.events.on({"mousedown":this.onmousedown,"mousemove":this.onmousemove,"mouseup":this.onmouseup,"click":this.onclick,"mouseout":this.onmouseout,"dblclick":this.ondblclick,scope:this});},onmousedown:function(evt){this.mousedown=true;Municipia.Event.stop(evt,true);},onmousemove:function(evt){if(this.mousedown){Municipia.Event.stop(evt,true);}},onmouseup:function(evt){if(this.mousedown){this.mousedown=false;Municipia.Event.stop(evt,true);}},onclick:function(evt){Municipia.Event.stop(evt,true);},onmouseout:function(evt){this.mousedown=false;},ondblclick:function(evt){Municipia.Event.stop(evt,true);},CLASS_NAME:"Municipia.Popup"});Municipia.Popup.WIDTH=200;Municipia.Popup.HEIGHT=200;Municipia.Popup.COLOR="white";Municipia.Popup.OPACITY=1;Municipia.Popup.BORDER="0px";OpenLayers.Format.SLD.v1_0_0.prototype.readers=OpenLayers.Util.applyDefaults({"sld":{"StyledLayerDescriptor":function(node,sld){sld.version=node.getAttribute("version");this.readChildNodes(node,sld);},"Name":function(node,obj){obj.name=this.getChildValue(node);},"Title":function(node,obj){obj.title=this.getChildValue(node);},"Abstract":function(node,obj){obj.description=this.getChildValue(node);},"NamedLayer":function(node,sld){var layer={userStyles:[],namedStyles:[]};this.readChildNodes(node,layer);for(var i=0,len=layer.userStyles.length;i<len;++i){layer.userStyles[i].layerName=layer.name;}
if(sld.namedLayers instanceof Array){sld.namedLayers.push(layer);}else{sld.namedLayers[layer.name]=layer;}},"NamedStyle":function(node,layer){layer.namedStyles.push(this.getChildName(node.firstChild));},"UserStyle":function(node,layer){var obj={defaultsPerSymbolizer:true,rules:[]};this.readChildNodes(node,obj);var style=new OpenLayers.Style(this.defaultSymbolizer,obj);layer.userStyles.push(style);},"IsDefault":function(node,style){if(this.getChildValue(node)=="1"){style.isDefault=true;}},"FeatureTypeStyle":function(node,style){var obj={rules:[]};this.readChildNodes(node,obj);style.rules=obj.rules;},"Rule":function(node,obj){var rule=new OpenLayers.Rule();this.readChildNodes(node,rule);obj.rules.push(rule);},"ElseFilter":function(node,rule){rule.elseFilter=true;},"MinScaleDenominator":function(node,rule){rule.minScaleDenominator=parseFloat(this.getChildValue(node));},"MaxScaleDenominator":function(node,rule){rule.maxScaleDenominator=parseFloat(this.getChildValue(node));},"TextSymbolizer":function(node,rule){var symbolizer=rule.symbolizer["Text"]||{};this.readChildNodes(node,symbolizer);rule.symbolizer["Text"]=symbolizer;},"Label":function(node,symbolizer){var obj={};this.readChildNodes(node,obj);if(obj.property){symbolizer.label="${"+obj.property+"}";}else{var value=this.readOgcExpression(node);if(value){symbolizer.label=value;}}},"LabelPlacement":function(node,symbolizer){var obj={};this.readChildNodes(node,obj);symbolizer.anchorpointx=obj.anchorpointx;symbolizer.anchorpointy=obj.anchorpointy;},"Font":function(node,symbolizer){this.readChildNodes(node,symbolizer);},"Halo":function(node,symbolizer){var obj={};this.readChildNodes(node,obj);symbolizer.haloRadius=obj.haloRadius;symbolizer.haloColor=obj.fillColor;symbolizer.haloOpacity=obj.fillOpacity;},"Radius":function(node,symbolizer){var radius=this.readOgcExpression(node);if(radius!=null){symbolizer.haloRadius=radius;}},"LineSymbolizer":function(node,rule){var symbolizer=rule.symbolizer["Line"]||{};this.readChildNodes(node,symbolizer);rule.symbolizer["Line"]=symbolizer;},"PolygonSymbolizer":function(node,rule){var symbolizer=rule.symbolizer["Polygon"]||{};this.readChildNodes(node,symbolizer);rule.symbolizer["Polygon"]=symbolizer;},"PointSymbolizer":function(node,rule){var symbolizer=rule.symbolizer["Point"]||{};this.readChildNodes(node,symbolizer);rule.symbolizer["Point"]=symbolizer;},"Stroke":function(node,symbolizer){symbolizer.stroke=true;this.readChildNodes(node,symbolizer);},"Fill":function(node,symbolizer){symbolizer.fill=true;this.readChildNodes(node,symbolizer);},"CssParameter":function(node,symbolizer){var cssProperty=node.getAttribute("name");var symProperty=this.cssMap[cssProperty];if(symProperty){var value=this.readOgcExpression(node);if(value){symbolizer[symProperty]=value;}}},"Graphic":function(node,symbolizer){symbolizer.graphic=true;var graphic={};this.readChildNodes(node,graphic);var properties=["strokeColor","strokeWidth","strokeOpacity","strokeLinecap","fillColor","fillOpacity","graphicName","rotation","graphicFormat"];var prop,value;for(var i=0,len=properties.length;i<len;++i){prop=properties[i];value=graphic[prop];if(value!=undefined){symbolizer[prop]=value;}}
if(graphic.opacity!=undefined){symbolizer.graphicOpacity=graphic.opacity;}
if(graphic.size!=undefined){symbolizer.pointRadius=graphic.size/2;}
if(graphic.href!=undefined){symbolizer.externalGraphic=Municipia.Util.relativeToAbsoluteURL(graphic.href);}
if(graphic.rotation!=undefined){symbolizer.rotation=graphic.rotation;}},"ExternalGraphic":function(node,graphic){this.readChildNodes(node,graphic);},"Mark":function(node,graphic){this.readChildNodes(node,graphic);},"WellKnownName":function(node,graphic){graphic.graphicName=this.getChildValue(node);},"Opacity":function(node,obj){var opacity=this.readOgcExpression(node);if(opacity){obj.opacity=opacity;}},"Size":function(node,obj){var size=this.readOgcExpression(node);if(size){obj.size=size;}},"Rotation":function(node,obj){var rotation=this.readOgcExpression(node);if(rotation){obj.rotation=rotation;}},"OnlineResource":function(node,obj){obj.href=this.getAttributeNS(node,this.namespaces.xlink,"href");},"PointPlacement":function(node,obj){this.readChildNodes(node,obj);},"AnchorPoint":function(node,obj){this.readChildNodes(node,obj);},"AnchorPointX":function(node,obj){var anchorpointx=this.readOgcExpression(node);if(anchorpointx){obj.anchorpointx=anchorpointx;}},"AnchorPointY":function(node,obj){var anchorpointy=this.readOgcExpression(node);if(anchorpointy){obj.anchorpointy=anchorpointy;}},"Format":function(node,graphic){graphic.graphicFormat=this.getChildValue(node);}}},OpenLayers.Format.Filter.v1_0_0.prototype.readers);OpenLayers.Format.SLD.v1_0_0.prototype.writers=OpenLayers.Util.applyDefaults({"sld":{"StyledLayerDescriptor":function(sld){var root=this.createElementNSPlus("sld:StyledLayerDescriptor",{attributes:{"version":this.VERSION,"xsi:schemaLocation":this.schemaLocation}});if(sld.name){this.writeNode("Name",sld.name,root);}
if(sld.title){this.writeNode("Title",sld.title,root);}
if(sld.description){this.writeNode("Abstract",sld.description,root);}
if(sld.namedLayers instanceof Array){for(var i=0,len=sld.namedLayers.length;i<len;++i){this.writeNode("NamedLayer",sld.namedLayers[i],root);}}else{for(var name in sld.namedLayers){this.writeNode("NamedLayer",sld.namedLayers[name],root);}}
return root;},"Name":function(name){return this.createElementNSPlus("sld:Name",{value:name});},"Title":function(title){return this.createElementNSPlus("sld:Title",{value:title});},"Abstract":function(description){return this.createElementNSPlus("sld:Abstract",{value:description});},"NamedLayer":function(layer){var node=this.createElementNSPlus("sld:NamedLayer");this.writeNode("Name",layer.name,node);if(layer.namedStyles){for(var i=0,len=layer.namedStyles.length;i<len;++i){this.writeNode("NamedStyle",layer.namedStyles[i],node);}}
if(layer.userStyles){for(var i=0,len=layer.userStyles.length;i<len;++i){this.writeNode("UserStyle",layer.userStyles[i],node);}}
return node;},"NamedStyle":function(name){var node=this.createElementNSPlus("sld:NamedStyle");this.writeNode("Name",name,node);return node;},"UserStyle":function(style){var node=this.createElementNSPlus("sld:UserStyle");if(style.name){this.writeNode("Name",style.name,node);}
if(style.title){this.writeNode("Title",style.title,node);}
if(style.description){this.writeNode("Abstract",style.description,node);}
if(style.isDefault){this.writeNode("IsDefault",style.isDefault,node);}
this.writeNode("FeatureTypeStyle",style,node);return node;},"IsDefault":function(bool){return this.createElementNSPlus("sld:IsDefault",{value:(bool)?"1":"0"});},"FeatureTypeStyle":function(style){var node=this.createElementNSPlus("sld:FeatureTypeStyle");for(var i=0,len=style.rules.length;i<len;++i){this.writeNode("Rule",style.rules[i],node);}
return node;},"Rule":function(rule){var node=this.createElementNSPlus("sld:Rule");if(rule.name){this.writeNode("Name",rule.name,node);}
if(rule.title){this.writeNode("Title",rule.title,node);}
if(rule.description){this.writeNode("Abstract",rule.description,node);}
if(rule.elseFilter){this.writeNode("ElseFilter",null,node);}else if(rule.filter){this.writeNode("ogc:Filter",rule.filter,node);}
if(rule.minScaleDenominator!=undefined){this.writeNode("MinScaleDenominator",rule.minScaleDenominator,node);}
if(rule.maxScaleDenominator!=undefined){this.writeNode("MaxScaleDenominator",rule.maxScaleDenominator,node);}
var types=OpenLayers.Style.SYMBOLIZER_PREFIXES;var type,symbolizer;for(var i=0,len=types.length;i<len;++i){type=types[i];symbolizer=rule.symbolizer[type];if(symbolizer){this.writeNode(type+"Symbolizer",symbolizer,node);}}
return node;},"ElseFilter":function(){return this.createElementNSPlus("sld:ElseFilter");},"MinScaleDenominator":function(scale){return this.createElementNSPlus("sld:MinScaleDenominator",{value:scale});},"MaxScaleDenominator":function(scale){return this.createElementNSPlus("sld:MaxScaleDenominator",{value:scale});},"LineSymbolizer":function(symbolizer){var node=this.createElementNSPlus("sld:LineSymbolizer");this.writeNode("Stroke",symbolizer,node);return node;},"Stroke":function(symbolizer){var node=this.createElementNSPlus("sld:Stroke");if(symbolizer.strokeColor!=undefined){this.writeNode("CssParameter",{symbolizer:symbolizer,key:"strokeColor"},node);}
if(symbolizer.strokeOpacity!=undefined){this.writeNode("CssParameter",{symbolizer:symbolizer,key:"strokeOpacity"},node);}
if(symbolizer.strokeWidth!=undefined){this.writeNode("CssParameter",{symbolizer:symbolizer,key:"strokeWidth"},node);}
return node;},"CssParameter":function(obj){return this.createElementNSPlus("sld:CssParameter",{attributes:{name:this.getCssProperty(obj.key)},value:obj.symbolizer[obj.key]});},"TextSymbolizer":function(symbolizer){var node=this.createElementNSPlus("sld:TextSymbolizer");if(symbolizer.label!=null){this.writeNode("Label",symbolizer.label,node);}
if(symbolizer.fontFamily!=null||symbolizer.fontSize!=null||symbolizer.fontWeight!=null||symbolizer.fontStyle!=null){this.writeNode("Font",symbolizer,node);}
if(symbolizer.anchorpointx!=null||symbolizer.anchorpointy!=null){this.writeNode("LabelPlacement",symbolizer,node);}
if(symbolizer.haloRadius!=null||symbolizer.haloColor!=null||symbolizer.haloOpacity!=null){this.writeNode("Halo",symbolizer,node);}
if(symbolizer.fillColor!=null||symbolizer.fillOpacity!=null){this.writeNode("Fill",symbolizer,node);}
return node;},"Font":function(symbolizer){var node=this.createElementNSPlus("sld:Font");if(symbolizer.fontFamily){this.writeNode("CssParameter",{symbolizer:symbolizer,key:"fontFamily"},node);}
if(symbolizer.fontSize){this.writeNode("CssParameter",{symbolizer:symbolizer,key:"fontSize"},node);}
if(symbolizer.fontWeight){this.writeNode("CssParameter",{symbolizer:symbolizer,key:"fontWeight"},node);}
if(symbolizer.fontStyle){this.writeNode("CssParameter",{symbolizer:symbolizer,key:"fontStyle"},node);}
return node;},"Label":function(label){var node=this.createElementNSPlus("sld:Label");var tokens=label.split("${");node.appendChild(this.createTextNode(tokens[0]));var item,last;for(var i=1,len=tokens.length;i<len;i++){item=tokens[i];last=item.indexOf("}");if(last>0){this.writeNode("ogc:PropertyName",{property:item.substring(0,last)},node);node.appendChild(this.createTextNode(item.substring(++last)));}else{node.appendChild(this.createTextNode("${"+item));}}
return node;},"LabelPlacement":function(symbolizer){var node=this.createElementNSPlus("sld:LabelPlacement");this.writeNode("PointPlacement",symbolizer,node);return node;},"PointPlacement":function(symbolizer){var node=this.createElementNSPlus("sld:PointPlacement");this.writeNode("AnchorPoint",symbolizer,node);return node;},"AnchorPoint":function(symbolizer){var node=this.createElementNSPlus("sld:AnchorPoint");if(symbolizer.anchorpointx){this.writeNode("AnchorPointX",symbolizer.anchorpointx,node);}
if(symbolizer.anchorpointy){this.writeNode("AnchorPointY",symbolizer.anchorpointy,node);}
return node;},"AnchorPointX":function(value){return this.createElementNSPlus("sld:AnchorPointX",{value:value});},"AnchorPointY":function(value){return this.createElementNSPlus("sld:AnchorPointY",{value:value});},"Halo":function(symbolizer){var node=this.createElementNSPlus("sld:Halo");if(symbolizer.haloRadius){this.writeNode("Radius",symbolizer.haloRadius,node);}
if(symbolizer.haloColor||symbolizer.haloOpacity){this.writeNode("Fill",{fillColor:symbolizer.haloColor,fillOpacity:symbolizer.haloOpacity},node);}
return node;},"Radius":function(value){return node=this.createElementNSPlus("sld:Radius",{value:value});},"PolygonSymbolizer":function(symbolizer){var node=this.createElementNSPlus("sld:PolygonSymbolizer");if(symbolizer.fillColor!=undefined||symbolizer.fillOpacity!=undefined){this.writeNode("Fill",symbolizer,node);}
if(symbolizer.strokeWidth!=undefined||symbolizer.strokeColor!=undefined||symbolizer.strokeOpacity!=undefined||symbolizer.strokeDashstyle!=undefined){this.writeNode("Stroke",symbolizer,node);}
return node;},"Fill":function(symbolizer){var node=this.createElementNSPlus("sld:Fill");if(symbolizer.fillColor){this.writeNode("CssParameter",{symbolizer:symbolizer,key:"fillColor"},node);}
if(symbolizer.fillOpacity!=null){this.writeNode("CssParameter",{symbolizer:symbolizer,key:"fillOpacity"},node);}
return node;},"PointSymbolizer":function(symbolizer){var node=this.createElementNSPlus("sld:PointSymbolizer");this.writeNode("Graphic",symbolizer,node);return node;},"Graphic":function(symbolizer){var node=this.createElementNSPlus("sld:Graphic");if(symbolizer.externalGraphic!=undefined){this.writeNode("ExternalGraphic",symbolizer,node);}else{this.writeNode("Mark",symbolizer,node);}
if(symbolizer.graphicOpacity!=undefined){this.writeNode("Opacity",symbolizer.graphicOpacity,node);}
if(symbolizer.pointRadius!=undefined){this.writeNode("Size",symbolizer.pointRadius*2,node);}
if(symbolizer.rotation!=undefined){this.writeNode("Rotation",symbolizer.rotation,node);}
return node;},"ExternalGraphic":function(symbolizer){var node=this.createElementNSPlus("sld:ExternalGraphic");this.writeNode("OnlineResource",symbolizer.externalGraphic,node);var format=symbolizer.graphicFormat||this.getGraphicFormat(symbolizer.externalGraphic);this.writeNode("Format",format,node);return node;},"Mark":function(symbolizer){var node=this.createElementNSPlus("sld:Mark");if(symbolizer.graphicName){this.writeNode("WellKnownName",symbolizer.graphicName,node);}
this.writeNode("Fill",symbolizer,node);this.writeNode("Stroke",symbolizer,node);return node;},"WellKnownName":function(name){return this.createElementNSPlus("sld:WellKnownName",{value:name});},"Opacity":function(value){return this.createElementNSPlus("sld:Opacity",{value:value});},"Size":function(value){return this.createElementNSPlus("sld:Size",{value:value});},"Rotation":function(value){return this.createElementNSPlus("sld:Rotation",{value:value});},"OnlineResource":function(href){return this.createElementNSPlus("sld:OnlineResource",{attributes:{"xlink:type":"simple","xlink:href":href}});},"Format":function(format){return this.createElementNSPlus("sld:Format",{value:format});}}},OpenLayers.Format.Filter.v1_0_0.prototype.writers);﻿
Ext.namespace('Municipia.Toolbar');Municipia.Toolbar=function(config){Ext.apply(this,config);Municipia.Toolbar.superclass.constructor.call(this);};Ext.extend(Municipia.Toolbar,Ext.Toolbar,{cls:'x-statusbar',busyIconCls:'x-status-busy',busyText:'Loading...',autoClear:5000,activeThreadId:0,controls:null,state:null,statusEl:null,configurable:false,buttons:[],defaultControl:null,initComponent:function(){if(this.statusAlign=='right'){this.cls+=' x-status-right';}
Municipia.Toolbar.superclass.initComponent.call(this);this.controls=[];this.autoWidth=true;this.autoHeight=false;this.height='20px';Ext.QuickTips.init();},addControl:function(control,options){control.visible=true;this.controls.push(control);this.map.addControl(control);var mb=new Ext.Toolbar.Button(options);mb.tooltip=control.title;mb.enableToggle=(control.type==OpenLayers.Control.TYPE_TOGGLE);if(control.isDefault){mb.pressed=true;this.defaultControl=control;}
mb.scope=this;mb.handler=function(){this.activateControl(control);};this.add(mb);this.buttons.push(mb);return mb;},getControlByClassName:function(className){if(this.controls){for(var i=0;i<this.controls.length;i++){if(this.controls[i].CLASS_NAME==className){return this.controls[i];}}}
return null;},getButtonForControl:function(control){if(this.controls){for(var i=0;i<this.controls.length;i++){if(this.controls[i]==control){return this.buttons[i];}}}
return null;},activate:function(){if(this.configurable){this.applyState(this.state);this.activateControl(this.defaultControl);var mb=new Ext.Toolbar.Button({'text':'+'});mb.menu=new Ext.menu.Menu();for(var i=0;i<this.controls.length;i++){mb.menu.add({'style':'height:25px','text':'<div style="position: relative; left: 25px; top: -15px;" class="'+this.buttons[i].iconCls+'"/>',checked:this.controls[i].visible,scope:{toolbar:this,button:this.buttons[i],control:this.controls[i]},checkHandler:function(item,checked){if(checked){this.control.visible=true;if(this.control==this.toolbar.defaultControl){this.toolbar.activateControl(this.control);}
this.button.show();}else{this.control.visible=false;this.control.deactivate();this.button.hide();}
this.toolbar.saveState();}});}
this.add(mb);}else if(this.defaultControl){this.activateControl(this.defaultControl);}},deactivate:function(){for(var i=0;i<this.controls.length;i++){this.controls[i].deactivate();if(this.controls[i].type!=OpenLayers.Control.TYPE_BUTTON){this.buttons[i].toggle(false);}}},applyState:function(state){if(!state){return false;}
this.state=state;var cs=state.controls;if(cs){for(var i=0,len=cs.length;i<len;i++){var s=cs[i];var c=this.getControlByClassName(s.id);if(c){c.visible=s.visible;if(!c.visible){this.buttons[i].hide();}}}}},getState:function(){var o={controls:[]};for(var i=0,c;i<this.controls.length;i++){c=this.controls[i];o.controls[i]={id:c.CLASS_NAME,visible:c.visible};}
return o;},activateControl:function(control){var button=this.getButtonForControl(control);if(!button){OpenLayers.Console.warn("Toolbar.activateControl : button was not found");return;}
if(control.type==OpenLayers.Control.TYPE_BUTTON){control.trigger();return;}
if(control.type==OpenLayers.Control.TYPE_TOGGLE){if(control.active){control.deactivate();button.toggle(false);}else{control.activate();button.toggle(true);}
return;}
for(var i=0;i<this.controls.length;i++){if(this.controls[i]==control&&control.visible){control.activate();button.toggle(true);}else{if(this.controls[i].type!=OpenLayers.Control.TYPE_TOGGLE){this.controls[i].deactivate();this.buttons[i].toggle(false);}}}},addLoadingStatus:function(){var right=this.statusAlign=='right',td=Ext.get(this.nextBlock());if(right){this.tr.appendChild(td.dom);}else{td.insertBefore(this.tr.firstChild);}
this.statusEl=td.createChild({cls:'x-status-text '+(this.iconCls||this.defaultIconCls||''),html:this.text||this.defaultText||''});this.statusEl.unselectable();this.spacerEl=td.insertSibling({tag:'td',style:'width:100%',cn:[{cls:'ytb-spacer'}]},right?'before':'after');},setStatus:function(o){o=o||{};if(typeof o=='string'){o={text:o};}
if(o.text!==undefined){this.setText(o.text);}
if(o.iconCls!==undefined){this.setIcon(o.iconCls);}
if(o.clear){var c=o.clear,wait=this.autoClear,defaults={useDefaults:true,anim:true};if(typeof c=='object'){c=Ext.applyIf(c,defaults);if(c.wait){wait=c.wait;}}else if(typeof c=='number'){wait=c;c=defaults;}else if(typeof c=='boolean'){c=defaults;}
c.threadId=this.activeThreadId;this.clearStatus.defer(wait,this,[c]);}
return this;},clearStatus:function(o){o=o||{};if(o.threadId&&o.threadId!==this.activeThreadId){return this;}
var text=o.useDefaults?this.defaultText:'',iconCls=o.useDefaults?this.defaultIconCls:'';if(this.statusEl!=null){if(o.anim){this.statusEl.fadeOut({remove:false,useDisplay:true,scope:this,callback:function(){this.setStatus({text:text,iconCls:iconCls});this.statusEl.show();}});}else{this.statusEl.hide();this.setStatus({text:text,iconCls:iconCls});this.statusEl.show();}}
return this;},setText:function(text){this.activeThreadId++;this.text=text||'';if(this.rendered&&this.statusEl!=null){this.statusEl.update(this.text);}
return this;},getText:function(){return this.text;},setIcon:function(cls){this.activeThreadId++;cls=cls||'';if(this.rendered&&this.statusEl!=null){if(this.currIconCls){this.statusEl.removeClass(this.currIconCls);this.currIconCls=null;}
if(cls.length>0){this.statusEl.addClass(cls);this.currIconCls=cls;}}else{this.currIconCls=cls;}
return this;},showBusy:function(o){if(typeof o=='string'){o={text:o};}
o=Ext.applyIf(o||{},{text:this.busyText,iconCls:this.busyIconCls});return this.setStatus(o);}});﻿
OpenLayers.Control.prototype.cursorClass=null;OpenLayers.Control.prototype.activate=function(){if(this.active){return false;}
if(this.handler){this.handler.activate();}
if(this.cursorClass){OpenLayers.Element.addClass(this.map.div,this.cursorClass);}
this.active=true;this.events.triggerEvent("activate");return true;};OpenLayers.Control.prototype.deactivate=function(){if(this.active){if(this.handler){this.handler.deactivate();}
if(this.cursorClass){OpenLayers.Element.removeClass(this.map.div,this.cursorClass);}
this.active=false;this.events.triggerEvent("deactivate");return true;}
return false;};Municipia.Control.LayerSwitcher=Municipia.Class(OpenLayers.Control,{initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,arguments);},destroy:function(){OpenLayers.Event.stopObservingElement(this.div);OpenLayers.Control.prototype.destroy.apply(this,arguments);},setMap:function(map){OpenLayers.Control.prototype.setMap.apply(this,arguments);this.map.events.on({"changelayer":this.redraw,scope:this});},draw:function(){OpenLayers.Control.prototype.draw.apply(this);this.loadContents();return this.div;},redraw:function(){},onChangeLayer:function(e){},onMoveEnd:function(e){},onRemoveLayer:function(e){},onRemoveLayerClicked:function(item){},removeGroup:function(group){},initPanel:function(){},initBaseNodes:function(){},initGroups:function(){},createGroup:function(name){},createGroupNode:function(group){return;},createLegendNodes:function(group){},groupSetVisibility:function(visibility){},groupGetVisibility:function(){return this.visibility;},groupAddLayer:function(layer){},groupRemoveLayer:function(layer){},getRenderToId:function(elem){},onShowLegendClicked:function(){},onRightClick:function(node,evt){},groupAddAttribute:function(key,value){},onCheckboxChange:function(node,checked){},onStartDrag:function(panel,node,e){},onEndDrag:function(panel,node,e){},groupLoadStart:function(e){},groupLoadEnd:function(e){},groupInRange:function(){},groupSetIcon:function(icon){},getContainerHeight:function(cont){},CLASS_NAME:"Municipia.Control.LayerSwitcher"});Municipia.Control.OverviewMap=Municipia.Class(Municipia.Control,{element:null,ovmap:null,size:new OpenLayers.Size(180,110),layers:null,minRectSize:15,minRectDisplayClass:"RectReplacement",minRatio:8,maxRatio:32,mapOptions:null,handlers:null,overviewPanel:null,initialize:function(options){this.layers=[];this.handlers={};Municipia.Control.prototype.initialize.apply(this,[options]);},destroy:function(){if(!this.mapDiv){return;}
this.handlers.click.destroy();this.mapDiv.removeChild(this.extentRectangle);this.extentRectangle=null;this.rectEvents.destroy();this.rectEvents=null;this.ovmap.destroy();this.ovmap=null;this.mapDiv=null;this.element=null;this.map.events.un({"moveend":this.update,"changebaselayer":this.baseLayerDraw,scope:this});OpenLayers.Control.prototype.destroy.apply(this,arguments);},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);if(!(this.layers.length>0)){if(this.map.baseLayer){var layer=this.map.baseLayer.clone();this.layers=[layer];}else{this.map.events.register("changebaselayer",this,this.baseLayerDraw);return this.div;}}
this.element=document.createElement('div');this.element.className=this.displayClass+'Element';this.element.style.display='none';this.mapDiv=document.createElement('div');this.mapDiv.style.width=this.size.w+'px';this.mapDiv.style.height=this.size.h+'px';this.mapDiv.style.position='relative';this.mapDiv.style.overflow='hidden';this.mapDiv.id=OpenLayers.Util.createUniqueID('overviewMap');this.extentRectangle=document.createElement('div');this.extentRectangle.style.position='absolute';this.extentRectangle.style.zIndex=1000;this.extentRectangle.className=this.displayClass+'ExtentRectangle';this.mapDiv.appendChild(this.extentRectangle);if(!this.outsideViewport){this.div.className+=" "+this.displayClass+'Container';}else{this.element.style.display='';}
if(this.map.getExtent()){this.update();}
this.initPanel();this.map.events.register('moveend',this,this.update);return this.div;},baseLayerDraw:function(){this.draw();this.map.events.unregister("changebaselayer",this,this.baseLayerDraw);},rectDrag:function(px){var deltaX=this.handlers.drag.last.x-px.x;var deltaY=this.handlers.drag.last.y-px.y;if(deltaX!=0||deltaY!=0){var rectTop=this.rectPxBounds.top;var rectLeft=this.rectPxBounds.left;var rectHeight=Math.abs(this.rectPxBounds.getHeight());var rectWidth=this.rectPxBounds.getWidth();var newTop=Math.max(0,(rectTop-deltaY));newTop=Math.min(newTop,this.ovmap.size.h-this.hComp-rectHeight);var newLeft=Math.max(0,(rectLeft-deltaX));newLeft=Math.min(newLeft,this.ovmap.size.w-this.wComp-rectWidth);this.setRectPxBounds(new OpenLayers.Bounds(newLeft,newTop+rectHeight,newLeft+rectWidth,newTop));}},mapDivClick:function(evt){var pxCenter=this.rectPxBounds.getCenterPixel();var deltaX=evt.xy.x-pxCenter.x;var deltaY=evt.xy.y-pxCenter.y;var top=this.rectPxBounds.top;var left=this.rectPxBounds.left;var height=Math.abs(this.rectPxBounds.getHeight());var width=this.rectPxBounds.getWidth();var newTop=Math.max(0,(top+deltaY));newTop=Math.min(newTop,this.ovmap.size.h-height);var newLeft=Math.max(0,(left+deltaX));newLeft=Math.min(newLeft,this.ovmap.size.w-width);this.setRectPxBounds(new OpenLayers.Bounds(newLeft,newTop+height,newLeft+width,newTop));this.updateMapToRect();},update:function(){if(this.ovmap==null){this.createMap();}
if(!this.isSuitableOverview()){this.updateOverview();}
this.updateRectToMap();},isSuitableOverview:function(){var mapExtent=this.map.getExtent();var maxExtent=this.map.maxExtent;var testExtent=new OpenLayers.Bounds(Math.max(mapExtent.left,maxExtent.left),Math.max(mapExtent.bottom,maxExtent.bottom),Math.min(mapExtent.right,maxExtent.right),Math.min(mapExtent.top,maxExtent.top));var resRatio=this.ovmap.getResolution()/this.map.getResolution();return((resRatio>this.minRatio)&&(resRatio<=this.maxRatio)&&(this.ovmap.getExtent().containsBounds(testExtent)));},updateOverview:function(){var mapRes=this.map.getResolution();var targetRes=this.ovmap.getResolution();var resRatio=targetRes/mapRes;if(resRatio>this.maxRatio){targetRes=this.minRatio*mapRes;}else if(resRatio<=this.minRatio){targetRes=this.maxRatio*mapRes;}
this.ovmap.setCenter(this.map.center,this.ovmap.getZoomForResolution(targetRes));this.updateRectToMap();},createMap:function(){var options=OpenLayers.Util.extend({controls:[],maxResolution:'auto',fallThrough:false},this.mapOptions);this.ovmap=new OpenLayers.Map(this.mapDiv,options);OpenLayers.Event.stopObserving(window,'unload',this.ovmap.unloadDestroy);this.ovmap.addLayers(this.layers);this.ovmap.zoomToMaxExtent();this.wComp=parseInt(OpenLayers.Element.getStyle(this.extentRectangle,'border-left-width'))+
parseInt(OpenLayers.Element.getStyle(this.extentRectangle,'border-right-width'));this.wComp=(this.wComp)?this.wComp:2;this.hComp=parseInt(OpenLayers.Element.getStyle(this.extentRectangle,'border-top-width'))+
parseInt(OpenLayers.Element.getStyle(this.extentRectangle,'border-bottom-width'));this.hComp=(this.hComp)?this.hComp:2;this.handlers.drag=new OpenLayers.Handler.Drag(this,{move:this.rectDrag,done:this.updateMapToRect},{map:this.ovmap});this.handlers.click=new OpenLayers.Handler.Click(this,{"click":this.mapDivClick},{"single":true,"double":false,"stopSingle":true,"stopDouble":true,"pixelTolerance":1,map:this.ovmap});this.handlers.click.activate();this.rectEvents=new OpenLayers.Events(this,this.extentRectangle,null,true);this.rectEvents.register("mouseover",this,function(e){if(!this.handlers.drag.active&&!this.map.dragging){this.handlers.drag.activate();}});this.rectEvents.register("mouseout",this,function(e){if(!this.handlers.drag.dragging){this.handlers.drag.deactivate();}});},updateRectToMap:function(){if(this.map.getUnits()!='degrees'){if(this.ovmap.getProjection()&&(this.map.getProjection()!=this.ovmap.getProjection())){alert(OpenLayers.i18n("sameProjection"));}}
var pxBounds=this.getRectBoundsFromMapBounds(this.map.getExtent());if(pxBounds){this.setRectPxBounds(pxBounds);}},updateMapToRect:function(){var lonLatBounds=this.getMapBoundsFromRectBounds(this.rectPxBounds);this.map.panTo(lonLatBounds.getCenterLonLat());},setRectPxBounds:function(pxBounds){var top=Math.max(pxBounds.top,0);var left=Math.max(pxBounds.left,0);var bottom=Math.min(pxBounds.top+Math.abs(pxBounds.getHeight()),this.ovmap.size.h-this.hComp);var right=Math.min(pxBounds.left+pxBounds.getWidth(),this.ovmap.size.w-this.wComp);var width=Math.max(right-left,0);var height=Math.max(bottom-top,0);if(width<this.minRectSize||height<this.minRectSize){this.extentRectangle.className=this.displayClass+
this.minRectDisplayClass;var rLeft=left+(width/2)-(this.minRectSize/2);var rTop=top+(height/2)-(this.minRectSize/2);this.extentRectangle.style.top=Math.round(rTop)+'px';this.extentRectangle.style.left=Math.round(rLeft)+'px';this.extentRectangle.style.height=this.minRectSize+'px';this.extentRectangle.style.width=this.minRectSize+'px';}else{this.extentRectangle.className=this.displayClass+'ExtentRectangle';this.extentRectangle.style.top=Math.round(top)+'px';this.extentRectangle.style.left=Math.round(left)+'px';this.extentRectangle.style.height=Math.round(height)+'px';this.extentRectangle.style.width=Math.round(width)+'px';}
this.rectPxBounds=new OpenLayers.Bounds(Math.round(left),Math.round(bottom),Math.round(right),Math.round(top));},getRectBoundsFromMapBounds:function(lonLatBounds){var leftBottomLonLat=new OpenLayers.LonLat(lonLatBounds.left,lonLatBounds.bottom);var rightTopLonLat=new OpenLayers.LonLat(lonLatBounds.right,lonLatBounds.top);var leftBottomPx=this.getOverviewPxFromLonLat(leftBottomLonLat);var rightTopPx=this.getOverviewPxFromLonLat(rightTopLonLat);var bounds=null;if(leftBottomPx&&rightTopPx){bounds=new OpenLayers.Bounds(leftBottomPx.x,leftBottomPx.y,rightTopPx.x,rightTopPx.y);}
return bounds;},getMapBoundsFromRectBounds:function(pxBounds){var leftBottomPx=new OpenLayers.Pixel(pxBounds.left,pxBounds.bottom);var rightTopPx=new OpenLayers.Pixel(pxBounds.right,pxBounds.top);var leftBottomLonLat=this.getLonLatFromOverviewPx(leftBottomPx);var rightTopLonLat=this.getLonLatFromOverviewPx(rightTopPx);return new OpenLayers.Bounds(leftBottomLonLat.lon,leftBottomLonLat.lat,rightTopLonLat.lon,rightTopLonLat.lat);},getLonLatFromOverviewPx:function(overviewMapPx){var size=this.ovmap.size;var res=this.ovmap.getResolution();var center=this.ovmap.getExtent().getCenterLonLat();var delta_x=overviewMapPx.x-(size.w/2);var delta_y=overviewMapPx.y-(size.h/2);return new OpenLayers.LonLat(center.lon+delta_x*res,center.lat-delta_y*res);},getOverviewPxFromLonLat:function(lonlat){var res=this.ovmap.getResolution();var extent=this.ovmap.getExtent();var px=null;if(extent){px=new OpenLayers.Pixel(Math.round(1/res*(lonlat.lon-extent.left)),Math.round(1/res*(extent.top-lonlat.lat)));}
return px;},initPanel:function(){this.overviewPanel=new Ext.Panel({layout:'fit',ls:this,region:'center',renderTo:this.getRenderToId(this.container)});this.overviewPanel.add(this.mapDiv);if(!this.container){this.container=new Ext.Window({title:OpenLayers.i18n("TitleOverviewMap"),layout:"fit",minimizable:false,listeners:{beforehide:function(){overviewMapHide(this);}},y:100,x:70,closable:true,closeAction:'hide',collapsible:false,width:this.size.w+25,height:this.size.h+30,resizable:false,header:false,focus:Ext.emptyFn,items:[this.overviewPanel]});this.container.show();}
else{if(typeof(this.container)=="string"){this.container=Ext.get(this.container);}
else{this.container=this.container;}
this.overviewPanel.setHeight(this.getContainerHeight(this.container));this.container.on("resize",function(panel,adjWidth,adjHeight){this.ls.overviewPanel.setHeight(adjHeight-45);this.ls.overviewPanel.setWidth(adjWidth-1);},{ls:this});}},getRenderToId:function(elem){var id=null;switch(typeof(elem)){case"string":id=elem;break;case typeof({}):if(elem!=null){id=elem.body?elem.body.id:elem.id;}
break;default:id=null;}
return id;},CLASS_NAME:'Municipia.Control.OverviewMap'});Municipia.Popup.Anchored=Municipia.Class(Municipia.Popup,{relativePosition:null,anchor:null,initialize:function(id,lonlat,size,contentHTML,anchor,closeBox,closeBoxCallback){var newArguments=new Array(id,lonlat,size,contentHTML,closeBox,closeBoxCallback);Municipia.Popup.prototype.initialize.apply(this,newArguments);this.anchor=(anchor!=null)?anchor:{size:new Municipia.Size(0,0),offset:new Municipia.Pixel(0,0)};},destroy:function(){this.anchor=null;this.relativePosition=null;Municipia.Popup.prototype.destroy.apply(this,arguments);},show:function(){this.updatePosition();Municipia.Popup.prototype.show.apply(this,arguments);},moveTo:function(px){var oldRelativePosition=this.relativePosition;this.relativePosition=this.calculateRelativePosition(px);var newPx=this.calculateNewPx(px);var newArguments=new Array(newPx);Municipia.Popup.prototype.moveTo.apply(this,newArguments);if(this.relativePosition!=oldRelativePosition){this.updateRelativePosition();}},setSize:function(size){Municipia.Popup.prototype.setSize.apply(this,arguments);if((this.lonlat)&&(this.map)){var px=this.map.getLayerPxFromLonLat(this.lonlat);this.moveTo(px);}},calculateRelativePosition:function(px){var lonlat=this.map.getLonLatFromLayerPx(px);var extent=this.map.getExtent();var quadrant=extent.determineQuadrant(lonlat);return Municipia.Bounds.oppositeQuadrant(quadrant);},updateRelativePosition:function(){},calculateNewPx:function(px){var newPx=px.offset(this.anchor.offset);var top=(this.relativePosition.charAt(0)=='t');newPx.y+=(top)?-this.size.h:this.anchor.size.h;var left=(this.relativePosition.charAt(1)=='l');newPx.x+=(left)?-this.size.w:this.anchor.size.w;return newPx;},CLASS_NAME:"Municipia.Popup.Anchored"});Municipia.Popup.AnchoredBubble=Municipia.Class(Municipia.Popup.Anchored,{rounded:false,initialize:function(id,lonlat,size,contentHTML,anchor,closeBox,closeBoxCallback){this.padding=new Municipia.Bounds(0,Municipia.Popup.AnchoredBubble.CORNER_SIZE,0,Municipia.Popup.AnchoredBubble.CORNER_SIZE);Municipia.Popup.Anchored.prototype.initialize.apply(this,arguments);},draw:function(px){Municipia.Popup.Anchored.prototype.draw.apply(this,arguments);this.setContentHTML();this.setBackgroundColor();this.setOpacity();return this.div;},updateRelativePosition:function(){this.setRicoCorners();},setSize:function(size){Municipia.Popup.Anchored.prototype.setSize.apply(this,arguments);this.setRicoCorners();},setBackgroundColor:function(color){if(color!=undefined){this.backgroundColor=color;}
if(this.div!=null){if(this.contentDiv!=null){this.div.style.background="transparent";OpenLayers.Rico.Corner.changeColor(this.groupDiv,this.backgroundColor);}}},setOpacity:function(opacity){Municipia.Popup.Anchored.prototype.setOpacity.call(this,opacity);if(this.div!=null){if(this.groupDiv!=null){OpenLayers.Rico.Corner.changeOpacity(this.groupDiv,this.opacity);}}},setBorder:function(border){this.border=0;},setRicoCorners:function(){var corners=this.getCornersToRound(this.relativePosition);var options={corners:corners,color:this.backgroundColor,bgColor:"transparent",blend:false};if(!this.rounded){OpenLayers.Rico.Corner.round(this.div,options);this.rounded=true;}else{OpenLayers.Rico.Corner.reRound(this.groupDiv,options);this.setBackgroundColor();this.setOpacity();}},getCornersToRound:function(){var corners=['tl','tr','bl','br'];var corner=Municipia.Bounds.oppositeQuadrant(this.relativePosition);Municipia.Util.removeItem(corners,corner);return corners.join(" ");},CLASS_NAME:"Municipia.Popup.AnchoredBubble"});Municipia.Popup.AnchoredBubble.CORNER_SIZE=5;Municipia.Popup.Center=Municipia.Class(Municipia.Popup.Anchored,{calculateNewPx:function(px){var newPx=px.offset(this.anchor.offset);var size=this.size||this.contentSize;newPx.y+=-size.h;newPx.x+=-size.w/2;return newPx;},CLASS_NAME:"Municipia.Popup.Center"});Municipia.Popup.POI=Municipia.Class(Municipia.Popup,{relativePosition:null,anchor:null,initialize:function(id,lonlat,size,contentHTML,anchor,closeBox,closeBoxCallback){var newArguments=new Array(id,lonlat,size,contentHTML,closeBox,closeBoxCallback);Municipia.Popup.prototype.initialize.apply(this,newArguments);this.anchor=(anchor!=null)?anchor:{size:new Municipia.Size(0,0),offset:new Municipia.Pixel(0,0)};},destroy:function(){this.anchor=null;this.relativePosition=null;Municipia.Popup.prototype.destroy.apply(this,arguments);},draw:function(px){Municipia.Popup.prototype.draw.apply(this,arguments);this.setContentHTML();this.setOpacity();return this.div;},show:function(){this.updatePosition();Municipia.Popup.prototype.show.apply(this,arguments);},moveTo:function(px){var oldRelativePosition=this.relativePosition;this.relativePosition=this.calculateRelativePosition(px);var newPx=this.calculateNewPx(px);var newArguments=new Array(newPx);Municipia.Popup.prototype.moveTo.apply(this,newArguments);if(this.relativePosition!=oldRelativePosition){this.updateRelativePosition();}},setSize:function(size){this.size=size;var contentSize=this.size.clone();var contentDivPadding=this.getContentDivPadding();var wPadding=contentDivPadding.left+contentDivPadding.right;var hPadding=contentDivPadding.top+contentDivPadding.bottom;this.fixPadding();wPadding+=this.padding.left+this.padding.right;hPadding+=this.padding.top+this.padding.bottom;this.size.w+=wPadding;this.size.h+=hPadding;if(Municipia.Util.getBrowserName()=="msie"){contentSize.w+=contentDivPadding.left+contentDivPadding.right;contentSize.h+=contentDivPadding.bottom+contentDivPadding.top;}
if(this.div!=null){this.div.style.width=this.size.w+"px";this.div.style.height=this.size.h+"px";}
if(this.contentDiv!=null){this.contentDiv.style.width=contentSize.w+"px";this.contentDiv.style.height=contentSize.h+"px";}
if((this.lonlat)&&(this.map)){var px=this.map.getLayerPxFromLonLat(this.lonlat);this.moveTo(px);}},setContentHTML:function(contentHTML){if(contentHTML!=null){this.contentHTML=contentHTML;}
if(this.autoSize){var realSize=OpenLayers.Util.getRenderedDimensions(this.contentHTML);var safeSize=this.getSafeContentSize(realSize);var newSize=null;if(safeSize.equals(realSize)){newSize=realSize;}else{var fixedSize=new OpenLayers.Size();fixedSize.w=(safeSize.w<realSize.w)?safeSize.w:null;fixedSize.h=(safeSize.h<realSize.h)?safeSize.h:null;if(fixedSize.w&&fixedSize.h){newSize=safeSize;}else{var clippedSize=OpenLayers.Util.getRenderedDimensions(this.contentHTML,fixedSize);var currentOverflow=OpenLayers.Element.getStyle(this.contentDiv,"overflow");if((currentOverflow!="hidden")&&(clippedSize.equals(safeSize))){var scrollBar=OpenLayers.Util.getScrollbarWidth();if(fixedSize.w){clippedSize.h+=scrollBar;}else{clippedSize.w+=scrollBar;}}
newSize=this.getSafeContentSize(clippedSize);}}
this.setSize(newSize);}
if(this.contentDiv!=null){this.contentDiv.innerHTML=this.contentHTML;}},addCloseBox:function(callback){this.closeDiv=Municipia.Util.createDiv(this.id+"_close",null,new Municipia.Size(17,17));this.closeDiv.className="olPopupCloseBox";var contentDivPadding=this.getContentDivPadding();this.closeDiv.style.right=(contentDivPadding.right+10)+"px";this.closeDiv.style.top=(contentDivPadding.top+10)+"px";this.groupDiv.appendChild(this.closeDiv);var closePopup=callback||function(e){this.hide();Municipia.Event.stop(e);};Municipia.Event.observe(this.closeDiv,"click",Municipia.Function.bindAsEventListener(closePopup,this));},calculateRelativePosition:function(px){var lonlat=this.map.getLonLatFromLayerPx(px);var extent=this.map.getExtent();var quadrant=extent.determineQuadrant(lonlat);return Municipia.Bounds.oppositeQuadrant(quadrant);},updateRelativePosition:function(){},calculateNewPx:function(px){var newPx=px.offset(this.anchor.offset);var top=(this.relativePosition.charAt(0)=='t');newPx.y+=(top)?-this.size.h:this.anchor.size.h;var left=(this.relativePosition.charAt(1)=='l');newPx.x+=(left)?-this.size.w:this.anchor.size.w;return newPx;},CLASS_NAME:"Municipia.Popup.POI"});Municipia.Popup.Right=Municipia.Class(Municipia.Popup.Anchored,{displayClass:"",contentDisplayClass:"",setContentHTML:function(contentHTML){if(contentHTML!=null){this.contentHTML=contentHTML;}
if((this.contentDiv!=null)&&(this.contentHTML!=null)&&(this.contentHTML!=this.contentDiv.innerHTML)){this.contentDiv.innerHTML=this.contentHTML;this.div.innerHTML=this.contentHTML;if(this.autoSize){this.registerImageListeners();this.updateSize();}}},calculateNewPx:function(px){var newPx=px.offset(this.anchor.offset);var size=this.size||this.contentSize;newPx.y+=-size.h;newPx.x+=0;return newPx;},CLASS_NAME:"OpenLayers.Popup.Right"});Municipia.Popup.Top=Municipia.Class(Municipia.Popup.Anchored,{calculateNewPx:function(px){var newPx=px.offset(this.anchor.offset);var size=this.size||this.contentSize;newPx.y+=-(size.h+4);newPx.x+=-size.w/2;return newPx;},CLASS_NAME:"Municipia.Popup.Top"});Municipia.Feature=Municipia.Class({layer:null,id:null,lonlat:null,data:null,marker:null,popupClass:Municipia.Popup.AnchoredBubble,popup:null,initialize:function(layer,lonlat,data){this.layer=layer;this.lonlat=lonlat;this.data=(data!=null)?data:{};this.id=Municipia.Util.createUniqueID(this.CLASS_NAME+"_");},destroy:function(){if((this.layer!=null)&&(this.layer.map!=null)){if(this.popup!=null){this.layer.map.removePopup(this.popup);}}
this.layer=null;this.id=null;this.lonlat=null;this.data=null;if(this.marker!=null){this.destroyMarker(this.marker);this.marker=null;}
if(this.popup!=null){this.destroyPopup(this.popup);this.popup=null;}},onScreen:function(){var onScreen=false;if((this.layer!=null)&&(this.layer.map!=null)){var screenBounds=this.layer.map.getExtent();onScreen=screenBounds.containsLonLat(this.lonlat);}
return onScreen;},createMarker:function(){if(this.lonlat!=null){this.marker=new Municipia.Marker(this.lonlat,this.data.icon);}
return this.marker;},destroyMarker:function(){this.marker.destroy();},createPopup:function(closeBox){if(this.lonlat!=null){var id=this.id+"_popup";var anchor=(this.marker)?this.marker.icon:null;if(!this.popup){this.popup=new this.popupClass(id,this.lonlat,this.data.popupSize,this.data.popupContentHTML,anchor,closeBox);}
if(this.data.overflow!=null){this.popup.contentDiv.style.overflow=this.data.overflow;}
this.popup.feature=this;}
return this.popup;},destroyPopup:function(){if(this.popup){this.popup.feature=null;this.popup.destroy();this.popup=null;}},CLASS_NAME:"Municipia.Feature"});Municipia.Feature.WFS=Municipia.Class(Municipia.Feature,{overClass:null,initialize:function(layer,xmlNode){var newArguments=arguments;var data=this.processXMLNode(xmlNode);if(layer.options.iconUrl){var size=new Municipia.Size(20,20);var offset=new Municipia.Pixel(-(size.w/2),-(size.h/2));var icon=new Municipia.Icon(layer.options.iconUrl,size,offset);data.icon=icon;}
this.overClass="featureMouseOver";this.closeBox=true;this.autoSize=true;this.popupClass=OpenLayers.Popup.AnchoredBubble;var nome=data.nome==null?'':data.nome;var morada=data.morada==null?'':data.morada;var telefone=data.telefone==null?'':data.telefone;var codPostal=data.codPostal==null?'':data.codPostal;var tipoId=data.tipoId==null?'':data.tipoId;var globalId='"'+data.globalId+'"';data.popupContentHTML="<div class='tituloMarkerInfo'><p>"+nome+"</p></div><div class='bodyMarkerInfo'><p>"+morada+"</p></br><p>"+telefone+"</p></br><p>"+codPostal+"</p></div><div class='detalhesMarkerInfo'>Consultar <a href='#' onclick='javascript:openJanelaDetalhe("+tipoId+","+globalId+")' >detalhes</a></div>";data.overflow="hidden";newArguments=new Array(layer,data.lonlat,data);Municipia.Feature.prototype.initialize.apply(this,newArguments);this.createMarker();this.layer.addMarker(this.marker);this.marker.events.register("mousedown",this,this.markerClick);},destroy:function(){if(this.marker!=null){this.layer.removeMarker(this.marker);}
Municipia.Feature.prototype.destroy.apply(this,arguments);},processXMLNode:function(xmlNode){var point=Municipia.Ajax.getElementsByTagNameNS(xmlNode,"http://www.opengis.net/gml","gml","Point");var text=Municipia.Util.getXmlNodeValue(Municipia.Ajax.getElementsByTagNameNS(point[0],"http://www.opengis.net/gml","gml","coordinates")[0]);var floats=text.split(",");var nome="";var nomeNode=Municipia.Ajax.getElementsByTagNameNS(xmlNode,app.namespaceGeoServerUrl,app.namespaceGeoServer,"NOME");if(nomeNode.length==0)
nomeNode=Municipia.Ajax.getElementsByTagNameNS(xmlNode,app.namespaceGeoServerUrl,app.namespaceGeoServer,"DESIGNACAO");if(nomeNode.length>0)
nome=(Municipia.Util.getXmlNodeValue(nomeNode[0])==null||Municipia.Util.getXmlNodeValue(nomeNode[0])=="undefined")?"":Municipia.Util.getXmlNodeValue(nomeNode[0]);var moradaNode=Municipia.Ajax.getElementsByTagNameNS(xmlNode,app.namespaceGeoServerUrl,app.namespaceGeoServer,"MORADA");var morada="";if(moradaNode.length>0)
morada=(Municipia.Util.getXmlNodeValue(moradaNode[0])==null||Municipia.Util.getXmlNodeValue(moradaNode[0])=="undefined")?"":Municipia.Util.getXmlNodeValue(moradaNode[0]);var telefoneNode=Municipia.Ajax.getElementsByTagNameNS(xmlNode,app.namespaceGeoServerUrl,app.namespaceGeoServer,"TELEFONE");var telefone="";if(telefoneNode.length>0)
telefone=(Municipia.Util.getXmlNodeValue(telefoneNode[0])==null||Municipia.Util.getXmlNodeValue(telefoneNode[0])=="undefined")?"":Municipia.Util.getXmlNodeValue(telefoneNode[0]);var codPostalNode=Municipia.Ajax.getElementsByTagNameNS(xmlNode,app.namespaceGeoServerUrl,app.namespaceGeoServer,"COD_POSTAL");var locNode=Municipia.Ajax.getElementsByTagNameNS(xmlNode,app.namespaceGeoServerUrl,app.namespaceGeoServer,"LOC_POSTAL");var codPostal="";if(codPostalNode.length>0&&locNode.length>0){var cod=(Municipia.Util.getXmlNodeValue(codPostalNode[0])==null||Municipia.Util.getXmlNodeValue(codPostalNode[0])=="undefined")?"":Municipia.Util.getXmlNodeValue(codPostalNode[0]);var loc=(Municipia.Util.getXmlNodeValue(locNode[0])==null||Municipia.Util.getXmlNodeValue(locNode[0])=="undefined")?"":Municipia.Util.getXmlNodeValue(locNode[0]);codPostal=cod+" "+loc;}
var globalIdNode=Municipia.Ajax.getElementsByTagNameNS(xmlNode,app.namespaceGeoServerUrl,app.namespaceGeoServer,"GLOBALID");var globalId="";if(globalIdNode.length>0)
globalId=(Municipia.Util.getXmlNodeValue(globalIdNode[0])==null||Municipia.Util.getXmlNodeValue(globalIdNode[0])=="undefined")?"":Municipia.Util.getXmlNodeValue(globalIdNode[0]);var tipoIdNode=Municipia.Ajax.getElementsByTagNameNS(xmlNode,app.namespaceGeoServerUrl,app.namespaceGeoServer,"TIPOID");var tipoId="";if(tipoIdNode.length>0)
tipoId=(Municipia.Util.getXmlNodeValue(tipoIdNode[0])==null||Municipia.Util.getXmlNodeValue(tipoIdNode[0])=="undefined")?"":Municipia.Util.getXmlNodeValue(tipoIdNode[0]);return{lonlat:new Municipia.LonLat(parseFloat(floats[0]),parseFloat(floats[1])),id:null,nome:nome,morada:morada,telefone:telefone,codPostal:codPostal,globalId:globalId,tipoId:tipoId};},markerClick:function(evt){if(this.layer.map.currentPopup&&this.layer.map.currentPopup!=null&&this.layer.map.popups.length>0&&this.layer.map.currentPopup.visible()&&(this.popup==null||this.popup!=this.layer.map.currentPopup)){this.layer.map.currentPopup.hide();}
if(this.popup==null){this.popup=this.createPopup(this.closeBox);this.popup.setBackgroundColor('#eff6fb');if(this.popup.closeDiv!=null)
this.popup.closeDiv.className="olPopupDetalheCloseBox";this.layer.map.addPopup(this.popup);this.popup.show();}else{this.popup.toggle();}
this.layer.map.currentPopup=this.popup;Municipia.Event.stop(evt);},markerMouseOver:function(evt){if(this.overClass!=null){var control=this.layer.map.controlActive;if(control){OpenLayers.Element.removeClass(this.layer.map.div,control.cursorClass);OpenLayers.Element.addClass(this.layer.map.div,this.overClass);}}
Municipia.Event.stop(evt);},markerMouseOut:function(evt){if(this.overClass){var control=this.layer.map.controlActive;if(control){OpenLayers.Element.removeClass(this.layer.map.div,this.overClass);OpenLayers.Element.addClass(this.layer.map.div,control.cursorClass);}}
Municipia.Event.stop(evt);},CLASS_NAME:"Municipia.Feature.WFS"});Ext.namespace('Municipia.controls');Municipia.controls.MapComponent=function(config){Ext.apply(this,config);this.contentEl=this.map.div;var content=Ext.get(this.contentEl);content.setStyle('width','100%');content.setStyle('height','100%');Municipia.controls.MapComponent.superclass.constructor.call(this);};Ext.extend(Municipia.controls.MapComponent,Ext.Panel,{map:null,initComponent:function(){Municipia.controls.MapComponent.superclass.initComponent.apply(this,arguments);this.on("bodyresize",this.map.updateSize,this.map);}});Ext.reg('mapcomponent',Municipia.controls.MapComponent);Proj4js={defaultDatum:'WGS84',proxyScript:null,defsLookupService:'http://spatialreference.org/ref',libPath:'../lib/',transform:function(source,dest,point){if(!source.readyToUse||!dest.readyToUse){this.reportError("Proj4js initialization for "+source.srsCode+" not yet complete");return;}
if(point.transformed){this.log("point already transformed");return;}
if((source.srsProjNumber=="900913"&&dest.datumCode!="WGS84")||(dest.srsProjNumber=="900913"&&source.datumCode!="WGS84")){var wgs84=Proj4js.WGS84;this.transform(source,wgs84,point);point.transformed=false;source=wgs84;}
if(source.projName=="longlat"){point.x*=Proj4js.common.D2R;point.y*=Proj4js.common.D2R;}else{if(source.to_meter){point.x*=source.to_meter;point.y*=source.to_meter;}
source.inverse(point);}
if(source.from_greenwich){point.x+=source.from_greenwich;}
point=this.datum_transform(source.datum,dest.datum,point);if(dest.from_greenwich){point.x-=dest.from_greenwich;}
if(dest.projName=="longlat"){point.x*=Proj4js.common.R2D;point.y*=Proj4js.common.R2D;}else{dest.forward(point);if(dest.to_meter){point.x/=dest.to_meter;point.y/=dest.to_meter;}}
point.transformed=true;return point;},datum_transform:function(source,dest,point){if(source.compare_datums(dest)){return point;}
if(source.datum_type==Proj4js.common.PJD_NODATUM||dest.datum_type==Proj4js.common.PJD_NODATUM){return point;}
if(source.datum_type==Proj4js.common.PJD_GRIDSHIFT)
{alert("ERROR: Grid shift transformations are not implemented yet.");}
if(dest.datum_type==Proj4js.common.PJD_GRIDSHIFT)
{alert("ERROR: Grid shift transformations are not implemented yet.");}
if(source.es!=dest.es||source.a!=dest.a||source.datum_type==Proj4js.common.PJD_3PARAM||source.datum_type==Proj4js.common.PJD_7PARAM||dest.datum_type==Proj4js.common.PJD_3PARAM||dest.datum_type==Proj4js.common.PJD_7PARAM)
{source.geodetic_to_geocentric(point);if(source.datum_type==Proj4js.common.PJD_3PARAM||source.datum_type==Proj4js.common.PJD_7PARAM){source.geocentric_to_wgs84(point);}
if(dest.datum_type==Proj4js.common.PJD_3PARAM||dest.datum_type==Proj4js.common.PJD_7PARAM){dest.geocentric_from_wgs84(point);}
dest.geocentric_to_geodetic(point);}
if(dest.datum_type==Proj4js.common.PJD_GRIDSHIFT)
{alert("ERROR: Grid shift transformations are not implemented yet.");}
return point;},reportError:function(msg){},log:function(msg){},loadProjDefinition:function(proj){if(this.defs[proj.srsCode])return this.defs[proj.srsCode];var options={method:'get',asynchronous:false,onSuccess:this.defsLoadedFromDisk.bind(this,proj.srsCode)}
var url=this.libPath+'defs/'+proj.srsAuth.toUpperCase()+proj.srsProjNumber+'.js';new OpenLayers.Ajax.Request(url,options);if(this.defs[proj.srsCode])return this.defs[proj.srsCode];if(this.proxyScript){var url=this.proxyScript+this.defsLookupService+'/'+proj.srsAuth+'/'+proj.srsProjNumber+'/proj4';options.onSuccess=this.defsLoadedFromService.bind(this,proj.srsCode)
options.onFailure=this.defsFailed.bind(this,proj.srsCode);new OpenLayers.Ajax.Request(url,options);}
return this.defs[proj.srsCode];},defsLoadedFromDisk:function(srsCode,transport){eval(transport.responseText);},defsLoadedFromService:function(srsCode,transport){this.defs[srsCode]=transport.responseText;Proj4js.defs[srsCode]=transport.responseText},defsFailed:function(srsCode){this.reportError('failed to load projection definition for: '+srsCode);OpenLayers.Util.extend(this.defs[srsCode],this.defs['WGS84']);},loadProjCode:function(projName){if(this.Proj[projName])return;var options={method:'get',asynchronous:false,onSuccess:this.loadProjCodeSuccess.bind(this,projName),onFailure:this.loadProjCodeFailure.bind(this,projName)};var url=this.libPath+'projCode/'+projName+'.js';new OpenLayers.Ajax.Request(url,options);},loadProjCodeSuccess:function(projName,transport){eval(transport.responseText);if(this.Proj[projName].dependsOn){this.loadProjCode(this.Proj[projName].dependsOn);}},loadProjCodeFailure:function(projName){Proj4js.reportError("failed to find projection file for: "+projName);}};Proj4js.Proj=OpenLayers.Class({readyToUse:false,title:null,projName:null,units:null,datum:null,initialize:function(srsCode){this.srsCode=srsCode.toUpperCase();if(this.srsCode.indexOf("EPSG")==0){this.srsCode=this.srsCode;this.srsAuth='epsg';this.srsProjNumber=this.srsCode.substring(5);}else{this.srsAuth='';this.srsProjNumber=this.srsCode;}
var defs=Proj4js.loadProjDefinition(this);if(defs){this.parseDefs(defs);Proj4js.loadProjCode(this.projName);this.callInit();}},callInit:function(){Proj4js.log('projection script loaded for:'+this.projName);OpenLayers.Util.extend(this,Proj4js.Proj[this.projName]);this.init();this.mapXYToLonLat=this.inverse;this.lonLatToMapXY=this.forward;this.readyToUse=true;},parseDefs:function(proj4opts){this.defData=proj4opts;var paramName,paramVal;var paramArray=this.defData.split("+");for(var prop=0;prop<paramArray.length;prop++){var property=paramArray[prop].split("=");paramName=property[0].toLowerCase();paramVal=property[1];switch(paramName.replace(/\s/gi,"")){case"":break;case"title":this.title=paramVal;break;case"proj":this.projName=paramVal.replace(/\s/gi,"");break;case"units":this.units=paramVal.replace(/\s/gi,"");break;case"datum":this.datumCode=paramVal.replace(/\s/gi,"");break;case"nadgrids":this.nagrids=paramVal.replace(/\s/gi,"");break;case"ellps":this.ellps=paramVal.replace(/\s/gi,"");break;case"a":this.a=parseFloat(paramVal);break;case"b":this.b=parseFloat(paramVal);break;case"lat_0":this.lat0=paramVal*Proj4js.common.D2R;break;case"lat_1":this.lat1=paramVal*Proj4js.common.D2R;break;case"lat_2":this.lat2=paramVal*Proj4js.common.D2R;break;case"lat_ts":this.lat_ts=paramVal*Proj4js.common.D2R;break;case"lon_0":this.long0=paramVal*Proj4js.common.D2R;break;case"x_0":this.x0=parseFloat(paramVal);break;case"y_0":this.y0=parseFloat(paramVal);break;case"k_0":this.k0=parseFloat(paramVal);break;case"k":this.k0=parseFloat(paramVal);break;case"R_A":this.R=parseFloat(paramVal);break;case"zone":this.zone=parseInt(paramVal);break;case"south":this.utmSouth=true;break;case"towgs84":this.datum_params=paramVal.split(",");break;case"to_meter":this.to_meter=parseFloat(paramVal);break;case"from_greenwich":this.from_greenwich=paramVal*Proj4js.common.D2R;break;case"pm":paramVal=paramVal.replace(/\s/gi,"");this.from_greenwich=Proj4js.PrimeMeridian[paramVal]?Proj4js.PrimeMeridian[paramVal]*Proj4js.common.D2R:0.0;break;case"no_defs":break;default:Proj4js.log("Unrecognized parameter: "+paramName);}}
this.deriveConstants();},deriveConstants:function(){if(this.nagrids=='@null')this.datumCode='none';if(this.datumCode&&this.datumCode!='none'){var datumDef=Proj4js.Datum[this.datumCode];if(datumDef){this.datum_params=datumDef.towgs84.split(',');this.ellps=datumDef.ellipse;this.datumName=datumDef.datumName;}}
if(!this.a){var ellipse=Proj4js.Ellipsoid[this.ellps]?Proj4js.Ellipsoid[this.ellps]:Proj4js.Ellipsoid['WGS84'];OpenLayers.Util.extend(this,ellipse);}
if(this.rf&&!this.b)this.b=(1.0-1.0/this.rf)*this.a;if(Math.abs(this.a-this.b)<Proj4js.common.EPSLN)this.sphere=true;this.a2=this.a*this.a;this.b2=this.b*this.b;this.es=(this.a2-this.b2)/this.a2;this.e=Math.sqrt(this.es);this.ep2=(this.a2-this.b2)/this.b2;if(!this.k0)this.k0=1.0;this.datum=new Proj4js.datum(this);}});Proj4js.Proj.longlat={init:function(){},forward:function(pt){return pt;},inverse:function(pt){return pt;}};Proj4js.defs={'WGS84':"+title=long/lat:WGS84 +proj=longlat +ellps=WGS84 +datum=WGS84",'EPSG:4326':"+title=long/lat:WGS84 +proj=longlat +a=6378137.0 +b=6356752.31424518 +ellps=WGS84 +datum=WGS84",'EPSG:4269':"+title=long/lat:NAD83 +proj=longlat +a=6378137.0 +b=6356752.31414036 +ellps=GRS80 +datum=NAD83"};Proj4js.common={PI:Math.PI,HALF_PI:Math.PI*0.5,TWO_PI:Math.PI*2,FORTPI:0.78539816339744833,R2D:57.2957795131,D2R:0.0174532925199,SEC_TO_RAD:4.84813681109535993589914102357e-6,EPSLN:1.0e-10,MAX_ITER:20,COS_67P5:0.38268343236508977,AD_C:1.0026000,PJD_UNKNOWN:0,PJD_3PARAM:1,PJD_7PARAM:2,PJD_GRIDSHIFT:3,PJD_WGS84:4,PJD_NODATUM:5,SRS_WGS84_SEMIMAJOR:6378137.0,msfnz:function(eccent,sinphi,cosphi){var con=eccent*sinphi;return cosphi/(Math.sqrt(1.0-con*con));},tsfnz:function(eccent,phi,sinphi){var con=eccent*sinphi;var com=.5*eccent;con=Math.pow(((1.0-con)/(1.0+con)),com);return(Math.tan(.5*(this.HALF_PI-phi))/con);},phi2z:function(eccent,ts){var eccnth=.5*eccent;var con,dphi;var phi=this.HALF_PI-2*Math.atan(ts);for(i=0;i<=15;i++){con=eccent*Math.sin(phi);dphi=this.HALF_PI-2*Math.atan(ts*(Math.pow(((1.0-con)/(1.0+con)),eccnth)))-phi;phi+=dphi;if(Math.abs(dphi)<=.0000000001)return phi;}
alert("phi2z has NoConvergence");return(-9999);},qsfnz:function(eccent,sinphi,cosphi){var con;if(eccent>1.0e-7){con=eccent*sinphi;return((1.0-eccent*eccent)*(sinphi/(1.0-con*con)-(.5/eccent)*Math.log((1.0-con)/(1.0+con))));}else{return(2.0*sinphi);}},asinz:function(x){if(Math.abs(x)>1.0){x=(x>1.0)?1.0:-1.0;}
return Math.asin(x);},e0fn:function(x){return(1.0-0.25*x*(1.0+x/16.0*(3.0+1.25*x)));},e1fn:function(x){return(0.375*x*(1.0+0.25*x*(1.0+0.46875*x)));},e2fn:function(x){return(0.05859375*x*x*(1.0+0.75*x));},e3fn:function(x){return(x*x*x*(35.0/3072.0));},mlfn:function(e0,e1,e2,e3,phi){return(e0*phi-e1*Math.sin(2.0*phi)+e2*Math.sin(4.0*phi)-e3*Math.sin(6.0*phi));},srat:function(esinp,exp){return(Math.pow((1.0-esinp)/(1.0+esinp),exp));},sign:function(x){if(x<0.0)return(-1);else return(1);},adjust_lon:function(x){x=(Math.abs(x)<this.PI)?x:(x-(this.sign(x)*this.TWO_PI));return x;}};Proj4js.datum=OpenLayers.Class({initialize:function(proj){this.datum_type=Proj4js.common.PJD_WGS84;if(proj.datumCode&&proj.datumCode=='none'){this.datum_type=Proj4js.common.PJD_NODATUM;}
if(proj&&proj.datum_params){for(var i=0;i<proj.datum_params.length;i++){proj.datum_params[i]=parseFloat(proj.datum_params[i]);}
if(proj.datum_params[0]!=0||proj.datum_params[1]!=0||proj.datum_params[2]!=0){this.datum_type=Proj4js.common.PJD_3PARAM;}
if(proj.datum_params.length>3){if(proj.datum_params[3]!=0||proj.datum_params[4]!=0||proj.datum_params[5]!=0||proj.datum_params[6]!=0){this.datum_type=Proj4js.common.PJD_7PARAM;proj.datum_params[3]*=Proj4js.common.SEC_TO_RAD;proj.datum_params[4]*=Proj4js.common.SEC_TO_RAD;proj.datum_params[5]*=Proj4js.common.SEC_TO_RAD;proj.datum_params[6]=(proj.datum_params[6]/1000000.0)+1.0;}}}
if(proj){this.a=proj.a;this.b=proj.b;this.es=proj.es;this.ep2=proj.ep2;this.datum_params=proj.datum_params;}},compare_datums:function(dest){if(this.datum_type!=dest.datum_type){return false;}else if(this.a!=dest.a||Math.abs(this.es-dest.es)>0.000000000050){return false;}else if(this.datum_type==Proj4js.common.PJD_3PARAM){return(this.datum_params[0]==dest.datum_params[0]&&this.datum_params[1]==dest.datum_params[1]&&this.datum_params[2]==dest.datum_params[2]);}else if(this.datum_type==Proj4js.common.PJD_7PARAM){return(this.datum_params[0]==dest.datum_params[0]&&this.datum_params[1]==dest.datum_params[1]&&this.datum_params[2]==dest.datum_params[2]&&this.datum_params[3]==dest.datum_params[3]&&this.datum_params[4]==dest.datum_params[4]&&this.datum_params[5]==dest.datum_params[5]&&this.datum_params[6]==dest.datum_params[6]);}else if(this.datum_type==Proj4js.common.PJD_GRIDSHIFT){return strcmp(pj_param(this.params,"snadgrids").s,pj_param(dest.params,"snadgrids").s)==0;}else{return true;}},geodetic_to_geocentric:function(p){var Longitude=p.x;var Latitude=p.y;var Height=p.z?p.z:0;var X;var Y;var Z;var Error_Code=0;var Rn;var Sin_Lat;var Sin2_Lat;var Cos_Lat;if(Latitude<-Proj4js.common.HALF_PI&&Latitude>-1.001*Proj4js.common.HALF_PI){Latitude=-Proj4js.common.HALF_PI;}else if(Latitude>Proj4js.common.HALF_PI&&Latitude<1.001*Proj4js.common.HALF_PI){Latitude=Proj4js.common.HALF_PI;}else if((Latitude<-Proj4js.common.HALF_PI)||(Latitude>Proj4js.common.HALF_PI)){Proj4js.reportError('geocent:lat out of range:'+Latitude);return null;}
if(Longitude>Proj4js.common.PI)Longitude-=(2*Proj4js.common.PI);Sin_Lat=Math.sin(Latitude);Cos_Lat=Math.cos(Latitude);Sin2_Lat=Sin_Lat*Sin_Lat;Rn=this.a/(Math.sqrt(1.0e0-this.es*Sin2_Lat));X=(Rn+Height)*Cos_Lat*Math.cos(Longitude);Y=(Rn+Height)*Cos_Lat*Math.sin(Longitude);Z=((Rn*(1-this.es))+Height)*Sin_Lat;p.x=X;p.y=Y;p.z=Z;return Error_Code;},geocentric_to_geodetic:function(p){var genau=1.E-12;var genau2=(genau*genau);var maxiter=30;var P;var RR;var CT;var ST;var RX;var RK;var RN;var CPHI0;var SPHI0;var CPHI;var SPHI;var SDPHI;var At_Pole;var iter;var X=p.x;var Y=p.y;var Z=p.z?p.z:0.0;var Longitude;var Latitude;var Height;At_Pole=false;P=Math.sqrt(X*X+Y*Y);RR=Math.sqrt(X*X+Y*Y+Z*Z);if(P/this.a<genau){At_Pole=true;Longitude=0.0;if(RR/this.a<genau){Latitude=Proj4js.common.HALF_PI;Height=-this.b;return;}}else{Longitude=Math.atan2(Y,X);}
CT=Z/RR;ST=P/RR;RX=1.0/Math.sqrt(1.0-this.es*(2.0-this.es)*ST*ST);CPHI0=ST*(1.0-this.es)*RX;SPHI0=CT*RX;iter=0;do
{iter++;RN=this.a/Math.sqrt(1.0-this.es*SPHI0*SPHI0);Height=P*CPHI0+Z*SPHI0-RN*(1.0-this.es*SPHI0*SPHI0);RK=this.es*RN/(RN+Height);RX=1.0/Math.sqrt(1.0-RK*(2.0-RK)*ST*ST);CPHI=ST*(1.0-RK)*RX;SPHI=CT*RX;SDPHI=SPHI*CPHI0-CPHI*SPHI0;CPHI0=CPHI;SPHI0=SPHI;}
while(SDPHI*SDPHI>genau2&&iter<maxiter);Latitude=Math.atan(SPHI/Math.abs(CPHI));p.x=Longitude;p.y=Latitude;p.z=Height;return p;},geocentric_to_geodetic_noniter:function(p){var X=p.x;var Y=p.y;var Z=p.z?p.z:0;var Longitude;var Latitude;var Height;var W;var W2;var T0;var T1;var S0;var S1;var Sin_B0;var Sin3_B0;var Cos_B0;var Sin_p1;var Cos_p1;var Rn;var Sum;var At_Pole;X=parseFloat(X);Y=parseFloat(Y);Z=parseFloat(Z);At_Pole=false;if(X!=0.0)
{Longitude=Math.atan2(Y,X);}
else
{if(Y>0)
{Longitude=Proj4js.common.HALF_PI;}
else if(Y<0)
{Longitude=-Proj4js.common.HALF_PI;}
else
{At_Pole=true;Longitude=0.0;if(Z>0.0)
{Latitude=Proj4js.common.HALF_PI;}
else if(Z<0.0)
{Latitude=-Proj4js.common.HALF_PI;}
else
{Latitude=Proj4js.common.HALF_PI;Height=-this.b;return;}}}
W2=X*X+Y*Y;W=Math.sqrt(W2);T0=Z*Proj4js.common.AD_C;S0=Math.sqrt(T0*T0+W2);Sin_B0=T0/S0;Cos_B0=W/S0;Sin3_B0=Sin_B0*Sin_B0*Sin_B0;T1=Z+this.b*this.ep2*Sin3_B0;Sum=W-this.a*this.es*Cos_B0*Cos_B0*Cos_B0;S1=Math.sqrt(T1*T1+Sum*Sum);Sin_p1=T1/S1;Cos_p1=Sum/S1;Rn=this.a/Math.sqrt(1.0-this.es*Sin_p1*Sin_p1);if(Cos_p1>=Proj4js.common.COS_67P5)
{Height=W/Cos_p1-Rn;}
else if(Cos_p1<=-Proj4js.common.COS_67P5)
{Height=W/-Cos_p1-Rn;}
else
{Height=Z/Sin_p1+Rn*(this.es-1.0);}
if(At_Pole==false)
{Latitude=Math.atan(Sin_p1/Cos_p1);}
p.x=Longitude;p.y=Latitude;p.z=Height;return p;},geocentric_to_wgs84:function(p){if(this.datum_type==Proj4js.common.PJD_3PARAM)
{p.x+=this.datum_params[0];p.y+=this.datum_params[1];p.z+=this.datum_params[2];}
else
{var Dx_BF=this.datum_params[0];var Dy_BF=this.datum_params[1];var Dz_BF=this.datum_params[2];var Rx_BF=this.datum_params[3];var Ry_BF=this.datum_params[4];var Rz_BF=this.datum_params[5];var M_BF=this.datum_params[6];var x_out=M_BF*(p.x-Rz_BF*p.y+Ry_BF*p.z)+Dx_BF;var y_out=M_BF*(Rz_BF*p.x+p.y-Rx_BF*p.z)+Dy_BF;var z_out=M_BF*(-Ry_BF*p.x+Rx_BF*p.y+p.z)+Dz_BF;p.x=x_out;p.y=y_out;p.z=z_out;}},geocentric_from_wgs84:function(p){if(this.datum_type==Proj4js.common.PJD_3PARAM)
{p.x-=this.datum_params[0];p.y-=this.datum_params[1];p.z-=this.datum_params[2];}
else
{var Dx_BF=this.datum_params[0];var Dy_BF=this.datum_params[1];var Dz_BF=this.datum_params[2];var Rx_BF=this.datum_params[3];var Ry_BF=this.datum_params[4];var Rz_BF=this.datum_params[5];var M_BF=this.datum_params[6];var x_tmp=(p.x-Dx_BF)/M_BF;var y_tmp=(p.y-Dy_BF)/M_BF;var z_tmp=(p.z-Dz_BF)/M_BF;p.x=x_tmp+Rz_BF*y_tmp-Ry_BF*z_tmp;p.y=-Rz_BF*x_tmp+y_tmp+Rx_BF*z_tmp;p.z=Ry_BF*x_tmp-Rx_BF*y_tmp+z_tmp;}}});Proj4js.Point=OpenLayers.Class({initialize:function(x,y,z){if(typeof x=='object'){this.x=x[0];this.y=x[1];this.z=x[2]||0.0;}else{this.x=x;this.y=y;this.z=z||0.0;}},clone:function(){return new Proj4js.Point(this.x,this.y,this.z);},toString:function(){return("x="+this.x+",y="+this.y);},toShortString:function(){return(this.x+", "+this.y);}});Proj4js.PrimeMeridian={"greenwich":0.0,"lisbon":-9.131906111111,"paris":2.337229166667,"bogota":-74.080916666667,"madrid":-3.687938888889,"rome":12.452333333333,"bern":7.439583333333,"jakarta":106.807719444444,"ferro":-17.666666666667,"brussels":4.367975,"stockholm":18.058277777778,"athens":23.7163375,"oslo":10.722916666667};Proj4js.Ellipsoid={"MERIT":{a:6378137.0,rf:298.257,ellipseName:"MERIT 1983"},"SGS85":{a:6378136.0,rf:298.257,ellipseName:"Soviet Geodetic System 85"},"GRS80":{a:6378137.0,rf:298.257222101,ellipseName:"GRS 1980(IUGG, 1980)"},"IAU76":{a:6378140.0,rf:298.257,ellipseName:"IAU 1976"},"airy":{a:6377563.396,b:6356256.910,ellipseName:"Airy 1830"},"APL4.":{a:6378137,rf:298.25,ellipseName:"Appl. Physics. 1965"},"NWL9D":{a:6378145.0,rf:298.25,ellipseName:"Naval Weapons Lab., 1965"},"mod_airy":{a:6377340.189,b:6356034.446,ellipseName:"Modified Airy"},"andrae":{a:6377104.43,rf:300.0,ellipseName:"Andrae 1876 (Den., Iclnd.)"},"aust_SA":{a:6378160.0,rf:298.25,ellipseName:"Australian Natl & S. Amer. 1969"},"GRS67":{a:6378160.0,rf:298.2471674270,ellipseName:"GRS 67(IUGG 1967)"},"bessel":{a:6377397.155,rf:299.1528128,ellipseName:"Bessel 1841"},"bess_nam":{a:6377483.865,rf:299.1528128,ellipseName:"Bessel 1841 (Namibia)"},"clrk66":{a:6378206.4,b:6356583.8,ellipseName:"Clarke 1866"},"clrk80":{a:6378249.145,rf:293.4663,ellipseName:"Clarke 1880 mod."},"CPM":{a:6375738.7,rf:334.29,ellipseName:"Comm. des Poids et Mesures 1799"},"delmbr":{a:6376428.0,rf:311.5,ellipseName:"Delambre 1810 (Belgium)"},"engelis":{a:6378136.05,rf:298.2566,ellipseName:"Engelis 1985"},"evrst30":{a:6377276.345,rf:300.8017,ellipseName:"Everest 1830"},"evrst48":{a:6377304.063,rf:300.8017,ellipseName:"Everest 1948"},"evrst56":{a:6377301.243,rf:300.8017,ellipseName:"Everest 1956"},"evrst69":{a:6377295.664,rf:300.8017,ellipseName:"Everest 1969"},"evrstSS":{a:6377298.556,rf:300.8017,ellipseName:"Everest (Sabah & Sarawak)"},"fschr60":{a:6378166.0,rf:298.3,ellipseName:"Fischer (Mercury Datum) 1960"},"fschr60m":{a:6378155.0,rf:298.3,ellipseName:"Fischer 1960"},"fschr68":{a:6378150.0,rf:298.3,ellipseName:"Fischer 1968"},"helmert":{a:6378200.0,rf:298.3,ellipseName:"Helmert 1906"},"hough":{a:6378270.0,rf:297.0,ellipseName:"Hough"},"intl":{a:6378388.0,rf:297.0,ellipseName:"International 1909 (Hayford)"},"kaula":{a:6378163.0,rf:298.24,ellipseName:"Kaula 1961"},"lerch":{a:6378139.0,rf:298.257,ellipseName:"Lerch 1979"},"mprts":{a:6397300.0,rf:191.0,ellipseName:"Maupertius 1738"},"new_intl":{a:6378157.5,b:6356772.2,ellipseName:"New International 1967"},"plessis":{a:6376523.0,rf:6355863.0,ellipseName:"Plessis 1817 (France)"},"krass":{a:6378245.0,rf:298.3,ellipseName:"Krassovsky, 1942"},"SEasia":{a:6378155.0,b:6356773.3205,ellipseName:"Southeast Asia"},"walbeck":{a:6376896.0,b:6355834.8467,ellipseName:"Walbeck"},"WGS60":{a:6378165.0,rf:298.3,ellipseName:"WGS 60"},"WGS66":{a:6378145.0,rf:298.25,ellipseName:"WGS 66"},"WGS72":{a:6378135.0,rf:298.26,ellipseName:"WGS 72"},"WGS84":{a:6378137.0,rf:298.257223563,ellipseName:"WGS 84"},"sphere":{a:6370997.0,b:6370997.0,ellipseName:"Normal Sphere (r=6370997)"}};Proj4js.Datum={"WGS84":{towgs84:"0,0,0",ellipse:"WGS84",datumName:""},"GGRS87":{towgs84:"-199.87,74.79,246.62",ellipse:"GRS80",datumName:"Greek_Geodetic_Reference_System_1987"},"NAD83":{towgs84:"0,0,0",ellipse:"GRS80",datumName:"North_American_Datum_1983"},"NAD27":{nadgrids:"@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat",ellipse:"clrk66",datumName:"North_American_Datum_1927"},"potsdam":{towgs84:"606.0,23.0,413.0",ellipse:"bessel",datumName:"Potsdam Rauenberg 1950 DHDN"},"carthage":{towgs84:"-263.0,6.0,431.0",ellipse:"clark80",datumName:"Carthage 1934 Tunisia"},"hermannskogel":{towgs84:"653.0,-212.0,449.0",ellipse:"bessel",datumName:"Hermannskogel"},"ire65":{towgs84:"482.530,-130.596,564.557,-1.042,-0.214,-0.631,8.15",ellipse:"mod_airy",datumName:"Ireland 1965"},"nzgd49":{towgs84:"59.47,-5.04,187.44,0.47,-0.1,1.024,-4.5993",ellipse:"intl",datumName:"New Zealand Geodetic Datum 1949"},"OSGB36":{towgs84:"446.448,-125.157,542.060,0.1502,0.2470,0.8421,-20.4894",ellipse:"airy",datumName:"Airy 1830"}};Proj4js.WGS84=new Proj4js.Proj('WGS84');Proj4js.Datum['OSB36']=Proj4js.Datum['OSGB36'];Proj4js.Proj.sterea={dependsOn:'gauss',init:function(){Proj4js.Proj['gauss'].init.apply(this);if(!this.rc){Proj4js.reportError("sterea:init:E_ERROR_0");return;}
this.sinc0=Math.sin(this.phic0);this.cosc0=Math.cos(this.phic0);this.R2=2.0*this.rc;if(!this.title)this.title="Oblique Stereographic Alternative";},forward:function(p){p.x=Proj4js.common.adjust_lon(p.x-this.long0);Proj4js.Proj['gauss'].forward.apply(this,[p]);sinc=Math.sin(p.y);cosc=Math.cos(p.y);cosl=Math.cos(p.x);k=this.k0*this.R2/(1.0+this.sinc0*sinc+this.cosc0*cosc*cosl);p.x=k*cosc*Math.sin(p.x);p.y=k*(this.cosc0*sinc-this.sinc0*cosc*cosl);p.x=this.a*p.x+this.x0;p.y=this.a*p.y+this.y0;return p;},inverse:function(p){var lon,lat;p.x=(p.x-this.x0)/this.a;p.y=(p.y-this.y0)/this.a;p.x/=this.k0;p.y/=this.k0;if((rho=Math.sqrt(p.x*p.x+p.y*p.y))){c=2.0*Math.atan2(rho,this.R2);sinc=Math.sin(c);cosc=Math.cos(c);lat=Math.asin(cosc*this.sinc0+p.y*sinc*this.cosc0/rho);lon=Math.atan2(p.x*sinc,rho*this.cosc0*cosc-p.y*this.sinc0*sinc);}else{lat=this.phic0;lon=0.;}
p.x=lon;p.y=lat;Proj4js.Proj['gauss'].inverse.apply(this,[p]);p.x=Proj4js.common.adjust_lon(p.x+this.long0);return p;}};Proj4js.Proj.aea={init:function(){if(Math.abs(this.lat1+this.lat2)<Proj4js.common.EPSLN){Proj4js.reportError("aeaInitEqualLatitudes");return;}
this.temp=this.b/this.a;this.es=1.0-Math.pow(this.temp,2);this.e3=Math.sqrt(this.es);this.sin_po=Math.sin(this.lat1);this.cos_po=Math.cos(this.lat1);this.t1=this.sin_po
this.con=this.sin_po;this.ms1=Proj4js.common.msfnz(this.e3,this.sin_po,this.cos_po);this.qs1=Proj4js.common.qsfnz(this.e3,this.sin_po,this.cos_po);this.sin_po=Math.sin(this.lat2);this.cos_po=Math.cos(this.lat2);this.t2=this.sin_po;this.ms2=Proj4js.common.msfnz(this.e3,this.sin_po,this.cos_po);this.qs2=Proj4js.common.qsfnz(this.e3,this.sin_po,this.cos_po);this.sin_po=Math.sin(this.lat0);this.cos_po=Math.cos(this.lat0);this.t3=this.sin_po;this.qs0=Proj4js.common.qsfnz(this.e3,this.sin_po,this.cos_po);if(Math.abs(this.lat1-this.lat2)>Proj4js.common.EPSLN){this.ns0=(this.ms1*this.ms1-this.ms2*this.ms2)/(this.qs2-this.qs1);}else{this.ns0=this.con;}
this.c=this.ms1*this.ms1+this.ns0*this.qs1;this.rh=this.a*Math.sqrt(this.c-this.ns0*this.qs0)/this.ns0;},forward:function(p){var lon=p.x;var lat=p.y;this.sin_phi=Math.sin(lat);this.cos_phi=Math.cos(lat);var qs=Proj4js.common.qsfnz(this.e3,this.sin_phi,this.cos_phi);var rh1=this.a*Math.sqrt(this.c-this.ns0*qs)/this.ns0;var theta=this.ns0*Proj4js.common.adjust_lon(lon-this.long0);var x=rh1*Math.sin(theta)+this.x0;var y=this.rh-rh1*Math.cos(theta)+this.y0;p.x=x;p.y=y;return p;},inverse:function(p){var rh1,qs,con,theta,lon,lat;p.x-=this.x0;p.y=this.rh-p.y+this.y0;if(this.ns0>=0){rh1=Math.sqrt(p.x*p.x+p.y*p.y);con=1.0;}else{rh1=-Math.sqrt(p.x*p.x+p.y*p.y);con=-1.0;}
theta=0.0;if(rh1!=0.0){theta=Math.atan2(con*p.x,con*p.y);}
con=rh1*this.ns0/this.a;qs=(this.c-con*con)/this.ns0;if(this.e3>=1e-10){con=1-.5*(1.0-this.es)*Math.log((1.0-this.e3)/(1.0+this.e3))/this.e3;if(Math.abs(Math.abs(con)-Math.abs(qs))>.0000000001){lat=this.phi1z(this.e3,qs);}else{if(qs>=0){lat=.5*PI;}else{lat=-.5*PI;}}}else{lat=this.phi1z(e3,qs);}
lon=Proj4js.common.adjust_lon(theta/this.ns0+this.long0);p.x=lon;p.y=lat;return p;},phi1z:function(eccent,qs){var con,com,dphi;var phi=Proj4js.common.asinz(.5*qs);if(eccent<Proj4js.common.EPSLN)return phi;var eccnts=eccent*eccent;for(var i=1;i<=25;i++){sinphi=Math.sin(phi);cosphi=Math.cos(phi);con=eccent*sinphi;com=1.0-con*con;dphi=.5*com*com/cosphi*(qs/(1.0-eccnts)-sinphi/com+.5/eccent*Math.log((1.0-con)/(1.0+con)));phi=phi+dphi;if(Math.abs(dphi)<=1e-7)return phi;}
Proj4js.reportError("aea:phi1z:Convergence error");return null;}};function phi4z(eccent,e0,e1,e2,e3,a,b,c,phi){var sinphi,sin2ph,tanph,ml,mlp,con1,con2,con3,dphi,i;phi=a;for(i=1;i<=15;i++){sinphi=Math.sin(phi);tanphi=Math.tan(phi);c=tanphi*Math.sqrt(1.0-eccent*sinphi*sinphi);sin2ph=Math.sin(2.0*phi);ml=e0*phi-e1*sin2ph+e2*Math.sin(4.0*phi)-e3*Math.sin(6.0*phi);mlp=e0-2.0*e1*Math.cos(2.0*phi)+4.0*e2*Math.cos(4.0*phi)-6.0*e3*Math.cos(6.0*phi);con1=2.0*ml+c*(ml*ml+b)-2.0*a*(c*ml+1.0);con2=eccent*sin2ph*(ml*ml+b-2.0*a*ml)/(2.0*c);con3=2.0*(a-ml)*(c*mlp-2.0/sin2ph)-2.0*mlp;dphi=con1/(con2+con3);phi+=dphi;if(Math.abs(dphi)<=.0000000001)return(phi);}
Proj4js.reportError("phi4z: No convergence");return null;}
function e4fn(x){var con,com;con=1.0+x;com=1.0-x;return(Math.sqrt((Math.pow(con,con))*(Math.pow(com,com))));}
Proj4js.Proj.poly={init:function(){var temp;if(this.lat0=0)this.lat0=90;this.temp=this.b/this.a;this.es=1.0-Math.pow(this.temp,2);this.e=Math.sqrt(this.es);this.e0=Proj4js.common.e0fn(this.es);this.e1=Proj4js.common.e1fn(this.es);this.e2=Proj4js.common.e2fn(this.es);this.e3=Proj4js.common.e3fn(this.es);this.ml0=Proj4js.common.mlfn(this.e0,this.e1,this.e2,this.e3,this.lat0);},forward:function(p){var sinphi,cosphi;var al;var c;var con,ml;var ms;var x,y;var lon=p.x;var lat=p.y;con=Proj4js.common.adjust_lon(lon-this.long0);if(Math.abs(lat)<=.0000001){x=this.x0+this.a*con;y=this.y0-this.a*this.ml0;}else{sinphi=Math.sin(lat);cosphi=Math.cos(lat);ml=Proj4js.common.mlfn(this.e0,this.e1,this.e2,this.e3,lat);ms=Proj4js.common.msfnz(this.e,sinphi,cosphi);con=sinphi;x=this.x0+this.a*ms*Math.sin(con)/sinphi;y=this.y0+this.a*(ml-this.ml0+ms*(1.0-Math.cos(con))/sinphi);}
p.x=x;p.y=y;return p;},inverse:function(p){var sin_phi,cos_phi;var al;var b;var c;var con,ml;var iflg;var lon,lat;p.x-=this.x0;p.y-=this.y0;al=this.ml0+p.y/this.a;iflg=0;if(Math.abs(al)<=.0000001){lon=p.x/this.a+this.long0;lat=0.0;}else{b=al*al+(p.x/this.a)*(p.x/this.a);iflg=phi4z(this.es,this.e0,this.e1,this.e2,this.e3,this.al,b,c,lat);if(iflg!=1)return(iflg);lon=Proj4js.common.adjust_lon((asinz(p.x*c/this.a)/Math.sin(lat))+this.long0);}
p.x=lon;p.y=lat;return p;}};Proj4js.Proj.equi={init:function(){if(!this.x0)this.x0=0;if(!this.y0)this.y0=0;if(!this.lat0)this.lat0=0;if(!this.long0)this.long0=0;},forward:function(p){var lon=p.x;var lat=p.y;var dlon=Proj4js.common.adjust_lon(lon-this.long0);var x=this.x0+this.a*dlon*Math.cos(this.lat0);var y=this.y0+this.a*lat;this.t1=x;this.t2=Math.cos(this.lat0);p.x=x;p.y=y;return p;},inverse:function(p){p.x-=this.x0;p.y-=this.y0;var lat=p.y/this.a;if(Math.abs(lat)>Proj4js.common.HALF_PI){Proj4js.reportError("equi:Inv:DataError");}
var lon=Proj4js.common.adjust_lon(this.long0+p.x/(this.a*Math.cos(this.lat0)));p.x=lon;p.y=lat;}};Proj4js.Proj.merc={init:function(){if(this.lat_ts){if(this.sphere){this.k0=Math.cos(this.lat_ts);}else{this.k0=Proj4js.common.msfnz(this.es,Math.sin(this.lat_ts),Math.cos(this.lat_ts));}}},forward:function(p){var lon=p.x;var lat=p.y;if(lat*Proj4js.common.R2D>90.0&&lat*Proj4js.common.R2D<-90.0&&lon*Proj4js.common.R2D>180.0&&lon*Proj4js.common.R2D<-180.0){Proj4js.reportError("merc:forward: llInputOutOfRange: "+lon+" : "+lat);return null;}
var x,y;if(Math.abs(Math.abs(lat)-Proj4js.common.HALF_PI)<=Proj4js.common.EPSLN){Proj4js.reportError("merc:forward: ll2mAtPoles");return null;}else{if(this.sphere){x=this.x0+this.a*this.k0*Proj4js.common.adjust_lon(lon-this.long0);y=this.y0+this.a*this.k0*Math.log(Math.tan(Proj4js.common.FORTPI+0.5*lat));}else{var sinphi=Math.sin(lat);var ts=Proj4js.common.tsfnz(this.e,lat,sinphi);x=this.x0+this.a*this.k0*Proj4js.common.adjust_lon(lon-this.long0);y=this.y0-this.a*this.k0*Math.log(ts);}
p.x=x;p.y=y;return p;}},inverse:function(p){var x=p.x-this.x0;var y=p.y-this.y0;var lon,lat;if(this.sphere){lat=Proj4js.common.HALF_PI-2.0*Math.atan(Math.exp(-y/this.a*this.k0));}else{var ts=Math.exp(-y/(this.a*this.k0));lat=Proj4js.common.phi2z(this.e,ts);if(lat==-9999){Proj4js.reportError("merc:inverse: lat = -9999");return null;}}
lon=Proj4js.common.adjust_lon(this.long0+x/(this.a*this.k0));p.x=lon;p.y=lat;return p;}};Proj4js.Proj.utm={dependsOn:'tmerc',init:function(){if(!this.zone){Proj4js.reportError("utm:init: zone must be specified for UTM");return;}
this.lat0=0.0;this.long0=((6*Math.abs(this.zone))-183)*Proj4js.common.D2R;this.x0=500000.0;this.y0=this.utmSouth?10000000.0:0.0;this.k0=0.9996;Proj4js.Proj['tmerc'].init.apply(this);this.forward=Proj4js.Proj['tmerc'].forward;this.inverse=Proj4js.Proj['tmerc'].inverse;}};Proj4js.Proj.eqdc={init:function(){if(!this.mode)this.mode=0;this.temp=this.b/this.a;this.es=1.0-Math.pow(this.temp,2);this.e=Math.sqrt(this.es);this.e0=Proj4js.common.e0fn(this.es);this.e1=Proj4js.common.e1fn(this.es);this.e2=Proj4js.common.e2fn(this.es);this.e3=Proj4js.common.e3fn(this.es);this.sinphi=Math.sin(this.lat1);this.cosphi=Math.cos(this.lat1);this.ms1=Proj4js.common.msfnz(this.e,this.sinphi,this.cosphi);this.ml1=Proj4js.common.mlfn(this.e0,this.e1,this.e2,this.e3,this.lat1);if(this.mode!=0){if(Math.abs(this.lat1+this.lat2)<Proj4js.common.EPSLN){Proj4js.reportError("eqdc:Init:EqualLatitudes");}
this.sinphi=Math.sin(this.lat2);this.cosphi=Math.cos(this.lat2);this.ms2=Proj4js.common.msfnz(this.e,this.sinphi,this.cosphi);this.ml2=Proj4js.common.mlfn(this.e0,this.e1,this.e2,this.e3,this.lat2);if(Math.abs(this.lat1-this.lat2)>=Proj4js.common.EPSLN){this.ns=(this.ms1-this.ms2)/(this.ml2-this.ml1);}else{this.ns=this.sinphi;}}else{this.ns=this.sinphi;}
this.g=this.ml1+this.ms1/this.ns;this.ml0=Proj4js.common.mlfn(this.e0,this.e1,this.e2,this.e3,this.lat0);this.rh=this.a*(this.g-this.ml0);},forward:function(p){var lon=p.x;var lat=p.y;var ml=Proj4js.common.mlfn(this.e0,this.e1,this.e2,this.e3,lat);var rh1=this.a*(this.g-ml);var theta=this.ns*Proj4js.common.adjust_lon(lon-this.long0);var x=this.x0+rh1*Math.sin(theta);var y=this.y0+this.rh-rh1*Math.cos(theta);p.x=x;p.y=y;return p;},inverse:function(p){p.x-=this.x0;p.y=this.rh-p.y+this.y0;var con,rh1;if(this.ns>=0){var rh1=Math.sqrt(p.x*p.x+p.y*p.y);var con=1.0;}else{rh1=-Math.sqrt(p.x*p.x+p.y*p.y);con=-1.0;}
var theta=0.0;if(rh1!=0.0)theta=Math.atan2(con*p.x,con*p.y);var ml=this.g-rh1/this.a;var lat=this.phi3z(this.ml,this.e0,this.e1,this.e2,this.e3);var lon=Proj4js.common.adjust_lon(this.long0+theta/this.ns);p.x=lon;p.y=lat;return p;},phi3z:function(ml,e0,e1,e2,e3){var phi;var dphi;phi=ml;for(var i=0;i<15;i++){dphi=(ml+e1*Math.sin(2.0*phi)-e2*Math.sin(4.0*phi)+e3*Math.sin(6.0*phi))/e0-phi;phi+=dphi;if(Math.abs(dphi)<=.0000000001){return phi;}}
Proj4js.reportError("PHI3Z-CONV:Latitude failed to converge after 15 iterations");return null;}};Proj4js.Proj.tmerc={init:function(){this.e0=Proj4js.common.e0fn(this.es);this.e1=Proj4js.common.e1fn(this.es);this.e2=Proj4js.common.e2fn(this.es);this.e3=Proj4js.common.e3fn(this.es);this.ml0=this.a*Proj4js.common.mlfn(this.e0,this.e1,this.e2,this.e3,this.lat0);},forward:function(p){var lon=p.x;var lat=p.y;var delta_lon=Proj4js.common.adjust_lon(lon-this.long0);var con;var x,y;var sin_phi=Math.sin(lat);var cos_phi=Math.cos(lat);if(this.sphere){var b=cos_phi*Math.sin(delta_lon);if((Math.abs(Math.abs(b)-1.0))<.0000000001){Proj4js.reportError("tmerc:forward: Point projects into infinity");return(93);}else{x=.5*this.a*this.k0*Math.log((1.0+b)/(1.0-b));con=Math.acos(cos_phi*Math.cos(delta_lon)/Math.sqrt(1.0-b*b));if(lat<0)con=-con;y=this.a*this.k0*(con-this.lat0);}}else{var al=cos_phi*delta_lon;var als=Math.pow(al,2);var c=this.ep2*Math.pow(cos_phi,2);var tq=Math.tan(lat);var t=Math.pow(tq,2);con=1.0-this.es*Math.pow(sin_phi,2);var n=this.a/Math.sqrt(con);var ml=this.a*Proj4js.common.mlfn(this.e0,this.e1,this.e2,this.e3,lat);x=this.k0*n*al*(1.0+als/6.0*(1.0-t+c+als/20.0*(5.0-18.0*t+Math.pow(t,2)+72.0*c-58.0*this.ep2)))+this.x0;y=this.k0*(ml-this.ml0+n*tq*(als*(0.5+als/24.0*(5.0-t+9.0*c+4.0*Math.pow(c,2)+als/30.0*(61.0-58.0*t+Math.pow(t,2)+600.0*c-330.0*this.ep2)))))+this.y0;}
p.x=x;p.y=y;return p;},inverse:function(p){var con,phi;var delta_phi;var i;var max_iter=6;var lat,lon;if(this.sphere){var f=Math.exp(p.x/(this.a*this.k0));var g=.5*(f-1/f);var temp=this.lat0+p.y/(this.a*this.k0);var h=Math.cos(temp);con=Math.sqrt((1.0-h*h)/(1.0+g*g));lat=Math.asinz(con);if(temp<0)
lat=-lat;if((g==0)&&(h==0)){lon=this.long0;}else{lon=Proj4js.common.adjust_lon(Math.atan2(g,h)+this.long0);}}else{var x=p.x-this.x0;var y=p.y-this.y0;con=(this.ml0+y/this.k0)/this.a;phi=con;for(i=0;;i++){delta_phi=((con+this.e1*Math.sin(2.0*phi)-this.e2*Math.sin(4.0*phi)+this.e3*Math.sin(6.0*phi))/this.e0)-phi;phi+=delta_phi;if(Math.abs(delta_phi)<=Proj4js.common.EPSLN)break;if(i>=max_iter){Proj4js.reportError("tmerc:inverse: Latitude failed to converge");return(95);}}
if(Math.abs(phi)<Proj4js.common.HALF_PI){var sin_phi=Math.sin(phi);var cos_phi=Math.cos(phi);var tan_phi=Math.tan(phi);var c=this.ep2*Math.pow(cos_phi,2);var cs=Math.pow(c,2);var t=Math.pow(tan_phi,2);var ts=Math.pow(t,2);con=1.0-this.es*Math.pow(sin_phi,2);var n=this.a/Math.sqrt(con);var r=n*(1.0-this.es)/con;var d=x/(n*this.k0);var ds=Math.pow(d,2);lat=phi-(n*tan_phi*ds/r)*(0.5-ds/24.0*(5.0+3.0*t+10.0*c-4.0*cs-9.0*this.ep2-ds/30.0*(61.0+90.0*t+298.0*c+45.0*ts-252.0*this.ep2-3.0*cs)));lon=Proj4js.common.adjust_lon(this.long0+(d*(1.0-ds/6.0*(1.0+2.0*t+c-ds/20.0*(5.0-2.0*c+28.0*t-3.0*cs+8.0*this.ep2+24.0*ts)))/cos_phi));}else{lat=Proj4js.common.HALF_PI*Proj4js.common.sign(y);lon=this.long0;}}
p.x=lon;p.y=lat;return p;}};Proj4js.defs["GOOGLE"]="+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs";Proj4js.defs["EPSG:900913"]=Proj4js.defs["GOOGLE"];Proj4js.Proj.ortho={init:function(def){;this.sin_p14=Math.sin(this.lat0);this.cos_p14=Math.cos(this.lat0);},forward:function(p){var sinphi,cosphi;var dlon;var coslon;var ksp;var g;var lon=p.x;var lat=p.y;dlon=Proj4js.common.adjust_lon(lon-this.long0);sinphi=Math.sin(lat);cosphi=Math.cos(lat);coslon=Math.cos(dlon);g=this.sin_p14*sinphi+this.cos_p14*cosphi*coslon;ksp=1.0;if((g>0)||(Math.abs(g)<=Proj4js.common.EPSLN)){var x=this.a*ksp*cosphi*Math.sin(dlon);var y=this.y0+this.a*ksp*(this.cos_p14*sinphi-this.sin_p14*cosphi*coslon);}else{Proj4js.reportError("orthoFwdPointError");}
p.x=x;p.y=y;return p;},inverse:function(p){var rh;var z;var sinz,cosz;var temp;var con;var lon,lat;p.x-=this.x0;p.y-=this.y0;rh=Math.sqrt(p.x*p.x+p.y*p.y);if(rh>this.a+.0000001){Proj4js.reportError("orthoInvDataError");}
z=Proj4js.common.asinz(rh/this.a);sinz=Math.sin(z);cosi=Math.cos(z);lon=this.long0;if(Math.abs(rh)<=Proj4js.common.EPSLN){lat=this.lat0;}
lat=Proj4js.common.asinz(cosz*this.sin_p14+(y*sinz*this.cos_p14)/rh);con=Math.abs(lat0)-Proj4js.common.HALF_PI;if(Math.abs(con)<=Proj4js.common.EPSLN){if(this.lat0>=0){lon=Proj4js.common.adjust_lon(this.long0+Math.atan2(p.x,-p.y));}else{lon=Proj4js.common.adjust_lon(this.long0-Math.atan2(-p.x,p.y));}}
con=cosz-this.sin_p14*Math.sin(lat);if((Math.abs(con)>=Proj4js.common.EPSLN)||(Math.abs(x)>=Proj4js.common.EPSLN)){lon=Proj4js.common.adjust_lon(this.long0+Math.atan2((p.x*sinz*this.cos_p14),(con*rh)));}
p.x=lon;p.y=lat;return p;}};Proj4js.Proj.stere={ssfn_:function(phit,sinphi,eccen){sinphi*=eccen;return(Math.tan(.5*(Proj4js.common.HALF_PI+phit))*Math.pow((1.-sinphi)/(1.+sinphi),.5*eccen));},TOL:1.e-8,NITER:8,CONV:1.e-10,S_POLE:0,N_POLE:1,OBLIQ:2,EQUIT:3,init:function(){this.phits=this.lat_ts?this.lat_ts:Proj4js.common.HALF_PI;var t=Math.abs(this.lat0);if((Math.abs(t)-Proj4js.common.HALF_PI)<Proj4js.common.EPSLN){this.mode=this.lat0<0.?this.S_POLE:this.N_POLE;}else{this.mode=t>Proj4js.common.EPSLN?this.OBLIQ:this.EQUIT;}
this.phits=Math.abs(this.phits);if(this.es){var X;switch(this.mode){case this.N_POLE:case this.S_POLE:if(Math.abs(this.phits-Proj4js.common.HALF_PI)<Proj4js.common.EPSLN){this.akm1=2.*this.k0/Math.sqrt(Math.pow(1+this.e,1+this.e)*Math.pow(1-this.e,1-this.e));}else{t=Math.sin(this.phits);this.akm1=Math.cos(this.phits)/Proj4js.common.tsfnz(this.e,this.phits,t);t*=this.e;this.akm1/=Math.sqrt(1.-t*t);}
break;case this.EQUIT:this.akm1=2.*this.k0;break;case this.OBLIQ:t=Math.sin(this.lat0);X=2.*Math.atan(this.ssfn_(this.lat0,t,this.e))-Proj4js.common.HALF_PI;t*=this.e;this.akm1=2.*this.k0*Math.cos(this.lat0)/Math.sqrt(1.-t*t);this.sinX1=Math.sin(X);this.cosX1=Math.cos(X);break;}}else{switch(this.mode){case this.OBLIQ:this.sinph0=Math.sin(this.lat0);this.cosph0=Math.cos(this.lat0);case this.EQUIT:this.akm1=2.*this.k0;break;case this.S_POLE:case this.N_POLE:this.akm1=Math.abs(this.phits-Proj4js.common.HALF_PI)>=Proj4js.common.EPSLN?Math.cos(this.phits)/Math.tan(Proj4js.common.FORTPI-.5*this.phits):2.*this.k0;break;}}},forward:function(p){var lon=p.x;var lat=p.y;var x,y
if(this.sphere){var sinphi,cosphi,coslam,sinlam;sinphi=Math.sin(lat);cosphi=Math.cos(lat);coslam=Math.cos(lon);sinlam=Math.sin(lon);switch(this.mode){case this.EQUIT:y=1.+cosphi*coslam;if(y<=Proj4js.common.EPSLN){F_ERROR;}
y=this.akm1/y;x=y*cosphi*sinlam;y*=sinphi;break;case this.OBLIQ:y=1.+this.sinph0*sinphi+this.cosph0*cosphi*coslam;if(y<=Proj4js.common.EPSLN){F_ERROR;}
y=this.akm1/y;x=y*cosphi*sinlam;y*=this.cosph0*sinphi-this.sinph0*cosphi*coslam;break;case this.N_POLE:coslam=-coslam;lat=-lat;case this.S_POLE:if(Math.abs(lat-Proj4js.common.HALF_PI)<this.TOL){F_ERROR;}
y=this.akm1*Math.tan(Proj4js.common.FORTPI+.5*lat)
x=sinlam*y;y*=coslam;break;}}else{coslam=Math.cos(lon);sinlam=Math.sin(lon);sinphi=Math.sin(lat);if(this.mode==this.OBLIQ||this.mode==this.EQUIT){X=2.*Math.atan(this.ssfn_(lat,sinphi,this.e));sinX=Math.sin(X-Proj4js.common.HALF_PI);cosX=Math.cos(X);}
switch(this.mode){case this.OBLIQ:A=this.akm1/(this.cosX1*(1.+this.sinX1*sinX+this.cosX1*cosX*coslam));y=A*(this.cosX1*sinX-this.sinX1*cosX*coslam);x=A*cosX;break;case this.EQUIT:A=2.*this.akm1/(1.+cosX*coslam);y=A*sinX;x=A*cosX;break;case this.S_POLE:lat=-lat;coslam=-coslam;sinphi=-sinphi;case this.N_POLE:x=this.akm1*Proj4js.common.tsfnz(this.e,lat,sinphi);y=-x*coslam;break;}
x=x*sinlam;}
p.x=x*this.a+this.x0;p.y=y*this.a+this.y0;return p;},inverse:function(p){var x=(p.x-this.x0)/this.a;var y=(p.y-this.y0)/this.a;var lon,lat
var cosphi,sinphi,tp=0.0,phi_l=0.0,rho,halfe=0.0,pi2=0.0;var i;if(this.sphere){var c,rh,sinc,cosc;rh=Math.sqrt(x*x+y*y);c=2.*Math.atan(rh/this.akm1);sinc=Math.sin(c);cosc=Math.cos(c);lon=0.;switch(this.mode){case this.EQUIT:if(Math.abs(rh)<=Proj4js.common.EPSLN){lat=0.;}else{lat=Math.asin(y*sinc/rh);}
if(cosc!=0.||x!=0.)lon=Math.atan2(x*sinc,cosc*rh);break;case this.OBLIQ:if(Math.abs(rh)<=Proj4js.common.EPSLN){lat=this.phi0;}else{lat=Math.asin(cosc*sinph0+y*sinc*cosph0/rh);}
c=cosc-sinph0*Math.sin(lat);if(c!=0.||x!=0.){lon=Math.atan2(x*sinc*cosph0,c*rh);}
break;case this.N_POLE:y=-y;case this.S_POLE:if(Math.abs(rh)<=Proj4js.common.EPSLN){lat=this.phi0;}else{lat=Math.asin(this.mode==this.S_POLE?-cosc:cosc);}
lon=(x==0.&&y==0.)?0.:Math.atan2(x,y);break;}}else{rho=Math.sqrt(x*x+y*y);switch(this.mode){case this.OBLIQ:case this.EQUIT:tp=2.*Math.atan2(rho*this.cosX1,this.akm1);cosphi=Math.cos(tp);sinphi=Math.sin(tp);if(rho==0.0){phi_l=Math.asin(cosphi*this.sinX1);}else{phi_l=Math.asin(cosphi*this.sinX1+(y*sinphi*this.cosX1/rho));}
tp=Math.tan(.5*(Proj4js.common.HALF_PI+phi_l));x*=sinphi;y=rho*this.cosX1*cosphi-y*this.sinX1*sinphi;pi2=Proj4js.common.HALF_PI;halfe=.5*this.e;break;case this.N_POLE:y=-y;case this.S_POLE:tp=-rho/this.akm1
phi_l=Proj4js.common.HALF_PI-2.*Math.atan(tp);pi2=-Proj4js.common.HALF_PI;halfe=-.5*this.e;break;}
for(i=this.NITER;i--;phi_l=lat){sinphi=this.e*Math.sin(phi_l);lat=2.*Math.atan(tp*Math.pow((1.+sinphi)/(1.-sinphi),halfe))-pi2;if(Math.abs(phi_l-lat)<this.CONV){if(this.mode==this.S_POLE)lat=-lat;lon=(x==0.&&y==0.)?0.:Math.atan2(x,y);p.x=lon;p.y=lat
return p;}}}}};Proj4js.Proj.mill={init:function(){},forward:function(p){var lon=p.x;var lat=p.y;dlon=Proj4js.common.adjust_lon(lon-this.long0);var x=this.x0+this.R*dlon;var y=this.y0+this.R*Math.log(Math.tan((Proj4js.common.PI/4.0)+(lat/2.5)))*1.25;p.x=x;p.y=y;return p;},inverse:function(p){p.x-=this.x0;p.y-=this.y0;var lon=Proj4js.common.adjust_lon(this.long0+p.x/this.R);var lat=2.5*(Math.atan(Math.exp(p.y/this.R/1.25))-Proj4js.common.PI/4.0);p.x=lon;p.y=lat;return p;}};Proj4js.Proj.sinu={init:function(){this.R=6370997.0;},forward:function(p){var x,y,delta_lon;var lon=p.x;var lat=p.y;delta_lon=Proj4js.common.adjust_lon(lon-this.long0);x=this.R*delta_lon*Math.cos(lat)+this.x0;y=this.R*lat+this.y0;p.x=x;p.y=y;return p;},inverse:function(p){var lat,temp,lon;p.x-=this.x0;p.y-=this.y0;lat=p.y/this.R;if(Math.abs(lat)>Proj4js.common.HALF_PI){Proj4js.reportError("sinu:Inv:DataError");}
temp=Math.abs(lat)-Proj4js.common.HALF_PI;if(Math.abs(temp)>Proj4js.common.EPSLN){temp=this.long0+p.x/(this.R*Math.cos(lat));lon=Proj4js.common.adjust_lon(temp);}else{lon=this.long0;}
p.x=lon;p.y=lat;return p;}};var GEOCENT_LAT_ERROR=0x0001;var COS_67P5=0.38268343236508977;var AD_C=1.0026000;function cs_geodetic_to_geocentric(cs,p){var Longitude=p.x;var Latitude=p.y;var Height=p.z;var X;var Y;var Z;var Error_Code=0;var Rn;var Sin_Lat;var Sin2_Lat;var Cos_Lat;if(Latitude<-HALF_PI&&Latitude>-1.001*HALF_PI)
Latitude=-HALF_PI;else if(Latitude>HALF_PI&&Latitude<1.001*HALF_PI)
Latitude=HALF_PI;else if((Latitude<-HALF_PI)||(Latitude>HALF_PI))
{Error_Code|=GEOCENT_LAT_ERROR;}
if(!Error_Code)
{if(Longitude>PI)
Longitude-=(2*PI);Sin_Lat=Math.sin(Latitude);Cos_Lat=Math.cos(Latitude);Sin2_Lat=Sin_Lat*Sin_Lat;Rn=cs.a/(Math.sqrt(1.0e0-cs.es*Sin2_Lat));X=(Rn+Height)*Cos_Lat*Math.cos(Longitude);Y=(Rn+Height)*Cos_Lat*Math.sin(Longitude);Z=((Rn*(1-cs.es))+Height)*Sin_Lat;}
p.x=X;p.y=Y;p.z=Z;return Error_Code;}
function cs_geocentric_to_geodetic(cs,p){var X=p.x;var Y=p.y;var Z=p.z;var Longitude;var Latitude;var Height;var W;var W2;var T0;var T1;var S0;var S1;var Sin_B0;var Sin3_B0;var Cos_B0;var Sin_p1;var Cos_p1;var Rn;var Sum;var At_Pole;X=parseFloat(X);Y=parseFloat(Y);Z=parseFloat(Z);At_Pole=false;if(X!=0.0)
{Longitude=Math.atan2(Y,X);}
else
{if(Y>0)
{Longitude=HALF_PI;}
else if(Y<0)
{Longitude=-HALF_PI;}
else
{At_Pole=true;Longitude=0.0;if(Z>0.0)
{Latitude=HALF_PI;}
else if(Z<0.0)
{Latitude=-HALF_PI;}
else
{Latitude=HALF_PI;Height=-cs.b;return;}}}
W2=X*X+Y*Y;W=Math.sqrt(W2);T0=Z*AD_C;S0=Math.sqrt(T0*T0+W2);Sin_B0=T0/S0;Cos_B0=W/S0;Sin3_B0=Sin_B0*Sin_B0*Sin_B0;T1=Z+cs.b*cs.ep2*Sin3_B0;Sum=W-cs.a*cs.es*Cos_B0*Cos_B0*Cos_B0;S1=Math.sqrt(T1*T1+Sum*Sum);Sin_p1=T1/S1;Cos_p1=Sum/S1;Rn=cs.a/Math.sqrt(1.0-cs.es*Sin_p1*Sin_p1);if(Cos_p1>=COS_67P5)
{Height=W/Cos_p1-Rn;}
else if(Cos_p1<=-COS_67P5)
{Height=W/-Cos_p1-Rn;}
else
{Height=Z/Sin_p1+Rn*(cs.es-1.0);}
if(At_Pole==false)
{Latitude=Math.atan(Sin_p1/Cos_p1);}
p.x=Longitude;p.y=Latitude;p.z=Height;return 0;}
function cs_geocentric_to_wgs84(defn,p){if(defn.datum_type==PJD_3PARAM)
{p.x+=defn.datum_params[0];p.y+=defn.datum_params[1];p.z+=defn.datum_params[2];}
else
{var Dx_BF=defn.datum_params[0];var Dy_BF=defn.datum_params[1];var Dz_BF=defn.datum_params[2];var Rx_BF=defn.datum_params[3];var Ry_BF=defn.datum_params[4];var Rz_BF=defn.datum_params[5];var M_BF=defn.datum_params[6];var x_out=M_BF*(p.x-Rz_BF*p.y+Ry_BF*p.z)+Dx_BF;var y_out=M_BF*(Rz_BF*p.x+p.y-Rx_BF*p.z)+Dy_BF;var z_out=M_BF*(-Ry_BF*p.x+Rx_BF*p.y+p.z)+Dz_BF;p.x=x_out;p.y=y_out;p.z=z_out;}}
function cs_geocentric_from_wgs84(defn,p){if(defn.datum_type==PJD_3PARAM)
{p.x-=defn.datum_params[0];p.y-=defn.datum_params[1];p.z-=defn.datum_params[2];}
else
{var Dx_BF=defn.datum_params[0];var Dy_BF=defn.datum_params[1];var Dz_BF=defn.datum_params[2];var Rx_BF=defn.datum_params[3];var Ry_BF=defn.datum_params[4];var Rz_BF=defn.datum_params[5];var M_BF=defn.datum_params[6];var x_tmp=(p.x-Dx_BF)/M_BF;var y_tmp=(p.y-Dy_BF)/M_BF;var z_tmp=(p.z-Dz_BF)/M_BF;p.x=x_tmp+Rz_BF*y_tmp-Ry_BF*z_tmp;p.y=-Rz_BF*x_tmp+y_tmp+Rx_BF*z_tmp;p.z=Ry_BF*x_tmp-Rx_BF*y_tmp+z_tmp;}}
Proj4js.Proj.vandg={init:function(){this.R=6370997.0;},forward:function(p){var lon=p.x;var lat=p.y;var dlon=Proj4js.common.adjust_lon(lon-this.long0);var x,y;if(Math.abs(lat)<=Proj4js.common.EPSLN){x=this.x0+this.R*dlon;y=this.y0;}
var theta=Proj4js.common.asinz(2.0*Math.abs(lat/Proj4js.common.PI));if((Math.abs(dlon)<=Proj4js.common.EPSLN)||(Math.abs(Math.abs(lat)-Proj4js.common.HALF_PI)<=Proj4js.common.EPSLN)){x=this.x0;if(lat>=0){y=this.y0+Proj4js.common.PI*this.R*Math.tan(.5*theta);}else{y=this.y0+Proj4js.common.PI*this.R*-Math.tan(.5*theta);}}
var al=.5*Math.abs((Proj4js.common.PI/dlon)-(dlon/Proj4js.common.PI));var asq=al*al;var sinth=Math.sin(theta);var costh=Math.cos(theta);var g=costh/(sinth+costh-1.0);var gsq=g*g;var m=g*(2.0/sinth-1.0);var msq=m*m;var con=Proj4js.common.PI*this.R*(al*(g-msq)+Math.sqrt(asq*(g-msq)*(g-msq)-(msq+asq)*(gsq-msq)))/(msq+asq);if(dlon<0){con=-con;}
x=this.x0+con;con=Math.abs(con/(Proj4js.common.PI*this.R));if(lat>=0){y=this.y0+Proj4js.common.PI*this.R*Math.sqrt(1.0-con*con-2.0*al*con);}else{y=this.y0-Proj4js.common.PI*this.R*Math.sqrt(1.0-con*con-2.0*al*con);}
p.x=x;p.y=y;return p;},inverse:function(p){var dlon;var xx,yy,xys,c1,c2,c3;var al,asq;var a1;var m1;var con;var th1;var d;p.x-=this.x0;p.y-=this.y0;con=Proj4js.common.PI*this.R;xx=p.x/con;yy=p.y/con;xys=xx*xx+yy*yy;c1=-Math.abs(yy)*(1.0+xys);c2=c1-2.0*yy*yy+xx*xx;c3=-2.0*c1+1.0+2.0*yy*yy+xys*xys;d=yy*yy/c3+(2.0*c2*c2*c2/c3/c3/c3-9.0*c1*c2/c3/c3)/27.0;a1=(c1-c2*c2/3.0/c3)/c3;m1=2.0*Math.sqrt(-a1/3.0);con=((3.0*d)/a1)/m1;if(Math.abs(con)>1.0){if(con>=0.0){con=1.0;}else{con=-1.0;}}
th1=Math.acos(con)/3.0;if(p.y>=0){lat=(-m1*Math.cos(th1+Proj4js.common.PI/3.0)-c2/3.0/c3)*Proj4js.common.PI;}else{lat=-(-m1*Math.cos(th1+PI/3.0)-c2/3.0/c3)*Proj4js.common.PI;}
if(Math.abs(xx)<Proj4js.common.EPSLN){lon=this.long0;}
lon=Proj4js.common.adjust_lon(this.long0+Proj4js.common.PI*(xys-1.0+Math.sqrt(1.0+2.0*(xx*xx-yy*yy)+xys*xys))/2.0/xx);p.x=lon;p.y=lat;return p;}};Proj4js.Proj.gauss={init:function(){sphi=Math.sin(this.lat0);cphi=Math.cos(this.lat0);cphi*=cphi;this.rc=Math.sqrt(1.0-this.es)/(1.0-this.es*sphi*sphi);this.C=Math.sqrt(1.0+this.es*cphi*cphi/(1.0-this.es));this.phic0=Math.asin(sphi/this.C);this.ratexp=0.5*this.C*this.e;this.K=Math.tan(0.5*this.phic0+Proj4js.common.FORTPI)/(Math.pow(Math.tan(0.5*this.lat0+Proj4js.common.FORTPI),this.C)*Proj4js.common.srat(this.e*sphi,this.ratexp));},forward:function(p){var lon=p.x;var lat=p.y;p.y=2.0*Math.atan(this.K*Math.pow(Math.tan(0.5*lat+Proj4js.common.FORTPI),this.C)*Proj4js.common.srat(this.e*Math.sin(lat),this.ratexp))-Proj4js.common.HALF_PI;p.x=this.C*lon;return p;},inverse:function(p){var DEL_TOL=1e-14;var lon=p.x/this.C;var lat=p.y;num=Math.pow(Math.tan(0.5*lat+Proj4js.common.FORTPI)/this.K,1./this.C);for(var i=Proj4js.common.MAX_ITER;i>0;--i){lat=2.0*Math.atan(num*Proj4js.common.srat(this.e*Math.sin(p.y),-0.5*this.e))-Proj4js.common.HALF_PI;if(Math.abs(lat-p.y)<DEL_TOL)break;p.y=lat;}
if(!i){Proj4js.reportError("gauss:inverse:convergence failed");return null;}
p.x=lon;p.y=lat;return p;}};Proj4js.Proj.omerc={init:function(){if(!this.mode)this.mode=0;if(!this.lon1){this.lon1=0;this.mode=1;}
if(!this.lon2)this.lon2=0;if(!this.lat2)this.lat2=0;var temp=this.b/this.a;var es=1.0-Math.pow(temp,2);var e=Math.sqrt(es);this.sin_p20=Math.sin(this.lat0);this.cos_p20=Math.cos(this.lat0);this.con=1.0-this.es*this.sin_p20*this.sin_p20;this.com=Math.sqrt(1.0-es);this.bl=Math.sqrt(1.0+this.es*Math.pow(this.cos_p20,4.0)/(1.0-es));this.al=this.a*this.bl*this.k0*this.com/this.con;if(Math.abs(this.lat0)<Proj4js.common.EPSLN){this.ts=1.0;this.d=1.0;this.el=1.0;}else{this.ts=Proj4js.common.tsfnz(this.e,this.lat0,this.sin_p20);this.con=Math.sqrt(this.con);this.d=this.bl*this.com/(this.cos_p20*this.con);if((this.d*this.d-1.0)>0.0){if(this.lat0>=0.0){this.f=this.d+Math.sqrt(this.d*this.d-1.0);}else{this.f=this.d-Math.sqrt(this.d*this.d-1.0);}}else{this.f=this.d;}
this.el=this.f*Math.pow(this.ts,this.bl);}
if(this.mode!=0){this.g=.5*(this.f-1.0/this.f);this.gama=Proj4js.common.asinz(Math.sin(this.alpha)/this.d);this.longc=this.longc-Proj4js.common.asinz(this.g*Math.tan(this.gama))/this.bl;this.con=Math.abs(this.lat0);if((this.con>Proj4js.common.EPSLN)&&(Math.abs(this.con-Proj4js.common.HALF_PI)>Proj4js.common.EPSLN)){this.singam=Math.sin(this.gama);this.cosgam=Math.cos(this.gama);this.sinaz=Math.sin(this.alpha);this.cosaz=Math.cos(this.alpha);if(this.lat0>=0){this.u=(this.al/this.bl)*Math.atan(Math.sqrt(this.d*this.d-1.0)/this.cosaz);}else{this.u=-(this.al/this.bl)*Math.atan(Math.sqrt(this.d*this.d-1.0)/this.cosaz);}}else{Proj4js.reportError("omerc:Init:DataError");}}else{this.sinphi=Math.sin(this.at1);this.ts1=Proj4js.common.tsfnz(this.e,this.lat1,this.sinphi);this.sinphi=Math.sin(this.lat2);this.ts2=Proj4js.common.tsfnz(this.e,this.lat2,this.sinphi);this.h=Math.pow(this.ts1,this.bl);this.l=Math.pow(this.ts2,this.bl);this.f=this.el/this.h;this.g=.5*(this.f-1.0/this.f);this.j=(this.el*this.el-this.l*this.h)/(this.el*this.el+this.l*this.h);this.p=(this.l-this.h)/(this.l+this.h);this.dlon=this.lon1-this.lon2;if(this.dlon<-Proj4js.common.PI)this.lon2=this.lon2-2.0*Proj4js.common.PI;if(this.dlon>Proj4js.common.PI)this.lon2=this.lon2+2.0*Proj4js.common.PI;this.dlon=this.lon1-this.lon2;this.longc=.5*(this.lon1+this.lon2)-Math.atan(this.j*Math.tan(.5*this.bl*this.dlon)/this.p)/this.bl;this.dlon=Proj4js.common.adjust_lon(this.lon1-this.longc);this.gama=Math.atan(Math.sin(this.bl*this.dlon)/this.g);this.alpha=Proj4js.common.asinz(this.d*Math.sin(this.gama));if(Math.abs(this.lat1-this.lat2)<=Proj4js.common.EPSLN){Proj4js.reportError("omercInitDataError");}else{this.con=Math.abs(this.lat1);}
if((this.con<=Proj4js.common.EPSLN)||(Math.abs(this.con-HALF_PI)<=Proj4js.common.EPSLN)){Proj4js.reportError("omercInitDataError");}else{if(Math.abs(Math.abs(this.lat0)-Proj4js.common.HALF_PI)<=Proj4js.common.EPSLN){Proj4js.reportError("omercInitDataError");}}
this.singam=Math.sin(this.gam);this.cosgam=Math.cos(this.gam);this.sinaz=Math.sin(this.alpha);this.cosaz=Math.cos(this.alpha);if(this.lat0>=0){this.u=(this.al/this.bl)*Math.atan(Math.sqrt(this.d*this.d-1.0)/this.cosaz);}else{this.u=-(this.al/this.bl)*Math.atan(Math.sqrt(this.d*this.d-1.0)/this.cosaz);}}},forward:function(p){var theta;var sin_phi,cos_phi;var b;var c,t,tq;var con,n,ml;var q,us,vl;var ul,vs;var s;var dlon;var ts1;var lon=p.x;var lat=p.y;sin_phi=Math.sin(lat);dlon=Proj4js.common.adjust_lon(lon-this.longc);vl=Math.sin(this.bl*dlon);if(Math.abs(Math.abs(lat)-Proj4js.common.HALF_PI)>Proj4js.common.EPSLN){ts1=Proj4js.common.tsfnz(this.e,lat,sin_phi);q=this.el/(Math.pow(ts1,this.bl));s=.5*(q-1.0/q);t=.5*(q+1.0/q);ul=(s*this.singam-vl*this.cosgam)/t;con=Math.cos(this.bl*dlon);if(Math.abs(con)<.0000001){us=this.al*this.bl*dlon;}else{us=this.al*Math.atan((s*this.cosgam+vl*this.singam)/con)/this.bl;if(con<0)us=us+Proj4js.common.PI*this.al/this.bl;}}else{if(lat>=0){ul=this.singam;}else{ul=-this.singam;}
us=this.al*lat/this.bl;}
if(Math.abs(Math.abs(ul)-1.0)<=Proj4js.common.EPSLN){Proj4js.reportError("omercFwdInfinity");}
vs=.5*this.al*Math.log((1.0-ul)/(1.0+ul))/this.bl;us=us-this.u;var x=this.x0+vs*this.cosaz+us*this.sinaz;var y=this.y0+us*this.cosaz-vs*this.sinaz;p.x=x;p.y=y;return p;},inverse:function(p){var delta_lon;var theta;var delta_theta;var sin_phi,cos_phi;var b;var c,t,tq;var con,n,ml;var vs,us,q,s,ts1;var vl,ul,bs;var dlon;var flag;p.x-=this.x0;p.y-=this.y0;flag=0;vs=p.x*this.cosaz-p.y*this.sinaz;us=p.y*this.cosaz+p.x*this.sinaz;us=us+this.u;q=Math.exp(-this.bl*vs/this.al);s=.5*(q-1.0/q);t=.5*(q+1.0/q);vl=Math.sin(this.bl*us/this.al);ul=(vl*this.cosgam+s*this.singam)/t;if(Math.abs(Math.abs(ul)-1.0)<=Proj4js.common.EPSLN)
{lon=this.longc;if(ul>=0.0){lat=Proj4js.common.HALF_PI;}else{lat=-Proj4js.common.HALF_PI;}}else{con=1.0/this.bl;ts1=Math.pow((this.el/Math.sqrt((1.0+ul)/(1.0-ul))),con);lat=Proj4js.common.phi2z(this.e,ts1);theta=this.longc-Math.atan2((s*this.cosgam-vl*this.singam),con)/this.bl;lon=Proj4js.common.adjust_lon(theta);}
p.x=lon;p.y=lat;return p;}};Proj4js.Proj.lcc={init:function(){if(!this.lat2){this.lat2=this.lat0;}
if(!this.k0)this.k0=1.0;if(Math.abs(this.lat1+this.lat2)<Proj4js.common.EPSLN){Proj4js.reportError("lcc:init: Equal Latitudes");return;}
var temp=this.b/this.a;this.e=Math.sqrt(1.0-temp*temp);var sin1=Math.sin(this.lat1);var cos1=Math.cos(this.lat1);var ms1=Proj4js.common.msfnz(this.e,sin1,cos1);var ts1=Proj4js.common.tsfnz(this.e,this.lat1,sin1);var sin2=Math.sin(this.lat2);var cos2=Math.cos(this.lat2);var ms2=Proj4js.common.msfnz(this.e,sin2,cos2);var ts2=Proj4js.common.tsfnz(this.e,this.lat2,sin2);var ts0=Proj4js.common.tsfnz(this.e,this.lat0,Math.sin(this.lat0));if(Math.abs(this.lat1-this.lat2)>Proj4js.common.EPSLN){this.ns=Math.log(ms1/ms2)/Math.log(ts1/ts2);}else{this.ns=sin1;}
this.f0=ms1/(this.ns*Math.pow(ts1,this.ns));this.rh=this.a*this.f0*Math.pow(ts0,this.ns);if(!this.title)this.title="Lambert Conformal Conic";},forward:function(p){var lon=p.x;var lat=p.y;if(lat<=90.0&&lat>=-90.0&&lon<=180.0&&lon>=-180.0){}else{Proj4js.reportError("lcc:forward: llInputOutOfRange: "+lon+" : "+lat);return null;}
var con=Math.abs(Math.abs(lat)-Proj4js.common.HALF_PI);var ts;if(con>Proj4js.common.EPSLN){ts=Proj4js.common.tsfnz(this.e,lat,Math.sin(lat));rh1=this.a*this.f0*Math.pow(ts,this.ns);}else{con=lat*this.ns;if(con<=0){Proj4js.reportError("lcc:forward: No Projection");return null;}
rh1=0;}
var theta=this.ns*Proj4js.common.adjust_lon(lon-this.long0);p.x=this.k0*(rh1*Math.sin(theta))+this.x0;p.y=this.k0*(this.rh-rh1*Math.cos(theta))+this.y0;return p;},inverse:function(p){var rh1,con,ts;var lat,lon;x=(p.x-this.x0)/this.k0;y=(this.rh-(p.y-this.y0)/this.k0);if(this.ns>0){rh1=Math.sqrt(x*x+y*y);con=1.0;}else{rh1=-Math.sqrt(x*x+y*y);con=-1.0;}
var theta=0.0;if(rh1!=0){theta=Math.atan2((con*x),(con*y));}
if((rh1!=0)||(this.ns>0.0)){con=1.0/this.ns;ts=Math.pow((rh1/(this.a*this.f0)),con);lat=Proj4js.common.phi2z(this.e,ts);if(lat==-9999)return null;}else{lat=-Proj4js.common.HALF_PI;}
lon=Proj4js.common.adjust_lon(theta/this.ns+this.long0);p.x=lon;p.y=lat;return p;}};Proj4js.Proj.laea={init:function(){this.sin_lat_o=Math.sin(this.lat0);this.cos_lat_o=Math.cos(this.lat0);},forward:function(p){var lon=p.x;var lat=p.y;var delta_lon=Proj4js.common.adjust_lon(lon-this.long0);var sin_lat=Math.sin(lat);var cos_lat=Math.cos(lat);var sin_delta_lon=Math.sin(delta_lon);var cos_delta_lon=Math.cos(delta_lon);var g=this.sin_lat_o*sin_lat+this.cos_lat_o*cos_lat*cos_delta_lon;if(g==-1.0){Proj4js.reportError("laea:fwd:Point projects to a circle of radius "+2.0*R);return null;}
var ksp=this.a*Math.sqrt(2.0/(1.0+g));var x=ksp*cos_lat*sin_delta_lon+this.x0;var y=ksp*(this.cos_lat_o*sin_lat-this.sin_lat_o*cos_lat*cos_delta_lon)+this.x0;p.x=x;p.y=y
return p;},inverse:function(p){p.x-=this.x0;p.y-=this.y0;var Rh=Math.sqrt(p.x*p.x+p.y*p.y);var temp=Rh/(2.0*this.a);if(temp>1){Proj4js.reportError("laea:Inv:DataError");return null;}
var z=2.0*Proj4js.common.asinz(temp);var sin_z=Math.sin(z);var cos_z=Math.cos(z);var lon=this.long0;if(Math.abs(Rh)>Proj4js.common.EPSLN){var lat=Proj4js.common.asinz(this.sin_lat_o*cos_z+this.cos_lat_o*sin_z*p.y/Rh);var temp=Math.abs(this.lat0)-Proj4js.common.HALF_PI;if(Math.abs(temp)>Proj4js.common.EPSLN){temp=cos_z-this.sin_lat_o*Math.sin(lat);if(temp!=0.0)lon=Proj4js.common.adjust_lon(this.long0+Math.atan2(p.x*sin_z*this.cos_lat_o,temp*Rh));}else if(this.lat0<0.0){lon=Proj4js.common.adjust_lon(this.long0-Math.atan2(-p.x,p.y));}else{lon=Proj4js.common.adjust_lon(this.long0+Math.atan2(p.x,-p.y));}}else{lat=this.lat0;}
p.x=lon;p.y=lat;return p;}};Proj4js.Proj.aeqd={init:function(){this.sin_p12=Math.sin(this.lat0)
this.cos_p12=Math.cos(this.lat0)},forward:function(p){var lon=p.x;var lat=p.y;var ksp;var sinphi=Math.sin(p.y);var cosphi=Math.cos(p.y);var dlon=Proj4js.common.adjust_lon(lon-this.long0);var coslon=Math.cos(dlon);var g=this.sin_p12*sinphi+this.cos_p12*cosphi*coslon;if(Math.abs(Math.abs(g)-1.0)<Proj4js.common.EPSLN){ksp=1.0;if(g<0.0){Proj4js.reportError("aeqd:Fwd:PointError");return;}}else{var z=Math.acos(g);ksp=z/Math.sin(z);}
p.x=this.x0+this.a*ksp*cosphi*Math.sin(dlon);p.y=this.y0+this.a*ksp*(this.cos_p12*sinphi-this.sin_p12*cosphi*coslon);return p;},inverse:function(p){p.x-=this.x0;p.y-=this.y0;var rh=Math.sqrt(p.x*p.x+p.y*p.y);if(rh>(2.0*Proj4js.common.HALF_PI*this.a)){Proj4js.reportError("aeqdInvDataError");return;}
var z=rh/this.a;var sinz=Math.sin(z)
var cosz=Math.cos(z)
var lon=this.long0;var lat;if(Math.abs(rh)<=Proj4js.common.EPSLN){lat=this.lat0;}else{lat=Proj4js.common.asinz(cosz*this.sin_p12+(p.y*sinz*this.cos_p12)/rh);var con=Math.abs(this.lat0)-Proj4js.common.HALF_PI;if(Math.abs(con)<=Proj4js.common.EPSLN){if(lat0>=0.0){lon=Proj4js.common.adjust_lon(this.long0+Math.atan2(p.x,-p.y));}else{lon=Proj4js.common.adjust_lon(this.long0-Math.atan2(-p.x,p.y));}}else{con=cosz-this.sin_p12*Math.sin(lat);if((Math.abs(con)<Proj4js.common.EPSLN)&&(Math.abs(p.x)<Proj4js.common.EPSLN)){}else{var temp=Math.atan2((p.x*sinz*this.cos_p12),(con*rh));lon=Proj4js.common.adjust_lon(this.long0+Math.atan2((p.x*sinz*this.cos_p12),(con*rh)));}}}
p.x=lon;p.y=lat;return p;}};Proj4js.Proj.moll={init:function(){},forward:function(p){var lon=p.x;var lat=p.y;var delta_lon=Proj4js.common.adjust_lon(lon-this.long0);var theta=lat;var con=Proj4js.common.PI*Math.sin(lat);for(var i=0;;i++){var delta_theta=-(theta+Math.sin(theta)-con)/(1.0+Math.cos(theta));theta+=delta_theta;if(Math.abs(delta_theta)<Proj4js.common.EPSLN)break;if(i>=50){Proj4js.reportError("moll:Fwd:IterationError");}}
theta/=2.0;if(Proj4js.common.PI/2-Math.abs(lat)<Proj4js.common.EPSLN)delta_lon=0;var x=0.900316316158*this.R*delta_lon*Math.cos(theta)+this.x0;var y=1.4142135623731*this.R*Math.sin(theta)+this.y0;p.x=x;p.y=y;return p;},inverse:function(p){var theta;var arg;p.x-=this.x0;var arg=p.y/(1.4142135623731*this.R);if(Math.abs(arg)>0.999999999999)arg=0.999999999999;var theta=Math.asin(arg);var lon=Proj4js.common.adjust_lon(this.long0+(p.x/(0.900316316158*this.R*Math.cos(theta))));if(lon<(-Proj4js.common.PI))lon=-Proj4js.common.PI;if(lon>Proj4js.common.PI)lon=Proj4js.common.PI;arg=(2.0*theta+Math.sin(2.0*theta))/Proj4js.common.PI;if(Math.abs(arg)>1.0)arg=1.0;var lat=Math.asin(arg);p.x=lon;p.y=lat;return p;}};Proj4js.defs["EPSG:4326"]="+title=WGS84 +proj=longlat +a=6378137.0 +b=6356752.31424518 +ellps=WGS84 +datum=WGS84 +units=degrees";Proj4js.defs["EPSG:2942"]="+title=Porto Santo / UTM zone 28N +proj=utm +zone=28 +ellps=intl +towgs84=-499,-249,314,0,0,0,0 +units=m +no_defs ";Proj4js.defs["EPSG:27492"]="+title=Hayford-Gauss Datum 73 +proj=tmerc +lat_0=39.66666666666666 +lon_0=-8.131906111111112 +k=1 +x_0=180.598 +y_0=-86.98999999999999 +ellps=intl +units=m +no_defs ";Proj4js.defs["EPSG:900913"]=" +title= Google Mercator EPSG:900913 +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs ";Proj4js.defs["GOOGLE"]="+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs";Proj4js.defs["EPSG:900913"]=Proj4js.defs["GOOGLE"];Ext.namespace('Municipia.controls');Ext.namespace('Municipia.controls.print');Municipia.controls.print.Base={map:null,maps2Print:null,overrides:null,configUrl:null,config:null,layerTree:null,grids:null,intersectionLayer:null,legendEstatisticos:null,intersectionTitle:'',flagPDM:false,serviceParams:null,mask:null,printing:false,initPrint:function(){if(this.overrides==null){this.overrides={};}
if(this.config==null){Municipia.PrintProtocol.getConfiguration(this.configUrl,this.configReceived,this.configFailed,this,this.serviceParams,this.flagPDM);return true;}else{this.fillComponent();return false;}},configReceived:function(config){this.config=config;if(this.mask){this.mask.hide();}},configFailed:function(){if(this.mask){this.mask.hide();}},print:function(){if(this.mask){this.mask.msg=OpenLayers.i18n('print.generatingPDF');this.mask.show();}
var printCommand=new Municipia.PrintProtocol(this.map,this.config,this.overrides,this.getCurDpi(),this.serviceParams,this.flagPDM);this.fillSpec(printCommand);if(this.layerTree){this.addLegends(printCommand.spec);}
if(this.grids){this.addGrids(printCommand.spec);}
if(this.legendEstatisticos){this.addLegendEstatisticos(printCommand.spec,this.map);}
if(printCommand.spec.intersections){if(this.intersectionLayer!=null&&this.intersectionLayer.features.length>0){this.addIntersections(printCommand.spec,this.map);}else{if(this.mask){this.mask.hide();}
Ext.MessageBox.alert(OpenLayers.i18n('print.information'),OpenLayers.i18n('print.missfeaturesintersection'),null);return;}}
this.printing=true;printCommand.createPDF(function(){if(this.mask)this.mask.hide();this.printing=false;},function(request){var onClick='Ext.getCmp(\'printPopup\').destroy();';var path=request.getURL;if(path.lastIndexOf('?')!=-1)
{path=Base64.encode(path.substring(0,path.lastIndexOf('?')))+path.substring(path.lastIndexOf('?'));}
else
{path=Base64.encode(path)+"?";}
var urlFile=((app.urlApp.lastIndexOf('/')==app.urlApp.length-1)?app.urlApp:(app.urlApp+"/"))+app.proxyWMS+path;onClick+='window.open(\''+'util/Download.aspx?urlFile='+urlFile+'\', \'_blank\');';var content='<table border="0" cellspacing="0" cellpadding="0" class="printPageHeader" align="Center">';content+='<tr>';content+='<td colspan="2" >';content+=OpenLayers.i18n('print.pdfReady');content+='</td>';content+='</tr>';content+='</table>';content+='<div class="printPageContent">';content+='<table cellspacing="1" cellpadding="0" >';content+='<tr><td colspan="2"><br /></td></tr>';content+='<tr>';content+='<td colspan="2" align="right"  >';content+='<table id="PlantLinks" align="Center" border="0">';content+='<tr>';content+='<td><a title="'+OpenLayers.i18n('print.pdfView')+'" href="#" onclick="'+onClick+'" ><img title="Visualizar Impresso" src="images/pdfIcon.gif" style="border-width:0px;" /></a></td><td class="pdfUrlClass"><a href="#"  onclick="'+onClick+'" >'+OpenLayers.i18n('print.name-pdf')+'</a></td>';content+='</tr>';content+='</table>';content+='<br />';content+='<br />';content+='<center>';content+=OpenLayers.i18n('print.acrobat-reader-msg');content+='</center>';content+='</tr>';content+='</table>';content+='</div>';var popup=new Ext.Window({bodyStyle:'padding: 7px;',width:380,id:"printPopup",autoHeight:true,constrain:true,closable:true,title:OpenLayers.i18n('print.information'),html:content,listeners:{destroy:function(){if(this.mask)this.mask.hide();this.printing=false;},scope:this}});popup.show();},function(request){Ext.Msg.alert(OpenLayers.i18n('print.error'),OpenLayers.i18n('print.unableToPrint'));if(this.mask)this.mask.hide();this.printing=false;},this);},addGrids:function(spec){var grids=this.grids;if(grids&&typeof grids=="function"){grids=grids();}
if(grids){for(var name in grids){var grid=grids[name];if(!grid){continue;}
spec[name]={};var specData=spec[name].data=[];var specCols=spec[name].columns=[];var columns=grid.getColumnModel();var store=grid.getStore();for(var j=0;j<columns.getColumnCount();++j){if(!columns.isHidden(j)){specCols.push(columns.getDataIndex(j));}}
store.each(function(record){var hash={};for(var key in record.data){var val=record.data[key];if(val!=null){if(val.CLASS_NAME&&val.CLASS_NAME=='OpenLayers.Feature.Vector'){val=new OpenLayers.Format.WKT().write(val);}
hash[key]=val;}}
specData.push(hash);},this);}}},addLegends:function(spec){var legends=spec.legends=[];function addLayerIcon(layerNode){var layerInfo={name:layerNode.Text,icon:Municipia.Util.relativeToAbsoluteURL(layerNode.Image)};var classesInfo=layerInfo.classes=[];legends.push(layerInfo);}
function addLayerLegend(layerNode){var src='';var url=layerNode.Nodes[0].Attributes["legendURL"];var path=app.urlWMS;if(url.indexOf('?')==0){if(path.lastIndexOf('?')==path.length-1){path=path.substring(0,path.length-1);}
src=path+url;}
var layerInfo={name:layerNode.Text,icon:encodeURIComponent(Municipia.Util.relativeToAbsoluteURL(src))};var classesInfo=layerInfo.classes=[];legends.push(layerInfo);}
function goDeep(root){for(var index=0;index<root.length;index++){var node=root[index];var attr=node.Attributes;if(node.Checked&&node.Enabled&&node.Text&&node.Nodes.length==0){addLayerIcon(node);}else if(node.Checked&&node.Enabled&&node.Text&&node.Nodes.length==1&&node.Nodes[0].Category=="legenda"){addLayerLegend(node);}}}
goDeep(this.layerTree.AllNodes);},addLegendEstatisticos:function(spec,map){var legends=spec.legends=[];spec.titleLegenda='';for(var i=0;i<map.layers.length;++i){var olLayer=map.layers[i];if(olLayer.getVisibility()&&olLayer.calculateInRange()&&!olLayer.isBaseLayer){var legenda=this.getProperty(olLayer,"urlLegendEstatisticos");if(legenda){spec.titleLegenda=this.getProperty(olLayer,"tituloLegendEstatisticos");spec.mapTitle=this.getProperty(olLayer,"tituloEstatisticos");var layerInfo={name:'',icon:legenda};var classesInfo=layerInfo.classes=[];legends.push(layerInfo);}}}},addIntersections:function(spec,map){var intersectionsList=spec.intersections=[];var intersection={};var out_options={'internalProjection':map.baseLayer.projection,'externalProjection':map.baseLayer.projection};var format=new OpenLayers.Format.WKT(out_options);if(this.intersectionLayer.features.length==0){return;}
var str=format.write(this.intersectionLayer.features[0]);intersection.title=this.intersectionTitle;intersection.featureWKT=str;intersection.maxFeatures=95;intersection.srs=map.getProjection();intersection.units=map.getUnits();var layers=[];for(var i=0;i<map.layers.length;++i){var olLayer=map.layers[i];var crossable=false;crossable=this.getProperty(olLayer,"crossable");if(olLayer.displayInLayerSwitcher&&olLayer.calculateInRange()&&crossable){var layer={};layer.name=olLayer.name;layer.layer=this.getProperty(olLayer,"typename")||this.getProperty(layer,"layers");layer.baseURL=Base64.decode(app.urlWFS);layer.nameSpace=app.namespaceGeoServerUrl;layer.columnGeom=this.getProperty(olLayer,"geometry_column");layer.columnCross=this.getProperty(olLayer,"cross_column");layers.push(layer);}}
intersection.layers=layers;if(layers.length>0)
intersectionsList.push(intersection);},getProperty:function(layer,prop){var property=prop;var result="";if(layer[property]!=undefined)
result=layer[property];else if(layer.params!=null&&layer.params[property]!=undefined)
result=layer.params[property];else if(layer.params!=null&&layer.params[property.toUpperCase()]!=undefined)
result=layer.params[property.toUpperCase()];return result;},fillSpec:null,getCurDpi:null,getCurLayout:null,getPageTitle:null,getDivTitle:null,getMapTitle:null};Ext.namespace('Municipia.controls');Ext.namespace('Municipia.controls.print');Municipia.controls.print.BaseWidget=function(options){Municipia.controls.print.BaseWidget.superclass.constructor.call(this,options);};Ext.extend(Municipia.controls.print.BaseWidget,Ext.Panel,{pageDrag:null,rotateHandle:null,layer:null,layout:'fit',initComponent:function(){Municipia.controls.print.BaseWidget.superclass.initComponent.call(this);this.addEvents("configloaded");this.addEvents("setUp");this.addEvents("tearDown");this.on('expand',this.setUp,this);this.on('collapse',this.tearDown,this);this.on('activate',this.setUp,this);this.on('deactivate',this.tearDown,this);this.on('enable',this.setUp,this);this.on('disable',this.tearDown,this);this.on('render',function(){var mask=this.mask=new Ext.LoadMask(this.body,{msg:OpenLayers.i18n('print.loadingConfig')});if(this.config==null){mask.show();}},this);if(!this.initPrint()){this.fillComponent();}},configReceived:function(config){Municipia.controls.print.Base.configReceived.call(this,config);this.fillComponent();this.doLayout();this.setUp();this.fireEvent("configloaded");},configFailed:function(){Municipia.controls.print.Base.configFailed.call(this);this.add({border:false,region:'center',html:OpenLayers.i18n('print.serverDown')});this.doLayout();this.config=false;},isReallyVisible:function(){if(!this.isVisible()||!this.body.isVisible(true))return false;var result=true;this.bubble(function(component){return result=result&&component.isVisible()&&(!component.body||component.body.isVisible());},this);return result;},setUp:function(){if(!this.disabled&&this.isReallyVisible()&&this.config&&!this.layer){this.map.addLayer(this.getOrCreateLayer());this.pageDrag.activate();this.fireEvent("setUp");}},tearDown:function(){if(this.config&&this.pageDrag&&this.layer){this.pageDrag.destroy();this.pageDrag=null;this.removeRotateHandle();this.layer.removeFeatures(this.layer.features);this.layer.destroy();this.layer=null;this.fireEvent("tearDown");}},getOrCreateLayer:function(){if(!this.layer){var self=this;this.layer=new OpenLayers.Layer.Vector("_Print"+this.getId(),{displayInLayerSwitcher:false,calculateInRange:function(){return true;}});this.pageDrag=new OpenLayers.Control.DragFeature(this.layer);this.map.addControl(this.pageDrag);var curFeature=null;this.pageDrag.onStart=function(feature){OpenLayers.Control.DragFeature.prototype.onStart.apply(this,arguments);curFeature=feature;if(feature.attributes.rotate){self.pageRotateStart(feature);}else{self.pageDragStart(feature);}};this.pageDrag.onDrag=function(feature){OpenLayers.Control.DragFeature.prototype.onDrag.apply(this,arguments);if(!feature)feature=curFeature;if(feature.attributes.rotate){self.pageRotated(feature);}};this.pageDrag.onComplete=function(feature){OpenLayers.Control.DragFeature.prototype.onComplete.apply(this,arguments);if(!feature)feature=curFeature;if(feature.attributes.rotate){self.pageRotateComplete(feature);}else{self.pageDragComplete(feature);}
curFeature=null;};this.afterLayerCreated();}
return this.layer;},pageRotateStart:function(feature){},pageRotated:function(feature){var center=feature.attributes.center;var pos=feature.geometry;var angle=Math.atan2(pos.x-center.x,pos.y-center.y)*180/Math.PI;var page=feature.attributes.page;page.attributes.rotation=angle;page.geometry.rotate(feature.attributes.prevAngle-angle,center);this.layer.drawFeature(page);this.setCurRotation(Math.round(angle));feature.attributes.prevAngle=angle;},pageRotateComplete:function(feature){this.createRotateHandle(feature.attributes.page);},pageDragStart:function(feature){this.removeRotateHandle();},removeRotateHandle:function(){if(this.rotateHandle){this.rotateHandle.destroy();this.rotateHandle=null;}},pageDragComplete:function(feature){if(this.getCurLayout().rotation){this.createRotateHandle(feature);}},createRotateHandle:function(feature){this.removeRotateHandle();var firstPoint=feature.geometry.components[0].components[2];var secondPoint=feature.geometry.components[0].components[3];var lon=(firstPoint.x+secondPoint.x)/2;var lat=(firstPoint.y+secondPoint.y)/2;var rotatePoint=new OpenLayers.Geometry.Point(lon,lat);var center=this.getCenterRectangle(feature);this.rotateHandle=new OpenLayers.Feature.Vector(rotatePoint,{rotate:true,page:feature,center:{x:center[0],y:center[1]},prevAngle:feature.attributes.rotation});this.layer.addFeatures(this.rotateHandle);},createRectangle:function(center,scale,layout,rotation){var extent=this.getExtent(center,scale,layout);var rect=extent.toGeometry();rect.rotate(-rotation,{x:center.lon,y:center.lat});var feature=new OpenLayers.Feature.Vector(rect,{rotation:rotation});this.layer.addFeatures(feature);return feature;},getCenterRectangle:function(rectangle){var center=rectangle.geometry.getBounds().getCenterLonLat();return[center.lon,center.lat];},getExtent:function(center,scale,layout){var unitsRatio=OpenLayers.INCHES_PER_UNIT[this.map.baseLayer.units];var size=layout.map;var w=size.width/72.0/unitsRatio*scale/2.0;var h=size.height/72.0/unitsRatio*scale/2.0;return new OpenLayers.Bounds(center.lon-w,center.lat-h,center.lon+w,center.lat+h);},fitScale:function(layout){var availsTxt=this.config.scales;if(availsTxt.length==0)return;var avails=[];for(var i=0;i<availsTxt.length;++i){avails.push(parseFloat(availsTxt[i].value));}
avails.sort(function(a,b){return a-b;});var bounds=this.map.getExtent();var unitsRatio=OpenLayers.INCHES_PER_UNIT[this.map.baseLayer.units];var size=layout.map;var targetScale=Math.min(bounds.getWidth()/size.width*72.0*unitsRatio,bounds.getHeight()/size.height*72.0*unitsRatio);var nearestScale=avails[0];for(var j=1;j<avails.length;++j){if(avails[j]<=targetScale){nearestScale=avails[j];}else{break;}}
return nearestScale;},print:function(){this.overrides[this.layer.name]={visibility:false};Municipia.controls.print.Base.print.call(this);delete this.overrides[this.layer.name];},getLayoutForName:function(layoutName){var layouts=this.config.layouts;for(var i=0;i<layouts.length;++i){var cur=layouts[i];if(cur.name==layoutName){return cur;}}},createScaleCombo:function(){var scaleStore=new Ext.data.JsonStore({root:"scales",fields:['name','value'],data:this.config});return new Ext.form.ComboBox({fieldLabel:OpenLayers.i18n('print.scale'),store:scaleStore,displayField:'name',valueField:'value',typeAhead:false,mode:'local',id:'scale_'+this.getId(),hiddenId:'scaleId_'+this.getId(),hiddenName:"scale",name:"scale",editable:false,triggerAction:'all',value:this.config.scales[this.config.scales.length-1].value});},createDpiCombo:function(name){if(this.config.dpis.length>1){var dpiStore=new Ext.data.JsonStore({root:"dpis",fields:['name','value'],data:this.config});return{fieldLabel:OpenLayers.i18n('print.dpi'),xtype:'combo',store:dpiStore,displayField:'name',valueField:'value',typeAhead:false,mode:'local',id:'dpi_'+this.getId(),hiddenId:'dpiId_'+this.getId(),hiddenName:name,name:name,editable:false,triggerAction:'all',value:this.config.dpis[0].value};}else{return{xtype:'hidden',name:name,value:this.config.dpis[0].value};}},createLayoutCombo:function(name){if(this.config.layouts.length>1){var layoutStore=new Ext.data.JsonStore({root:"layouts",fields:['name'],data:this.config});return new Ext.form.ComboBox({fieldLabel:OpenLayers.i18n('print.layout'),store:layoutStore,displayField:'name',valueField:'name',typeAhead:false,mode:'local',id:'layout_'+this.getId(),hiddenId:'layoutId_'+this.getId(),hiddenName:name,name:name,editable:false,triggerAction:'all',value:this.config.layouts[0].name});}else{return new Ext.form.Hidden({name:name,value:this.config.layouts[0].name});}},createRotationTextField:function(){var layouts=this.config.layouts;var hasRotation=false;for(var i=0;i<layouts.length&&!hasRotation;++i){hasRotation=layouts[i].rotation;}
if(hasRotation){var num=/^-?[0-9]+$/;return new Ext.form.TextField({fieldLabel:OpenLayers.i18n('print.rotation'),name:'rotation',value:'0',maskRe:/^[-0-9]$/,msgTarget:'side',validator:function(v){return num.test(v)?true:"Not a number";}});}else{return null;}},createIntersectionsCheckbox:function(){var layouts=this.config.layouts;var hasIntersections=false;for(var i=0;i<layouts.length&&!hasIntersections;++i){hasIntersections=layouts[i].intersection;}
if(hasIntersections){return new Ext.form.Checkbox({fieldLabel:OpenLayers.i18n('print.intersections'),name:'/intersections',boxLabel:' ',checked:false});}else{return null;}},fillComponent:null,afterLayerCreated:null,fillSpec:null,setCurRotation:null});OpenLayers.Util.applyDefaults(Municipia.controls.print.BaseWidget.prototype,Municipia.controls.print.Base);Ext.namespace('Municipia.controls');Ext.namespace('Municipia.controls.print');Municipia.controls.print.MultiPage=Ext.extend(Municipia.controls.print.BaseWidget,{formConfig:null,columns:null,zoomToExtentEnabled:true,grid:null,printButton:null,freezeGeometryRefresh:false,fillComponent:function(){var innerPanel=this.add({border:false,layout:'border',id:this.getId()+'InnerPanel'});this.createGlobalForm(innerPanel);this.createGrid(innerPanel);},setUp:function(){if(this.config){if(Ext.isGecko3){var buggyDiv=this.formPanel.getEl().parent();buggyDiv.setStyle("position","absolute");setTimeout(function(){buggyDiv.setStyle("position","relative");},20);}
Municipia.controls.print.BaseWidget.prototype.setUp.call(this);}},createGlobalForm:function(innerPanel){var formConfig=OpenLayers.Util.extend({region:'south',bodyStyle:'padding: 7px 0 0 0;',border:false,bodyBorder:false,id:this.getId()+"formPanel"},this.formConfig);var formPanel=this.formPanel=new Ext.form.FormPanel(formConfig);var layout=this.createLayoutCombo("layout");if(this.config.layouts.length>1){layout.on('select',this.layoutChanged,this);}
formPanel.add(layout);formPanel.add(this.createDpiCombo("dpi"));this.printButton=formPanel.addButton({text:OpenLayers.i18n('print.print'),scope:this,handler:this.print,disabled:true});innerPanel.add(formPanel);},createGrid:function(innerPanel){var scale=this.createScaleCombo();scale.on('select',this.updateCurrentRectangle,this);var self=this;var columns=[{header:OpenLayers.i18n('print.scale'),dataIndex:'scale',editor:scale,renderer:function(value){return self.getScaleName(value);}}];var rotation=this.createRotationTextField();if(rotation!=null){columns.push({header:OpenLayers.i18n('print.rotation'),dataIndex:'rotation',editor:rotation,id:this.getId()+'_rotation',hidden:!this.config.layouts[0].rotation});}
if(this.columns){columns.push.apply(columns,this.columns);}
var pageFields=[];for(var i=0;i<columns.length;++i){pageFields.push({name:columns[i].dataIndex});}
var pages=new Ext.data.SimpleStore({fields:pageFields});var grid=this.grid=new Ext.grid.EditorGridPanel({region:'center',border:false,id:this.getId()+'PagesGrid',autoScroll:true,enableColumnHide:false,enableHdMenu:false,store:pages,viewConfig:{forceFit:true,emptyText:OpenLayers.i18n('print.noPage')},sm:new Ext.grid.RowSelectionModel({singleSelect:true}),clicksToEdit:1,columns:columns,bbar:[{text:OpenLayers.i18n('print.addPage'),scope:this,handler:this.addPage},{text:OpenLayers.i18n('print.remove'),scope:this,handler:this.removeSelected,id:this.getId()+"_remove",disabled:true},{text:OpenLayers.i18n('print.clearAll'),scope:this,handler:this.clearPages}]});innerPanel.add(grid);grid.getSelectionModel().addListener('selectionchange',this.selectionChanged,this);grid.getStore().addListener('update',function(store,record,operation){if(!this.freezeGeometryRefresh){this.updateRectangle(record);this.updatePrintLayerStyle();}},this);grid.getStore().addListener('remove',function(store,record,index){this.layer.removeFeatures(record.data.rectangle);this.removeRotateHandle();if(store.getCount()==0){this.printButton.disable();}},this);grid.getStore().addListener('clear',function(){this.layer.removeFeatures(this.layer.features);this.printButton.disable();},this);},selectionChanged:function(){this.updatePrintLayerStyle();var removeButton=Ext.getCmp(this.getId()+'_remove');var selected=this.grid.getSelectionModel().getSelected();if(selected){if(this.zoomToExtentEnabled){var bounds=selected.data.rectangle.geometry.getBounds().clone();bounds.extend(this.map.getExtent());this.map.zoomToExtent(bounds);}
removeButton.enable();var layoutData=this.getCurLayout();if(layoutData.rotation){this.createRotateHandle(selected.data.rectangle);}}else{removeButton.disable();}},updatePrintLayerStyle:function(){var selected=this.grid.getSelectionModel().getSelected();var theOne=null;for(var i=0;i<this.layer.features.length;++i){var feature=this.layer.features[i];var isTheOne=feature.data.record==selected;feature.style=OpenLayers.Feature.Vector.style[isTheOne?'select':'default'];if(isTheOne&&i!=this.layer.features.length-1){theOne=feature;this.layer.removeFeatures(feature);}}
if(theOne)this.layer.addFeatures(theOne);this.layer.redraw();},addPage:function(){var layoutData=this.getCurLayout();var scale=this.fitScale(layoutData);var feature=this.createRectangle(this.map.getCenter(),scale,layoutData,0);var newPage={scale:scale,rotation:0,rectangle:feature};for(var i=0;i<this.columns.length;++i){var cur=this.columns[i].dataIndex;if(newPage[cur]==null){newPage[cur]="";}}
var pages=this.grid.getStore();var record=new pages.recordType(newPage);pages.add(record);feature.data.record=record;this.grid.getSelectionModel().selectLastRow();this.printButton.enable();},clearPages:function(){this.grid.stopEditing();this.grid.getStore().removeAll();},removeSelected:function(){this.grid.stopEditing();var record=this.grid.getSelectionModel().getSelected();this.grid.getStore().remove(record);},layoutChanged:function(){this.grid.getStore().each(function(record){this.updateRectangle(record);},this);this.updatePrintLayerStyle();var cm=this.grid.getColumnModel();var rotationIndex=cm.getIndexById(this.id+'_rotation');if(rotationIndex>=0){var layoutData=this.getCurLayout();cm.setHidden(rotationIndex,!layoutData.rotation);}},updateCurrentRectangle:function(){this.updateRectangle(this.grid.getSelectionModel().getSelected());this.updatePrintLayerStyle();},updateRectangle:function(record){this.grid.stopEditing();this.layer.removeFeatures(record.data.rectangle);var layoutData=this.getCurLayout();var scale=record.get('scale');var angle=layoutData.rotation?record.get('rotation'):0;var center=record.data.rectangle.geometry.getBounds().getCenterLonLat();var feature=this.createRectangle(center,scale,layoutData,angle);feature.data.record=record;record.data.rectangle=feature;var sm=this.grid.getSelectionModel();if(sm.getSelected()==record){if(layoutData.rotation){this.createRotateHandle(feature);}else{this.removeRotateHandle();}}},afterLayerCreated:function(){if(this.grid.getStore().getCount()!=0){this.grid.getStore().each(function(record){this.layer.addFeatures(record.data.rectangle);},this);this.updatePrintLayerStyle();var sm=this.grid.getSelectionModel();var selected=sm.getSelected();if(selected&&this.getCurLayout().rotation){this.createRotateHandle(selected.data.rectangle);}}else{this.addPage();}},pageRotateStart:function(feature){Municipia.controls.print.BaseWidget.prototype.pageRotateStart.call(this,feature);this.grid.stopEditing();},pageDragStart:function(feature){Municipia.controls.print.BaseWidget.prototype.pageDragStart.call(this,feature);var prev=this.zoomToExtentEnabled;var sm=this.grid.getSelectionModel();if(sm.getSelected()!=feature.data.record){this.zoomToExtentEnabled=false;sm.selectRecords([feature.data.record]);this.zoomToExtentEnabled=prev;}
this.grid.stopEditing();},getCurDpi:function(){var values=this.formPanel.getForm().getValues();return values["dpi"];},getCurLayoutName:function(){var values=this.formPanel.getForm().getValues();return values['layout'];},getCurLayout:function(){var layout=this.getCurLayoutName();return this.getLayoutForName(layout);},setCurRotation:function(rotation){var selected=this.grid.getSelectionModel().getSelected();this.freezeGeometryRefresh=true;selected.set('rotation',rotation);this.freezeGeometryRefresh=false;},fillSpec:function(printCommand){var params=printCommand.spec;var layout=this.getCurLayout();this.formPanel.getForm().items.each(function(cur){params[cur.getName()]=cur.getValue();},this);this.grid.getStore().each(function(record){var page={};for(var key in record.data){if(key=='rectangle'){page.center=this.getCenterRectangle(record.data.rectangle);}else if(key=='rotation'&&!layout.rotation){}else{page[key]=record.data[key];}}
params.pages.push(page);},this);},getScaleName:function(scaleValue){var scales=this.config.scales;for(var i=0;i<scales.length;++i){var cur=scales[i];if(cur.value==scaleValue){return cur.name;}}}});Ext.reg('print-multi',Municipia.controls.print.MultiPage);Ext.namespace('Municipia.controls');Ext.namespace('Municipia.controls.print');Municipia.controls.print.PrintAction=function(config){var actionParams=OpenLayers.Util.extend({iconCls:'print-action',tooltip:OpenLayers.i18n('print.print-tooltip'),handler:this.handler,scope:this},config);Municipia.controls.print.PrintAction.superclass.constructor.call(this,actionParams);OpenLayers.Util.extend(this,config);this.mask=new Ext.LoadMask(this.map.div,{msg:OpenLayers.i18n('print.loadingConfig')});if(this.overrides==null){this.overrides={};}};Ext.extend(Municipia.controls.print.PrintAction,Ext.Action,{handler:function(){if(!this.printing){this.print();}},fillSpec:function(printCommand){var singlePage={center:[this.map.getCenter().lon,this.map.getCenter().lat],scale:Math.round(this.map.getScale())};var params=printCommand.spec;params.pages.push(singlePage);params.layout=this.getCurLayout();params.pageTitle=this.getPageTitle();params.divTitle=this.getDivTitle();params.mapTitle=this.getMapTitle();}});OpenLayers.Util.applyDefaults(Municipia.controls.print.PrintAction.prototype,Municipia.controls.print.Base);Ext.reg('print-action',Municipia.controls.print.PrintAction);Ext.namespace('Municipia.controls');Ext.namespace('Municipia.controls.print');Municipia.controls.print.PrintPDM=function(config){var actionParams=OpenLayers.Util.extend({iconCls:'print-pdm',tooltip:OpenLayers.i18n('print.print-pdm'),handler:this.handler,scope:this},config);Municipia.controls.print.PrintPDM.superclass.constructor.call(this,actionParams);OpenLayers.Util.extend(this,config);this.mask=new Ext.LoadMask(this.map.div,{msg:OpenLayers.i18n('print.loadingConfig')});this.overrides=this.fixOverrides(this.overrides,this.map);this.setLayersPrint();this.flagPDM=true;if(this.overrides==null){this.overrides={};}};Ext.extend(Municipia.controls.print.PrintPDM,Ext.Action,{win:null,layersPrint:null,grid:null,handler:function(){if(!this.printing){this.showWin();}},fillSpec:function(printCommand){var params=printCommand.spec;if(this.layersPrint!=null){var mapas=[];var listlayersPrint=[];for(name in this.layersPrint){listlayersPrint.push(this.layersPrint[name]);}
for(var i=0;i<(listlayersPrint.length-1);i++)
for(var j=i+1;j<listlayersPrint.length;j++)
if(listlayersPrint[j].ordem<listlayersPrint[i].ordem){var dummy=listlayersPrint[i];listlayersPrint[i]=listlayersPrint[j];listlayersPrint[j]=dummy;}
var newlayersPrint={};for(var i=0;i<listlayersPrint.length;i++){newlayersPrint[listlayersPrint[i].idprintpdm]=listlayersPrint[i];}
this.layersPrint=newlayersPrint;for(name in this.layersPrint){var cur=this.layersPrint[name];if(cur.visibility){var mapa=chain(params,params);mapa.pages=[];var newPage={scale:cur.scale,rotation:0,center:[this.map.getCenter().lon,this.map.getCenter().lat]};mapa.pages.push(newPage);var layers=mapa.layers;var newLayers=[];for(var i=0;i<layers.length;i++){if((layers[i].customParams&&layers[i].customParams.idprintpdm!=undefined&&layers[i].customParams.idprintpdm==cur.idprintpdm)||(layers[i].customParams&&layers[i].customParams.idprintpdm!=undefined&&layers[i].customParams.idprintpdm.indexOf("_")==0)){newLayers.push(layers[i]);}}
mapa.layers=newLayers;mapa.layout=cur.layout==""?this.getCurLayout():cur.layout;mapa.pageTitle=this.getPageTitle();mapa.divTitle=this.getDivTitle();mapa.mapTitle=cur.mapTitle;mapas.push(mapa);}}
printCommand.maps2Print=mapas;}},fixOverrides:function(overrides,map){overrides=OpenLayers.Util.extend({},overrides);var hasPDM=false;var name;var value;for(var i=0;i<map.layers.length;++i){var olLayer=map.layers[i];var type=olLayer.CLASS_NAME;if(olLayer.id_layer)
name=new String(olLayer.id_layer).camelize();else{if(olLayer.CLASS_NAME=="OpenLayers.Layer.Vector")
name=new String("_"+olLayer.name).camelize();else
name=new String(olLayer.name).camelize();}
if(name){if(!overrides[name]){overrides[name]={};}
value=this.getProperty(olLayer,"printpdm");if(type=="OpenLayers.Layer.Vector")
value=true;overrides[name].visibility=(value==""?false:value);overrides[name].idprintpdm=name;}}
return overrides;},setLayersPrint:function(){var map=this.map;var hasPDM=false;var name;var value;for(var i=0;i<map.layers.length;++i){var olLayer=map.layers[i];if(olLayer.id_layer)
name=new String(olLayer.id_layer).camelize();else{if(olLayer.CLASS_NAME=="OpenLayers.Layer.Vector")
name=new String("_"+olLayer.name).camelize();else
name=new String(olLayer.name).camelize();}
if(name){value=this.getProperty(olLayer,"printpdm");if(value){if(this.layersPrint==null)
this.layersPrint={};if(!this.layersPrint[name]){this.layersPrint[name]={};this.layersPrint[name].idprintpdm=name;this.layersPrint[name].name=olLayer.name;this.layersPrint[name].scale=this.getProperty(olLayer,"scale_printpdm");this.layersPrint[name].mapTitle=this.getProperty(olLayer,"maptitle_printpdm");this.layersPrint[name].layout=this.getProperty(olLayer,"layout_printpdm");this.layersPrint[name].visibility=(value==""?false:value);this.layersPrint[name].ordem=this.getProperty(olLayer,"ordem_print_pdm");}}}}},showWin:function(){if(this.layersPrint==null){Ext.MessageBox.alert(OpenLayers.i18n('print.information'),OpenLayers.i18n('print.pdm.nolayers'),null);return;}
if(!this.win){this.win=new Ext.Window({title:OpenLayers.i18n('print.print'),layout:'fit',closeAction:'hide',plain:true,modal:true,resizable:false,width:250,autoHeight:true,autoScroll:false,items:[{layout:'column',border:false,autoHeight:true,defaults:{columnWidth:'1.0',border:false},items:[{bodyStyle:'padding:5px;',items:{xtype:'fieldset',title:OpenLayers.i18n('print.pdm.fieldset'),autoHeight:true,defaultType:'checkbox',items:this.getItemsWin()}}]}],buttons:[{text:OpenLayers.i18n('print.pdm.btnprint'),id:'pdm_btn_imprimir',disabled:this.layersPrint==null?true:false,control_print:this,handler:function(){for(name in this.control_print.layersPrint){var cur=this.control_print.layersPrint[name];this.control_print.overrides[name].visibility=cur.visibility;}
this.control_print.print();this.ownerCt.hide();}},{text:OpenLayers.i18n('print.pdm.btncancel'),id:'pdm_btn_cancelar',handler:function(){this.ownerCt.hide();}}]});}
this.win.show();},getItemsWin:function(){var items=[];if(this.layersPrint!=null){for(name in this.layersPrint){var cur=this.layersPrint[name];var item={checked:true,fieldLabel:cur.name,boxLabel:'(1:'+cur.scale+')',name:'pdm_'+cur.idprintpdm,id:cur.idprintpdm,layersPrint:this.layersPrint,listeners:{'check':function(checkbox,checked){var btn=Ext.getCmp('pdm_btn_imprimir');var cur=this.layersPrint[checkbox.id];if(cur)
cur.visibility=checked;if(checked&&btn.disabled){btn.enable();}else if(!checked){var flagEnable=false;for(name in this.layersPrint){var cur=this.layersPrint[name];var check=Ext.getCmp(cur.idprintpdm);cur.visibility=check.getValue();flagEnable=flagEnable||check.getValue();}
if(!flagEnable){btn.disable();}}}}};items.push(item);}}
return items;}});OpenLayers.Util.applyDefaults(Municipia.controls.print.PrintPDM.prototype,Municipia.controls.print.Base);Ext.reg('print-pdm',Municipia.controls.print.PrintPDM);Ext.namespace('Municipia.controls');Ext.namespace('Municipia.controls.print');Municipia.controls.print.PrintPIP=function(config){var actionParams=OpenLayers.Util.extend({iconCls:'print-pip',tooltip:OpenLayers.i18n('print.print-tooltipPIP'),handler:this.handler,scope:this},config);Municipia.controls.print.PrintPIP.superclass.constructor.call(this,actionParams);OpenLayers.Util.extend(this,config);this.mask=new Ext.LoadMask(this.map.div,{msg:OpenLayers.i18n('print.loadingConfig')});this.overrides=this.fixOverrides(this.overrides,this.map);if(this.overrides==null){this.overrides={};}};Ext.extend(Municipia.controls.print.PrintPIP,Ext.Action,{handler:function(){if(!this.printing){if(!(this.intersectionLayer&&this.intersectionLayer.features.length==1)){Ext.MessageBox.alert(OpenLayers.i18n('print.information'),OpenLayers.i18n('print.pip.errorFeature'),null);return;}
this.print();}},fillSpec:function(printCommand){var singlePage={center:[this.intersectionLayer.features[0].geometry.bounds.getCenterLonLat().lon,this.intersectionLayer.features[0].geometry.bounds.getCenterLonLat().lat],scale:Math.round(this.map.getScale())};var params=printCommand.spec;params.pages.push(singlePage);params.layout=this.getCurLayout();params.pageTitle=this.getPageTitle();params.divTitle=this.getDivTitle();params.mapTitle=this.getMapTitle();params.intersections=true;},fixOverrides:function(overrides,map){overrides=OpenLayers.Util.extend({},overrides);var name;for(var i=0;i<map.layers.length;++i){var olLayer=map.layers[i];if(olLayer.id_layer)
name=new String(olLayer.id_layer).camelize();else{if(olLayer.CLASS_NAME=="OpenLayers.Layer.Vector")
name=new String("_"+olLayer.name).camelize();else
name=new String(olLayer.name).camelize();}
if(name){if(!overrides[name]){overrides[name]={};}
var crossable=false;crossable=this.getProperty(olLayer,"crossable");overrides[name].visibility=crossable;}}
return overrides;}});OpenLayers.Util.applyDefaults(Municipia.controls.print.PrintPIP.prototype,Municipia.controls.print.Base);Ext.reg('print-pip',Municipia.controls.print.PrintPIP);Municipia.PrintProtocol=OpenLayers.Class({config:null,spec:null,params:null,initialize:function(map,config,overrides,dpi,params,flagPDM){this.config=config;this.spec={pages:[],layout:'A4 portrait',pageTitle:'',divTitle:'',mapTitle:'',titleLegenda:''};this.addMapParams(overrides,map,dpi,flagPDM);this.params=params;},getAllInOneUrl:function(){var json=new OpenLayers.Format.JSON();var result=this.config.printURL+"?spec="+
json.write(this.encodeForURL(this.spec));if(this.params){result+="&"+OpenLayers.Util.getParameterString(this.params);}
return result;},createPDF:function(success,popup,failure,context){var newSpec={};if(this.maps2Print!=null){newSpec.maps=this.maps2Print;}else{newSpec.maps=[];newSpec.maps.push(this.spec);}
var specTxt=new OpenLayers.Format.JSON().write(newSpec);OpenLayers.Console.info(specTxt);try{var charset="UTF-8";var params=OpenLayers.Util.applyDefaults({},this.params);var path=this.config.createURL;if(path.lastIndexOf('?')!=-1)
{path=Base64.encode(path.substring(0,path.lastIndexOf('?')))+path.substring(path.lastIndexOf('?'));}
else
{path=Base64.encode(path)+"?";}
OpenLayers.Request.POST({url:app.proxyWFS+path,data:"spec="+escape(specTxt),params:params,headers:{'Content-type':"application/x-www-form-urlencoded",'Content-length':1,'Connection':"close"},callback:function(request){if(request.status>=200&&request.status<300){var json=new OpenLayers.Format.JSON();var answer=json.read(request.responseText);if(answer==null){if(request.responseXML&&request.responseXML.childNodes.length>0)
answer=json.read(request.responseXML.firstChild.textContent);}
if(answer&&answer.getURL){this.openPdf(answer,success,popup,context);}else{failure.call(context,request);}}else{failure.call(context,request);}},scope:this});}catch(err){OpenLayers.Console.warn("Cannot request the print service by AJAX. You must set "+"the 'OpenLayers.ProxyHost' variable. Fallback to GET method");window.open(this.getAllInOneUrl());success.call(context,err);}},openPdf:function(answer,success,popup,context){OpenLayers.Console.info(answer.getURL);popup.call(context,answer);},fixOverrides:function(overrides,map){overrides=OpenLayers.Util.extend({},overrides);var hasOverview=false;var name;for(var i=0;i<map.layers.length;++i){var olLayer=map.layers[i];if(olLayer.id_layer)
name=new String(olLayer.id_layer).camelize();else{if(olLayer.CLASS_NAME=="OpenLayers.Layer.Vector")
name=new String("_"+olLayer.name).camelize();else
name=new String(olLayer.name).camelize();}
if(!overrides[name]){overrides[name]={};}else if(overrides[name].overview){hasOverview=true;}}
if(hasOverview){for(name in overrides){var cur=overrides[name];if(!cur.overview){cur.overview=false;}}}
return overrides;},addMapParams:function(overrides,map,dpi,flagPDM){var spec=this.spec;spec.dpi=dpi;spec.units=map.baseLayer.units;spec.srs=map.baseLayer.projection.getCode();var layers=spec.layers=[];overrides=this.fixOverrides(overrides,map);var name;for(var i=0;i<map.layers.length;++i){var olLayer=map.layers[i];if(olLayer.id_layer)
name=new String(olLayer.id_layer).camelize();else{if(olLayer.CLASS_NAME=="OpenLayers.Layer.Vector")
name=new String("_"+olLayer.name).camelize();else
name=new String(olLayer.name).camelize();}
var layerOverrides=OpenLayers.Util.extend({},overrides[name]);OpenLayers.Util.extend(layerOverrides,layerOverrides[dpi]);if((olLayer.getVisibility()&&layerOverrides.visibility!==false)||layerOverrides.visibility===true){var type=olLayer.CLASS_NAME;var handler=Municipia.PrintProtocol.SUPPORTED_TYPES[type];if(handler){if(type=="OpenLayers.Layer.Vector"&&olLayer.features.length==0)
continue;if(type=="OpenLayers.Layer.Markers"&&olLayer.markers.length==0)
continue;var layer=handler.call(this,olLayer);if(layer){this.applyOverrides(layer,layerOverrides);if(olLayer.isBaseLayer){layers.unshift(layer);}else if(olLayer.inRange||flagPDM){layers.push(layer);}}}else if(!handler){OpenLayers.Console.error("Don't know how to print a layer of type "+type+" ("+olLayer.name+")");}}}},applyOverrides:function(layer,overrides){for(var key in overrides){if(isNaN(parseInt(key))){var value=overrides[key];if(key=='layers'||key=='styles'){value=Municipia.Util.fixArray(value);}
if(key=="visibility"){}else if(layer[key]!=null||key=="overview"){layer[key]=value;}else{layer.customParams[key]=value;}}}},convertLayer:function(olLayer){var url=olLayer.url;if(url instanceof Array){url=url[0];}
if(url!=undefined){if(url.lastIndexOf(app.proxyWMS)>-1){url=url.substring((url.lastIndexOf(app.proxyWMS)+app.proxyWMS.length),url.length);if(url.lastIndexOf('?')!=-1)
{url=Base64.decode(url.substring(0,url.lastIndexOf('?')))+url.substring(url.lastIndexOf('?'));}
else
{url=Base64.decode(url);}}else if(url.lastIndexOf(app.proxyWFS)>-1){url=url.substring((url.lastIndexOf(app.proxyWFS)+app.proxyWFS.length),url.length);if(url.lastIndexOf('?')!=-1)
{url=Base64.decode(url.substring(0,url.lastIndexOf('?')))+url.substring(url.lastIndexOf('?'));}
else
{url=Base64.decode(url);}}}
return{baseURL:Municipia.Util.relativeToAbsoluteURL(url),opacity:(olLayer.opacity!=null)?olLayer.opacity:1.0,singleTile:olLayer.singleTile,customParams:{}};},convertWMSLayer:function(olLayer){var layer=OpenLayers.Util.extend(this.convertLayer(olLayer),{type:'WMS',layers:Municipia.Util.fixArray(olLayer.params.LAYERS),format:olLayer.params.FORMAT||olLayer.DEFAULT_PARAMS.format,styles:Municipia.Util.fixArray(olLayer.params.STYLES||olLayer.DEFAULT_PARAMS.styles)});for(var paramName in olLayer.params){var paramNameLow=paramName.toLowerCase();if(olLayer.DEFAULT_PARAMS[paramNameLow]==null&&paramNameLow!='layers'&&paramNameLow!='width'&&paramNameLow!='height'&&paramNameLow!='srs'){layer.customParams[paramName]=olLayer.params[paramName];}}
return layer;},convertMapServerLayer:function(olLayer){var layer=OpenLayers.Util.extend(this.convertLayer(olLayer),{type:'MapServer',layers:Municipia.Util.fixArray(olLayer.params.LAYERS||olLayer.params.layers),format:olLayer.params.FORMAT||olLayer.params.format||olLayer.DEFAULT_PARAMS.format});for(var paramName in olLayer.params){var paramNameLow=paramName.toLowerCase();if(olLayer.DEFAULT_PARAMS[paramNameLow]==null&&paramNameLow!='layers'&&paramNameLow!='format'&&paramNameLow!='width'&&paramNameLow!='height'&&paramNameLow!='srs'){layer.customParams[paramName]=olLayer.params[paramName];}}
return layer;},convertTileCacheLayer:function(olLayer){return OpenLayers.Util.extend(this.convertLayer(olLayer),{type:'TileCache',layer:olLayer.layername,maxExtent:olLayer.maxExtent.toArray(),tileSize:[olLayer.tileSize.w,olLayer.tileSize.h],extension:olLayer.extension,resolutions:olLayer.resolutions});},convertTMSLayer:function(olLayer){var ext=this.convertLayer(olLayer);ext.baseURL=ext.baseURL+"1.0.0/";return OpenLayers.Util.extend(ext,{type:'TMS',layer:olLayer.layername,maxExtent:olLayer.maxExtent.toArray(),tileSize:[olLayer.tileSize.w,olLayer.tileSize.h],extension:olLayer.type,resolutions:olLayer.map.baseLayer.resolutions});},convertImageLayer:function(olLayer){var url=olLayer.getURL(olLayer.extent);return{type:'Image',baseURL:Municipia.Util.relativeToAbsoluteURL(url),opacity:(olLayer.opacity!=null)?olLayer.opacity:1.0,extent:olLayer.extent.toArray(),pixelSize:[olLayer.size.w,olLayer.size.h],name:olLayer.name};},convertVectorLayer:function(olLayer){var olFeatures=olLayer.features;var features=[];var styles={};var formatter=new OpenLayers.Format.GeoJSON();var nextId=1000000;var style=null;var styleName;for(var i=0;i<olFeatures.length;++i){var feature=olFeatures[i];if(style==null){if(feature.icon){style=new OpenLayers.Style({});style.pointRadius=5;style.externalGraphic=Municipia.Util.relativeToAbsoluteURL(feature.icon.url);}else{style=feature.style||olLayer.style||olLayer.styleMap.createSymbolizer(feature,feature.renderIntent);}
style._printId=styleName=nextId++;styles[styleName]=style;}
var featureGeoJson=formatter.extract.feature.call(formatter,feature);featureGeoJson.properties=OpenLayers.Util.extend({_style:styleName},featureGeoJson.properties);for(var cur in featureGeoJson.properties){var curVal=featureGeoJson.properties[cur];if(curVal instanceof Object&&!(curVal instanceof String)){delete featureGeoJson.properties[cur];}}
features.push(featureGeoJson);}
for(var key in styles){delete styles[key]._printId;}
var geoJson={"type":"FeatureCollection","features":features};return OpenLayers.Util.extend(this.convertLayer(olLayer),{type:'Vector',styles:styles,styleProperty:'_style',geoJson:geoJson,name:olLayer.name,opacity:(olLayer.opacity!=null)?olLayer.opacity:1.0});},convertMarkersLayer:function(olLayer){var olFeatures=olLayer.markers;var features=[];var styles={};var formatter=new OpenLayers.Format.GeoJSON();var nextId=1000000;var style=null;var styleName;for(var i=0;i<olFeatures.length;++i){var feature=olFeatures[i];if(style==null){if(feature.icon){style=new OpenLayers.Style({});style.pointRadius=5;style.externalGraphic=Municipia.Util.relativeToAbsoluteURL(feature.icon.url);}else{style=feature.style||olLayer.style||olLayer.styleMap.createSymbolizer(feature,feature.renderIntent);}
style._printId=styleName=nextId++;styles[styleName]=style;}
var geom=new OpenLayers.Geometry.Point(feature.lonlat.lon,feature.lonlat.lat);var featureAux=new OpenLayers.Feature.Vector();featureAux.geometry=geom;var featureGeoJson=formatter.extract.feature.call(formatter,featureAux);featureGeoJson.id=feature.events.element.id;featureGeoJson.properties=feature.attributes==undefined?{}:feature.attributes;featureGeoJson.properties=OpenLayers.Util.extend({_style:styleName},featureGeoJson.properties);for(var cur in featureGeoJson.properties){var curVal=featureGeoJson.properties[cur];if(curVal instanceof Object&&!(curVal instanceof String)){delete featureGeoJson.properties[cur];}}
features.push(featureGeoJson);}
for(var key in styles){delete styles[key]._printId;}
var geoJson={"type":"FeatureCollection","features":features};return OpenLayers.Util.extend(this.convertLayer(olLayer),{type:'Vector',styles:styles,styleProperty:'_style',geoJson:geoJson,name:olLayer.name,opacity:(olLayer.opacity!=null)?olLayer.opacity:1.0});},convertWFSLayer:function(olLayer){var olFeatures=olLayer.markers||olLayer.features;var features=[];var styles={};var formatter=new OpenLayers.Format.GeoJSON();var nextId=1;var style=null;var styleName;for(var i=0;i<olFeatures.length;++i){var feature=olFeatures[i];style=null;if(style==null){if(feature.icon){style=new OpenLayers.Style({});style.pointRadius=5;style.externalGraphic=Municipia.Util.relativeToAbsoluteURL(feature.icon.url);}else{style=feature.style||olLayer.style||olLayer.styleMap.createSymbolizer(feature,feature.renderIntent);if(style.pointRadius){style.graphicWidth=style.pointRadius;style.graphicHeight=style.pointRadius;}}
style._printId=styleName=nextId++;styles[styleName]=style;}
var point=new OpenLayers.Geometry.Point(feature.geometry.x,feature.geometry.y);var pointFeature=new OpenLayers.Feature.Vector(point,null,null);var featureGeoJson=formatter.extract.feature.call(formatter,pointFeature);featureGeoJson.properties=OpenLayers.Util.extend({_style:styleName},featureGeoJson.properties);for(var cur in featureGeoJson.properties){var curVal=featureGeoJson.properties[cur];if(curVal instanceof Object&&!(curVal instanceof String)){delete featureGeoJson.properties[cur];}}
features.push(featureGeoJson);}
for(var key in styles){delete styles[key]._printId;}
var geoJson={"type":"FeatureCollection","features":features};return OpenLayers.Util.extend(this.convertLayer(olLayer),{type:'Vector',styles:styles,styleProperty:'_style',geoJson:geoJson,name:olLayer.name,opacity:(olLayer.opacity!=null)?olLayer.opacity:1.0});},encodeForURL:function(cur){if(cur==null)return null;var type=typeof cur;Ext.type(cur);if(type=='string'){return escape(cur.replace(/[\n]/g,"\\n"));}else if(type=='object'&&cur.constructor==Array){var array=[];for(var i=0;i<cur.length;++i){var val=this.encodeForURL(cur[i]);if(val!=null)array.push(val);}
return array;}else if(type=='object'&&cur.CLASS_NAME&&cur.CLASS_NAME=='OpenLayers.Feature.Vector'){return new OpenLayers.Format.WKT().write(cur);}else if(type=='object'){var hash={};for(var j in cur){var val2=this.encodeForURL(cur[j]);if(val2!=null)hash[j]=val2;}
return hash;}else{return cur;}},CLASS_NAME:"Municipia.PrintProtocol"});Municipia.PrintProtocol.getConfiguration=function(url,success,failure,context,params){try{params=OpenLayers.Util.extend(params,{url:url});OpenLayers.Request.GET({url:url,params:params,callback:function(request){if(request.status>=200&&request.status<300){var json=new OpenLayers.Format.JSON();var answer=json.read(request.responseText);if(answer){success.call(context,answer);}else{failure.call(context,request);}}else{failure.call(context,request);}}});}catch(err){failure.call(context,err);}};Municipia.PrintProtocol.IGNORED=function(){return null;};Municipia.PrintProtocol.SUPPORTED_TYPES={'OpenLayers.Layer':Municipia.PrintProtocol.IGNORED,'OpenLayers.Layer.WMS':Municipia.PrintProtocol.prototype.convertWMSLayer,'OpenLayers.Layer.WMS.Untiled':Municipia.PrintProtocol.prototype.convertWMSLayer,'OpenLayers.Layer.TileCache':Municipia.PrintProtocol.prototype.convertTileCacheLayer,'OpenLayers.Layer.TMS':Municipia.PrintProtocol.prototype.convertTMSLayer,'OpenLayers.Layer.Vector':Municipia.PrintProtocol.prototype.convertVectorLayer,'OpenLayers.Layer.Markers':Municipia.PrintProtocol.prototype.convertMarkersLayer,'OpenLayers.Layer.WFS':Municipia.PrintProtocol.prototype.convertWFSLayer,'OpenLayers.Layer.GML':Municipia.PrintProtocol.prototype.convertVectorLayer,'OpenLayers.Layer.PointTrack':Municipia.PrintProtocol.prototype.convertVectorLayer,'OpenLayers.Layer.MapServer':Municipia.PrintProtocol.prototype.convertMapServerLayer,'OpenLayers.Layer.MapServer.Untiled':Municipia.PrintProtocol.prototype.convertMapServerLayer,'OpenLayers.Layer.Image':Municipia.PrintProtocol.prototype.convertImageLayer};Ext.namespace('Municipia.controls');Ext.namespace('Municipia.controls.print');Municipia.controls.print.SimpleForm=Ext.extend(Municipia.controls.print.BaseWidget,{formConfig:null,wantResetButton:true,scale:null,rectangle:null,rotation:null,infoPanel:null,fillComponent:function(){var formConfig=OpenLayers.Util.extend({border:false,bodyBorder:false},this.formConfig);var formPanel=this.formPanel=new Ext.form.FormPanel(formConfig);var layout=this.createLayoutCombo("/layout");if(this.config.layouts.length>1){layout.on('select',this.updateRectangle,this);}
formPanel.add(layout);formPanel.add(this.createDpiCombo("/dpi"));this.scale=formPanel.add(this.createScaleCombo());this.scale.on('select',this.updateRectangle,this);this.rotation=this.createRotationTextField();if(this.rotation!=null){this.rotation.setDisabled(!this.config.layouts[0].rotation);formPanel.add(this.rotation);this.rotation.on('change',function(){if(!this.rotation.isValid(true)){this.rotation.setValue(0);}
this.updateRectangle();},this);}
var intersections=this.createIntersectionsCheckbox();if(intersections!=null){formPanel.add(intersections);}
if(this.infoPanel!=null){formPanel.add(this.infoPanel);}
if(this.wantResetButton){formPanel.addButton({text:OpenLayers.i18n('print.resetPos'),scope:this,handler:function(){this.setCurScale(this.fitScale(this.getCurLayout()));if(this.rotation){this.setCurRotation(0);}
this.createTheRectangle();}});}
formPanel.addButton({text:OpenLayers.i18n('print.print'),scope:this,handler:this.print});this.add(formPanel);},updateRectangle:function(){this.layer.removeFeatures(this.rectangle);var center=this.rectangle.geometry.getBounds().getCenterLonLat();var layout=this.getCurLayout();this.rectangle=this.createRectangle(center,this.getCurScale(),layout,this.rotation&&layout.rotation?this.rotation.getValue():0);if(this.rotation){this.rotation.setDisabled(!layout.rotation);if(!layout.rotation){this.rotation.setValue(0);}}
if(layout.rotation){this.createRotateHandle(this.rectangle);}else{this.removeRotateHandle();}},createTheRectangle:function(){if(this.rectangle)this.layer.removeFeatures(this.rectangle);var layout=this.getCurLayout();this.rectangle=this.createRectangle(this.map.getCenter(),this.getCurScale(),this.getCurLayout(),this.rotation&&layout.rotation?this.rotation.getValue():0);if(layout.rotation){this.createRotateHandle(this.rectangle);}},afterLayerCreated:function(){this.setCurScale(this.fitScale(this.getCurLayout()));this.createTheRectangle();},getCurLayout:function(){var values=this.formPanel.getForm().getValues();var layoutName=values['/layout'];return this.getLayoutForName(layoutName);},getCurScale:function(){var values=this.formPanel.getForm().getValues();return values['scale'];},setCurScale:function(value){this.scale.setValue(value);},getCurDpi:function(){var values=this.formPanel.getForm().getValues();return values["dpi"];},setCurRotation:function(rotation){this.rotation.setValue(rotation);},fillSpec:function(printCommand){var singlePage={center:this.getCenterRectangle(this.rectangle)};var params=printCommand.spec;params.pages.push(singlePage);params.pageTitle=this.getPageTitle();params.divTitle=this.getDivTitle();params.mapTitle=this.getMapTitle();this.formPanel.getForm().items.each(function(cur){var name=cur.getName();if(OpenLayers.String.startsWith(name,"/")){params[name.substr(1)]=cur.getValue();}else{singlePage[name]=cur.getValue();}},this);}});Ext.reg('print-simple',Municipia.controls.print.SimpleForm);Ext.namespace('Municipia.controls');Ext.namespace('Municipia.controls.plLocalizacao');Ext.namespace('Municipia.layout');Municipia.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['municipia.row']=Municipia.layout.RowLayout;Municipia.controls.plLocalizacao.Base={map:null,configUrl:null,config:null,serviceParams:null,mask:null,printing:false,searching:false,vectorsLayer:null,initPlantas:function(){this.fillComponent();return false;},configReceived:function(config){this.config=config;if(this.mask){this.mask.hide();}},configFailed:function(){if(this.mask){this.mask.hide();}},pesquisar:function(){var o={start:0};var baseParams=this.formPanel.store.baseParams||{};this.formPanel.getForm().items.each(function(cur){var name=cur.getName();baseParams[name]=cur.getValue();},this);if(!this.formPanel.pretensao)
baseParams.idPretensao=-1;baseParams.initDate=Ext.util.Format.date(baseParams.initDate,'d-m-Y');baseParams.finalDate=Ext.util.Format.date(baseParams.finalDate,'d-m-Y');this.formPanel.store.baseParams=baseParams;this.searching=false;this.formPanel.store.reload({params:o});},imitirPlantas:function(flagEmissao){if(this.mask){if(flagEmissao)
this.mask.msg=OpenLayers.i18n('plantas.generatingPDF');else
this.mask.msg=OpenLayers.i18n('plantas.pedidos.generatingPDF');this.mask.show();}
var printCommand=new Municipia.PlantasProtocol(this.map,this.config,{},this.getCurDpi(),null);var out_options={'internalProjection':this.map.baseLayer.projection,'externalProjection':this.map.baseLayer.projection};var formatWKT=new OpenLayers.Format.WKT(out_options);var strWKT=formatWKT.write(this.vectorsLayer.features[0]);var formatGML=new OpenLayers.Format.GML.v2(out_options);var strGML=formatGML.write(this.vectorsLayer.features[0]);strGML=strGML.replace(/gml:geometry/gi,"feature:geometry");strGML=strGML.substr(strGML.indexOf("<feature:geometry>")+("<feature:geometry>").length)
strGML=strGML.substr(0,strGML.indexOf(">"))+" srsName='http://www.opengis.net/gml/srs/epsg.xml#"+this.map.baseLayer.projection.projCode.split(':')[1]+"'"+strGML.substr(strGML.indexOf(">"))
strGML=strGML.substr(0,strGML.indexOf("</feature:geometry>"))
var singlePage={center:[this.vectorsLayer.features[0].geometry.bounds.getCenterLonLat().lon,this.vectorsLayer.features[0].geometry.bounds.getCenterLonLat().lat],scale:Math.round(this.map.getScale())};var params=printCommand.spec;params.layout=this.getCurLayout();params.pageTitle=this.getPageTitle();params.divTitle=this.getDivTitle();params.mapTitle=this.getMapTitle();params.comment=this.comment;params.featureGML=strGML;params.featureWKT=strWKT;params.emissaoplantas=flagEmissao;params.pages.push(singlePage);if(flagEmissao){this.formPanel.getForm().items.each(function(cur){var name=cur.getName();params[name]=cur.getValue();},this);}else{var attributes=this.vectorsLayer.features[0].attributes;params.id=attributes.id;params.nome=attributes.nome;params.contribuinte=attributes.contribuinte;params.freguesia=attributes.freguesia;params.local=attributes.local;params.natobra=attributes.natobra;params.idNatObra=attributes.idNatObra;params.idPretensao=attributes.idPretensao;params.dataemissao=attributes.dataemissao;}
this.printing=true;printCommand.createPDF(function(){if(this.mask)this.mask.hide();this.printing=false;},function(request){this.showResponse(request);},function(request){Ext.Msg.alert(OpenLayers.i18n('plantas.error'),OpenLayers.i18n('plantas.unableToPrint'));if(this.mask)this.mask.hide();this.printing=false;},this);},showResponse:function(request){var onClick='Ext.getCmp(\'printPopup\').destroy();';var path=request.getURL;if(path.lastIndexOf('?')!=-1)
{path=Base64.encode(path.substring(0,path.lastIndexOf('?')))+path.substring(path.lastIndexOf('?'));}
else
{path=Base64.encode(path)+"?";}
var urlFile=((app.urlApp.lastIndexOf('/')==app.urlApp.length-1)?app.urlApp:(app.urlApp+"/"))+app.proxyWMS+path;onClick+='window.open(\''+'util/Download.aspx?urlFile='+urlFile+'\', \'_blank\');';var content='<table border="0" cellspacing="0" cellpadding="0" class="printPageHeader" align="Center">';content+='<tr>';content+='<td colspan="2" >';content+=OpenLayers.i18n('plantas.pdfReady');content+='</td>';content+='</tr>';content+='</table>';content+='<div class="printPageContent">';content+='<table cellspacing="1" cellpadding="0" >';content+='<tr><td colspan="2"><br /></td></tr>';content+='<tr>';content+='<td colspan="2" align="right"  >';content+='<table id="PlantLinks" align="Center" border="0">';content+='<tr>';content+='<td><a title="'+OpenLayers.i18n('print.pdfView')+'" href="#" onclick="'+onClick+'" ><img title="'+OpenLayers.i18n('print.pdfView')+'" src="images/pdfIcon.gif" style="border-width:0px;" /></a></td><td class="pdfUrlClass"><a href="#"  onclick="'+onClick+'" >'+OpenLayers.i18n('plantas.name-pdf')+'</a></td>';content+='</tr>';content+='</table>';content+='<br />';content+='<br />';content+='<center>';content+=OpenLayers.i18n('print.acrobat-reader-msg');content+='</center>';content+='</tr>';content+='</table>';content+='</div>';var popup=new Ext.Window({bodyStyle:'padding: 7px;',width:380,id:"printPopup",autoHeight:true,constrain:true,closable:true,title:OpenLayers.i18n('plantas.information'),html:content,listeners:{destroy:function(){if(this.mask)this.mask.hide();this.printing=false;},scope:this}});popup.show();},getCurDpi:null,getCurLayout:null,getPageTitle:null,getDivTitle:null,getMapTitle:null};Ext.namespace('Municipia.controls');Ext.namespace('Municipia.controls.plLocalizacao');Ext.override(Ext.form.Field,{showContainer:function(){this.setVisible(true);this.enable();this.getEl().up('.x-form-item').setDisplayed(true);},hideContainer:function(){this.disable();this.setVisible(false);this.getEl().up('.x-form-item').setDisplayed(false);},setContainerVisible:function(visible){if(visible){this.showContainer();}else{this.hideContainer();}
return this;}});Ext.form.Field.prototype.onRender=Ext.form.Field.prototype.onRender.createSequence(function(config){if(Ext.isEmpty(this.wrap))
{if(this.hiddenContainer==true){function hide(field)
{field.hideContainer();field.un('render',hide);}
this.on('render',hide);}}
else
{if(this.hiddenContainer==true){this.hideContainer();}}});Ext.override(Ext.form.Field,{showField:function(){this.enable();this.show();this.container.up('div.x-form-item').setDisplayed(true);},hideField:function(){this.disable();this.hide();this.container.up('div.x-form-item').setDisplayed(false);}});Municipia.controls.plLocalizacao.EmissaoForm=Ext.extend(Ext.Panel,{formConfig:null,infoPanel:null,layout:'fit',pretensao:false,initComponent:function(){Municipia.controls.plLocalizacao.EmissaoForm.superclass.initComponent.call(this);this.on('render',function(){var mask=this.mask=new Ext.LoadMask(this.body,{msg:OpenLayers.i18n('plantas.generatingPDF')});},this);this.fillComponent();},configReceived:function(config){Municipia.controls.plLocalizacao.base.configReceived.call(this,config);this.fillComponent();this.doLayout();this.fireEvent("configloaded");},configFailed:function(){Municipia.controls.plLocalizacao.Base.configFailed.call(this);this.add({border:false,region:'center',html:OpenLayers.i18n('plantas.serverDown')});this.doLayout();this.config=false;},fillComponent:function(){var formConfig=OpenLayers.Util.extend({rowHeight:1.0,autoScroll:true,border:false,bodyBorder:false,defaults:{allowBlank:true,selectOnFocus:true,msgTarget:'side'}},this.formConfig);var formPanel=this.formPanel=new Ext.form.FormPanel(formConfig);if(this.infoPanel!=null){formPanel.add(this.infoPanel);}
var itemsNatObra=[];itemsNatObra.push(this.createNaturezaObraCombo());itemsNatObra.push(this.createSubNaturezaObraCombo());if(this.pretensao){itemsNatObra.push(this.createPretensaoCombo());}
var fieldsetNatObra={xtype:'fieldset',checkboxToggle:false,title:OpenLayers.i18n('plantas.fieldsetnatobra'),collapsible:false,autoHeight:true,defaults:{width:130,listWidth:200,allowBlank:false,selectOnFocus:true,msgTarget:'side'},defaultType:'textfield',items:itemsNatObra};formPanel.add(fieldsetNatObra);var pn1=new Ext.Panel({fitContainer:true,fitToFrame:true,defaults:{width:130},html:"<span class='x-fieldset-header x-unselectable x-fieldset-header-text'>As plantas s&atilde;o emitidas com base na &aacute;rea delimitada pelo pol&iacute;gono desenhado no mapa. O desenho do pol&iacute;gono no mapa &eacute; efectuado atrav&eacute;s do bot&atilde;o <img src='images/toolbar/draw_polygon.png' height='18px' width='18px' />.  <img id='img_valid_coord' src='images/exclamation.gif' style='display:inline;visibility:hidden;' height='16px' width='18px' /></span>",bodyStyle:'padding-top: 15px; padding-bottom: 7px; text-align:justify;',cls:'txtPlantas',layout:'fit',autoScroll:false});var pn2=new Ext.Panel({fitContainer:true,fitToFrame:true,defaults:{width:130},html:"<span>Depois de conclu&iacute;do o desenho do pol&iacute;gono, e ap&oacute;s ter preenchido o local da obra, o seu nome e n&uacute;mero de identifica&ccedil;&atilde;o fiscal, carregue no bot&atilde;o <span style='color: black;'>"+OpenLayers.i18n('plantas.gerar')+"</span> para obter as plantas pretendidas.</span>",bodyStyle:'padding-bottom: 20px; text-align:justify;',cls:'txtPlantas',layout:'fit',autoScroll:false});formPanel.add(pn1);formPanel.add(pn2);var fieldsetReq={xtype:'fieldset',checkboxToggle:false,title:OpenLayers.i18n('plantas.fieldsetrequerente'),autoHeight:true,defaults:{width:130,allowBlank:false,selectOnFocus:true,msgTarget:'side'},defaultType:'textfield',collapsed:false,items:[this.createFreguesiaCombo(),this.createLocalTextField(),this.createNomeTextField(),this.createContribuinteTextField()]};formPanel.add(fieldsetReq);formPanel.addButton({text:OpenLayers.i18n('plantas.gerar'),scope:this,handler:this.initEmitir});this.add(formPanel);},initEmitir:function(){if(!this.printing){var imagemErro=document.getElementById('img_valid_coord');var validade=false;if(!(this.vectorsLayer&&this.vectorsLayer.features.length==1)){if(imagemErro)
imagemErro.style.visibility='visible';}else{if(imagemErro)
imagemErro.style.visibility='hidden';validade=true;}
if(this.formPanel.getForm().isValid()&&validade){this.imitirPlantas(true);}}},createLocalTextField:function(){return new Ext.form.TextField({fieldLabel:OpenLayers.i18n('plantas.local'),name:'local',blankText:OpenLayers.i18n('plantas.local.blankText')});},createNomeTextField:function(){return new Ext.form.TextField({fieldLabel:OpenLayers.i18n('plantas.nome'),name:'nome',blankText:OpenLayers.i18n('plantas.nome.blankText')});},createContribuinteTextField:function(){return new Ext.form.NumberField({fieldLabel:OpenLayers.i18n('plantas.contribuinte'),name:'contribuinte',blankText:OpenLayers.i18n('plantas.contribuinte.blankText'),msgTarget:'side',allowDecimals:false,allowNegative:false,validationEvent:'blur',minLength:9,maxLength:9,maxLengthText:OpenLayers.i18n('plantas.contribuinte.invalidText'),minLengthText:OpenLayers.i18n('plantas.contribuinte.invalidText'),invalidText:OpenLayers.i18n('plantas.contribuinte.invalidText'),validator:function(v){return IsValidNIF(v);}});},createNaturezaObraCombo:function(){var natobra=Ext.data.Record.create([{name:"idNatObra",mapping:"id"},{name:"nome",mapping:"descricao"}]);var natobraReader=new Ext.data.JsonReader({totalProperty:"totalRegistos",root:"listaNatObras",id:'idNatObra'},natobra);var natobraDS=new Ext.data.Store({proxy:new Ext.data.HttpProxy({method:'POST',scope:this,jsonData:"{}",url:'GeocidMadeira.asmx/getNatObras'}),baseParams:{'appID':app.appID,'paiid':'','nivel':'0'},reader:natobraReader,remoteSort:false});var natObraCombobox=new Ext.form.ComboBox({id:'cb_natobra',name:'cb_natobra',fieldLabel:OpenLayers.i18n('plantas.natobra.grupo'),hiddenContainer:false,store:natobraDS,mode:'remote',displayField:'nome',typeAhead:true,valueField:'idNatObra',hiddenName:'idGrupoNatObra',emptyText:OpenLayers.i18n('plantas.emptyGrupoNatObra'),selectOnFocus:true,forceSelection:true,allowBlank:false,editable:false,disabled:false,triggerAction:'all',blankText:OpenLayers.i18n('plantas.gobra.invalidText'),listeners:{'select':{fn:function(combo,record,index){var comboPretensao=Ext.getCmp('cb_pretensao');if(comboPretensao){comboPretensao.reset();comboPretensao.setDisabled(true);}
var comboSubNat=Ext.getCmp('cb_subnatobra');if(comboSubNat){comboSubNat.reset();if(comboSubNat.mode=='remote'){comboSubNat.store.reload();}
comboSubNat.showField();}},scope:this}}});natobraDS.on('beforeload',function(){var params=this.store.baseParams
var jsonData="{";for(var k in params){if(params[k]!="")
jsonData+="'"+k+"':'"+params[k]+"',"}
jsonData+="'paiid':''";if(jsonData.length>1&&(jsonData.lastIndexOf(',')==jsonData.length-1)){jsonData=jsonData.substring(0,jsonData.length-1);}
jsonData+="}";this.store.proxy.conn.jsonData=jsonData;},natObraCombobox);return natObraCombobox;},createSubNaturezaObraCombo:function(){var subnatobra=Ext.data.Record.create([{name:"idNatObra",mapping:"id"},{name:"nome",mapping:"descricao"}]);var subnatobraReader=new Ext.data.JsonReader({totalProperty:"totalRegistos",root:"listaNatObras",id:'idNatObra'},subnatobra);var subnatobraDS=new Ext.data.Store({proxy:new Ext.data.HttpProxy({method:'POST',scope:this,jsonData:"{}",url:'GeocidMadeira.asmx/getNatObras'}),baseParams:{'appID':app.appID,'paiid':'','nivel':'1'},reader:subnatobraReader,remoteSort:true});var subNatObraCombobox=new Ext.form.ComboBox({id:'cb_subnatobra',name:'cb_subnatobra',fieldLabel:OpenLayers.i18n('plantas.natobra.tipo'),hiddenContainer:false,disabled:true,store:subnatobraDS,mode:'remote',displayField:'nome',typeAhead:true,valueField:'idNatObra',hiddenName:'idNatObra',emptyText:OpenLayers.i18n('plantas.emptyTipoNatObra'),selectOnFocus:true,forceSelection:true,allowBlank:false,editable:false,triggerAction:'all',blankText:OpenLayers.i18n('plantas.tobra.invalidText'),listeners:{'select':{fn:function(combo,record,index){var comboPretensao=Ext.getCmp('cb_pretensao');if(comboPretensao){comboPretensao.reset();if(comboPretensao.mode=='remote'){comboPretensao.store.reload();}
comboPretensao.showField();}},scope:this}}});subnatobraDS.on('beforeload',function(){var params=this.store.baseParams
var jsonData="{";for(var k in params){if(params[k]!="")
jsonData+="'"+k+"':'"+params[k]+"',"}
jsonData+="'paiid':'"+Ext.getCmp('cb_natobra').getValue()+"'";if(jsonData.length>1&&(jsonData.lastIndexOf(',')==jsonData.length-1)){jsonData=jsonData.substring(0,jsonData.length-1);}
jsonData+="}";this.store.proxy.conn.jsonData=jsonData;},subNatObraCombobox);return subNatObraCombobox;},createPretensaoCombo:function(){var pretensao=Ext.data.Record.create([{name:"idPretensao",mapping:"id"},{name:"nome",mapping:"descricao"}]);var pretensaoReader=new Ext.data.JsonReader({totalProperty:"totalRegistos",root:"listaPretensoes",id:'idPretensao'},pretensao);var pretensaoDS=new Ext.data.Store({proxy:new Ext.data.HttpProxy({method:'POST',scope:this,jsonData:"{}",url:'GeocidMadeira.asmx/getPretensoes'}),baseParams:{'appID':app.appID,'idNatObra':-1},reader:pretensaoReader,remoteSort:true});var pretensaoCombobox=new Ext.form.ComboBox({id:'cb_pretensao',name:'cb_pretensao',fieldLabel:OpenLayers.i18n('plantas.pretensao'),hiddenContainer:false,disabled:true,store:pretensaoDS,mode:'remote',displayField:'nome',typeAhead:true,valueField:'idPretensao',hiddenName:'idPretensao',emptyText:OpenLayers.i18n('plantas.emptyPretensao'),selectOnFocus:true,forceSelection:true,allowBlank:false,editable:false,triggerAction:'all',blankText:OpenLayers.i18n('plantas.pretensao.invalidText')});pretensaoDS.on('beforeload',function(){var params=this.store.baseParams
var jsonData="{";for(var k in params){if(params[k]!="")
jsonData+="'"+k+"':'"+params[k]+"',"}
jsonData+="'idNatObra':'"+Ext.getCmp('cb_subnatobra').getValue()+"'";if(jsonData.length>1&&(jsonData.lastIndexOf(',')==jsonData.length-1)){jsonData=jsonData.substring(0,jsonData.length-1);}
jsonData+="}";this.store.proxy.conn.jsonData=jsonData;},pretensaoCombobox);return pretensaoCombobox;},createFreguesiaCombo:function(){var fregF=Ext.data.Record.create([{name:"dicofre",mapping:"dicofre"},{name:"descricao",mapping:"nome"},{name:"shape"},{name:"xmin"},{name:"ymin"},{name:"xmax"},{name:"ymax"},{name:"datum"}]);var freguesiasStore=new Ext.data.Store({proxy:new Ext.data.HttpProxy({method:'POST',scope:this,jsonData:"{}",url:'GeocidMadeira.asmx/getFreguesias'}),baseParams:{'appID':app.appID},remoteSort:false,reader:new Ext.data.JsonReader({totalProperty:"totalRegistos",root:"listaFreguesias",id:'dicofre'},fregF)});var combofreguesias=new Ext.form.ComboBox({fieldLabel:OpenLayers.i18n('plantas.freguesia'),name:'freguesia',id:'freguesia',hiddenContainer:false,disabled:false,selectOnFocus:true,forceSelection:true,allowBlank:false,editable:false,typeAhead:true,forceSelection:true,valueField:'descricao',displayField:'descricao',mode:'remote',emptyText:OpenLayers.i18n('plantas.freguesia.emptytext'),blankText:OpenLayers.i18n('plantas.freguesia.invalidText'),triggerAction:'all',store:freguesiasStore});freguesiasStore.on('beforeload',function(){var params=this.store.baseParams
var jsonData="{";for(var k in params){if(params[k]!="")
jsonData+="'"+k+"':'"+params[k]+"',"}
jsonData+="'ano':'2001'";if(jsonData.length>1&&(jsonData.lastIndexOf(',')==jsonData.length-1)){jsonData=jsonData.substring(0,jsonData.length-1);}
jsonData+="}";this.store.proxy.conn.jsonData=jsonData;},combofreguesias);return combofreguesias;},getCurDpi:function(){return 72;},getCurLayout:function(){return"A4 portrait";},getPageTitle:function(){return"";},getDivTitle:function(){return"";},getMapTitle:function(){return"";}});Ext.reg('plantas-localizacao',Municipia.controls.plLocalizacao.EmissaoForm);OpenLayers.Util.applyDefaults(Municipia.controls.plLocalizacao.EmissaoForm.prototype,Municipia.controls.plLocalizacao.Base);Ext.namespace('Municipia.controls');Ext.namespace('Municipia.controls.plLocalizacao');Municipia.controls.plLocalizacao.PedidosForm=Ext.extend(Ext.Panel,{formConfig:null,infoPanel:null,layout:'',pretensao:false,gStore:null,initComponent:function(){Municipia.controls.plLocalizacao.PedidosForm.superclass.initComponent.call(this);this.on('render',function(){var mask=this.mask=new Ext.LoadMask(this.body,{msg:OpenLayers.i18n('plantas.generatingPDF')});},this);this.fillComponent();},configReceived:function(config){Municipia.controls.plLocalizacao.base.configReceived.call(this,config);this.fillComponent();this.doLayout();this.fireEvent("configloaded");},configFailed:function(){Municipia.controls.plLocalizacao.Base.configFailed.call(this);this.add({border:false,region:'center',html:OpenLayers.i18n('plantas.serverDown')});this.doLayout();this.config=false;},fillComponent:function(){var formConfig=OpenLayers.Util.extend({border:false,bodyBorder:false,height:360,defaults:{allowBlank:false,selectOnFocus:true,msgTarget:'side'}},this.formConfig);var formPanel=this.formPanel=new Ext.form.FormPanel(formConfig);if(this.infoPanel!=null){formPanel.add(this.infoPanel);}
var itemsNatObra=[];itemsNatObra.push(this.createNaturezaObraCombo());itemsNatObra.push(this.createSubNaturezaObraCombo());if(this.pretensao){itemsNatObra.push(this.createPretensaoCombo());}
var fieldsetNatObra={xtype:'fieldset',checkboxToggle:false,title:OpenLayers.i18n('plantas.fieldsetnatobra'),collapsible:false,autoHeight:true,defaults:{width:130,listWidth:230,allowBlank:true,selectOnFocus:true,msgTarget:'side'},defaultType:'textfield',items:itemsNatObra};formPanel.add(fieldsetNatObra);var fieldsetReq={xtype:'fieldset',title:OpenLayers.i18n('plantas.fieldsetrequerente'),collapsible:false,autoHeight:true,defaults:{width:130,listWidth:200,selectOnFocus:true,msgTarget:'side'},defaultType:'textfield',items:[this.createLocalTextField(),this.createPlantaTextField(),this.createContribuinteTextField()]};formPanel.add(fieldsetReq);var fieldsetDates={xtype:'fieldset',title:OpenLayers.i18n('plantas.fieldsetDates'),collapsible:false,autoHeight:true,defaults:{width:130,allowBlank:true,selectOnFocus:true,msgTarget:'side'},items:[this.createComboInitDate(),this.createComboFinalDate()]};formPanel.add(fieldsetDates);formPanel.addButton({text:OpenLayers.i18n('plantas.pedidos.pesquisar'),scope:this,handler:this.initPesquisar});this.add(formPanel);this.gridPedidos=this.createGridNewPedidos();this.add(this.gridPedidos);formPanel.store=this.gStore;},initPesquisar:function(){if(!this.searching){if(this.formPanel.getForm().isValid()){this.pesquisar();}}},initImprimirPedido:function(){if(!(this.vectorsLayer&&this.vectorsLayer.features.length==1)){Ext.MessageBox.alert(OpenLayers.i18n('print.information'),OpenLayers.i18n('plantas.pedidos.deleteFeatureWKT'),null);return;}
if(!this.printing){this.imitirPlantas(false);}},createLocalTextField:function(){return new Ext.form.TextField({fieldLabel:OpenLayers.i18n('plantas.local'),name:'localPedidos',blankText:OpenLayers.i18n('plantas.local.blankText')});},createNomeTextField:function(){return new Ext.form.TextField({fieldLabel:OpenLayers.i18n('plantas.nome'),name:'nomePedidos',blankText:OpenLayers.i18n('plantas.nome.blankText')});},createComboInitDate:function(){return{xtype:'datefield',fieldLabel:'Data Inicial',name:'initDate'};},createComboFinalDate:function(){return{xtype:'datefield',fieldLabel:'Data Final',name:'finalDate'};},createContribuinteTextField:function(){return new Ext.form.NumberField({fieldLabel:OpenLayers.i18n('plantas.contribuinte'),name:'contribuintePedidos',blankText:OpenLayers.i18n('plantas.contribuinte.blankText'),msgTarget:'side',allowBlank:false,allowDecimals:false,allowNegative:false,validationEvent:'blur',minLength:9,maxLength:9,maxLengthText:OpenLayers.i18n('plantas.contribuinte.invalidText'),minLengthText:OpenLayers.i18n('plantas.contribuinte.invalidText'),invalidText:OpenLayers.i18n('plantas.contribuinte.invalidText'),validator:function(v){return IsValidNIF(v);}});},createPlantaTextField:function(){return new Ext.form.NumberField({fieldLabel:OpenLayers.i18n('plantas.n_planta'),name:'plantaPedidos',blankText:OpenLayers.i18n('plantas.n_planta.blankText'),msgTarget:'side',allowBlank:true,allowDecimals:false,allowNegative:false,minLength:0,maxLength:9,maxLengthText:OpenLayers.i18n('plantas.n_planta.invalidText'),minLengthText:OpenLayers.i18n('plantas.n_planta.invalidText'),invalidText:OpenLayers.i18n('plantas.n_planta.invalidText')});},createNaturezaObraCombo:function(){var natobra=Ext.data.Record.create([{name:"idNatObra",mapping:"id"},{name:"nome",mapping:"descricao"}]);var natobraReader=new Ext.data.JsonReader({totalProperty:"totalRegistos",root:"listaNatObras",id:'idNatObra'},natobra);var natobraDS=new Ext.data.Store({proxy:new Ext.data.HttpProxy({method:'POST',scope:this,jsonData:"{}",url:'GeocidMadeira.asmx/getNatObras'}),baseParams:{'appID':app.appID,'paiid':'','nivel':'0'},reader:natobraReader,remoteSort:false});var natObraCombobox=new Ext.form.ComboBox({id:'cb_pedidosnatobra',name:'cb_pedidosnatobra',fieldLabel:OpenLayers.i18n('plantas.natobra.grupo'),hiddenContainer:false,store:natobraDS,mode:'remote',displayField:'nome',typeAhead:true,valueField:'idNatObra',hiddenName:'idGrupoNatObra',emptyText:OpenLayers.i18n('plantas.emptyGrupoNatObra'),selectOnFocus:true,forceSelection:true,allowBlank:false,editable:false,disabled:false,triggerAction:'all',blankText:OpenLayers.i18n('plantas.gobra.invalidText'),listeners:{'select':{fn:function(combo,record,index){var comboPretensao=Ext.getCmp('cb_pedidospretensao');if(comboPretensao){comboPretensao.reset();comboPretensao.setDisabled(true);}
var comboSubNat=Ext.getCmp('cb_pedidossubnatuobra');if(comboSubNat){comboSubNat.reset();if(comboSubNat.mode=='remote'){comboSubNat.store.reload();}
comboSubNat.showField();}},scope:this}}});natobraDS.on('beforeload',function(){var params=this.store.baseParams
var jsonData="{";for(var k in params){if(params[k]!="")
jsonData+="'"+k+"':'"+params[k]+"',"}
jsonData+="'paiid':''";if(jsonData.length>1&&(jsonData.lastIndexOf(',')==jsonData.length-1)){jsonData=jsonData.substring(0,jsonData.length-1);}
jsonData+="}";this.store.proxy.conn.jsonData=jsonData;},natObraCombobox);natobraDS.on('load',function(store,records,options){this.store.insert(0,new Ext.data.Record({idNatObra:'-1',nome:'Todos'}));},natObraCombobox);return natObraCombobox;},createSubNaturezaObraCombo:function(){var subnatobra=Ext.data.Record.create([{name:"idNatObra",mapping:"id"},{name:"nome",mapping:"descricao"}]);var subnatobraReader=new Ext.data.JsonReader({totalProperty:"totalRegistos",root:"listaNatObras",id:'idNatObra'},subnatobra);var subnatobraDS=new Ext.data.Store({proxy:new Ext.data.HttpProxy({method:'POST',scope:this,jsonData:"{}",url:'GeocidMadeira.asmx/getNatObras'}),baseParams:{'appID':app.appID,'paiid':'','nivel':'1'},reader:subnatobraReader,remoteSort:true});var subNatObraCombobox=new Ext.form.ComboBox({id:'cb_pedidossubnatuobra',name:'cb_pedidossubnatuobra',fieldLabel:OpenLayers.i18n('plantas.natobra.tipo'),hiddenContainer:false,disabled:true,store:subnatobraDS,mode:'remote',displayField:'nome',typeAhead:true,valueField:'idNatObra',hiddenName:'idNatObra',emptyText:OpenLayers.i18n('plantas.emptyTipoNatObra'),selectOnFocus:true,forceSelection:true,allowBlank:false,editable:false,triggerAction:'all',blankText:OpenLayers.i18n('plantas.tobra.invalidText'),listeners:{'select':{fn:function(combo,record,index){var comboPretensao=Ext.getCmp('cb_pedidospretensao');if(comboPretensao){comboPretensao.reset();if(comboPretensao.mode=='remote'){comboPretensao.store.reload();}
comboPretensao.showField();}},scope:this}}});subnatobraDS.on('beforeload',function(){var params=this.store.baseParams
var jsonData="{";for(var k in params){if(params[k]!="")
jsonData+="'"+k+"':'"+params[k]+"',"}
jsonData+="'paiid':'"+Ext.getCmp('cb_pedidosnatobra').getValue()+"'";if(jsonData.length>1&&(jsonData.lastIndexOf(',')==jsonData.length-1)){jsonData=jsonData.substring(0,jsonData.length-1);}
jsonData+="}";this.store.proxy.conn.jsonData=jsonData;},subNatObraCombobox);return subNatObraCombobox;},createPretensaoCombo:function(){var pretensao=Ext.data.Record.create([{name:"idPretensao",mapping:"id"},{name:"nome",mapping:"descricao"}]);var pretensaoReader=new Ext.data.JsonReader({totalProperty:"totalRegistos",root:"listaPretensoes",id:'idPretensao'},pretensao);var pretensaoDS=new Ext.data.Store({proxy:new Ext.data.HttpProxy({method:'POST',scope:this,jsonData:"{}",url:'GeocidMadeira.asmx/getPretensoes'}),baseParams:{'appID':app.appID,'idNatObra':-1},reader:pretensaoReader,remoteSort:true});var pretensaoCombobox=new Ext.form.ComboBox({id:'cb_pedidospretensao',name:'cb_pedidospretensao',fieldLabel:OpenLayers.i18n('plantas.pretensao'),hiddenContainer:false,disabled:true,store:pretensaoDS,mode:'remote',displayField:'nome',typeAhead:true,valueField:'idPretensao',hiddenName:'idPretensao',emptyText:OpenLayers.i18n('plantas.emptyPretensao'),selectOnFocus:true,forceSelection:true,allowBlank:false,editable:false,triggerAction:'all',blankText:OpenLayers.i18n('plantas.pretensao.invalidText')});pretensaoDS.on('beforeload',function(){var params=this.store.baseParams
var jsonData="{";for(var k in params){if(params[k]!="")
jsonData+="'"+k+"':'"+params[k]+"',"}
jsonData+="'idNatObra':'"+Ext.getCmp('cb_pedidossubnatuobra').getValue()+"'";if(jsonData.length>1&&(jsonData.lastIndexOf(',')==jsonData.length-1)){jsonData=jsonData.substring(0,jsonData.length-1);}
jsonData+="}";this.store.proxy.conn.jsonData=jsonData;},pretensaoCombobox);pretensaoDS.on('load',function(store,records,options){this.store.insert(0,new Ext.data.Record({idPretensao:'-1',nome:'Todos'}));},pretensaoCombobox);return pretensaoCombobox;},createGridPedidos:function(){function renderTopic(value,cell,rec,rowIndex,colIndex,ds){var str=String.format('{0}',value);if(cell.id!=undefined){str=String.format('<P CLASS="zoomToFeature" TITLE="{0}" ><LEFT><IMAGE ALIGN="LEFT" VALIGN="MIDDLE" SRC="images/mapa/ZoomToFeature.gif"><B>&nbsp;{1}</B><LEFT></P>',OpenLayers.i18n('plantas.pedidos.selectPedido'),value);}
return str;}
var record=Ext.data.Record.create([{name:'id'},{name:'idnatobra'},{name:'nome'},{name:'natobra'},{name:'contribuinte'},{name:'localpedido'},{name:'data',type:'date',dateFormat:'d-m-Y'},{name:'featurewkt'},{name:'datum'}]);var reader=new Ext.data.JsonReader({totalProperty:"totalRegistos",root:"listaPesquisa",id:'id'},record);this.gStore=new Ext.data.GroupingStore({proxy:new Ext.data.HttpProxy({method:'POST',scope:this,jsonData:"{}",url:'GeocidMadeira.asmx/getPedidosPesquisa'}),baseParams:{'appID':app.appID},reader:reader,remoteSort:true,sortInfo:{field:'natobra',direction:"DESC"},groupField:'natobra'});this.gStore.setDefaultSort('natobra','DESC');this.gStore.on('beforeload',function(){var params=this.store.baseParams;var jsonData="{";for(var k in params){jsonData+="'"+k+"':'"+params[k]+"',"}
if(!this.pretensao)
jsonData+="'idPretensao': -1,"
if(jsonData.length>1){jsonData=jsonData.substring(0,jsonData.length-1);}
jsonData+="}";this.store.proxy.conn.jsonData=jsonData;},this.formPanel);var cmPedidos=new Ext.grid.ColumnModel([{id:'natobraColumn',header:"Tipo Obra",dataIndex:'natobra',width:100,hidden:false,sortable:true,renderer:renderTopic},{id:'localColumn',header:"Local",dataIndex:'localpedido',width:50,align:'center',sortable:true,hidden:false},{id:'dataColumn',header:"Data",dataIndex:'data',width:50,hidden:false,align:'center',sortable:true,renderer:Ext.util.Format.dateRenderer('d-m-Y')}]);cmPedidos.defaultSortable=true;var pesquisaPedidos=new Ext.grid.GridPanel({rowHeight:1.0,collapsed:false,frame:true,fitToFrame:true,store:this.gStore,autoScroll:true,autoHeight:true,autoWidth:true,cm:cmPedidos,trackMouseOver:true,sm:new Ext.grid.RowSelectionModel({singleSelect:true}),loadMask:true,autoExpandColumn:'natobraColumn',viewConfig:{forceFit:true,enableRowBody:false},view:new Ext.grid.GroupingView({forceFit:true,showGroupName:false,enableNoGroups:false,hideGroupedColumn:false,enableGroupingMenu:true,startCollapsed:true,startCollapsed:true}),bbar:new Ext.PagingToolbar({pageSize:10,store:this.gStore,displayInfo:false})});pesquisaPedidos.getSelectionModel().on('rowselect',function(sm,rowIdx,rec){var map=this.grid.ownerCt.map;var vectorLayer=this.grid.ownerCt.vectorsLayer;if(map&&vectorLayer){var in_options={'internalProjection':map.baseLayer.projection,'externalProjection':new OpenLayers.Projection(rec.json.datum)};var formatWKT=new OpenLayers.Format.WKT(in_options);var features=formatWKT.read(rec.json.featurewkt);var bounds;if(features){if(features.constructor!=Array){features=[features];}
for(var i=0;i<features.length;++i){var feature=features[i];if(!bounds){bounds=feature.geometry.getBounds();}else{bounds.extend(feature.geometry.getBounds());}
var params={};params.nome=rec.json.nome;params.contribuinte=rec.json.contribuinte;params.local=rec.json.localpedido;params.natobra=rec.json.natobra;params.idNatObra=rec.json.idnatobra;params.dataemissao=rec.json.data;OpenLayers.Util.extend(feature.attributes,params);}
vectorLayer.destroyFeatures();vectorLayer.addFeatures(features);map.zoomToExtent(bounds);this.grid.buttons[0].enable();}else{Ext.MessageBox.alert(OpenLayers.i18n('print.information'),OpenLayers.i18n('plantas.pedidos.errorFeatureWKT'),null);}}});pesquisaPedidos.addButton({text:OpenLayers.i18n('plantas.pedidos.imprimir'),id:'btnprintpedido',scope:this,handler:this.initImprimirPedido,disabled:true});return pesquisaPedidos;},createGridNewPedidos:function(){function renderTopic(value,cell,rec,rowIndex,colIndex,ds){var str=String.format('{0}',value);if(cell.id!=undefined){str=String.format('<P CLASS="zoomToFeature" TITLE="{0}" ><LEFT><IMAGE ALIGN="LEFT" VALIGN="MIDDLE" SRC="images/mapa/ZoomToFeature.gif"><B>{1}</B></LEFT></P>',OpenLayers.i18n('plantas.pedidos.selectPedido'),value);}
return str;}
function renderNPlanta(value,cell,rec,rowIndex,colIndex,ds){var str=String.format('{0}',value);if(cell.id!=undefined){str=String.format('<CENTER>{0}</CENTER>',value);}
return str;}
var record=Ext.data.Record.create([{name:'id'},{name:'n_planta'},{name:'idnatobra'},{name:'nome'},{name:'natobra'},{name:'contribuinte'},{name:'localpedido'},{name:'idpretensao'},{name:'pretensao'},{name:'data',type:'date',dateFormat:'d-m-Y'},{name:'featurewkt'},{name:'datum'}]);var reader=new Ext.data.JsonReader({totalProperty:"totalRegistos",root:"listaPesquisa",id:'id'},record);this.gStore=new Ext.data.GroupingStore({proxy:new Ext.data.HttpProxy({method:'POST',scope:this,jsonData:"{}",url:'GeocidMadeira.asmx/getPedidosPesquisa'}),baseParams:{'appID':app.appID},reader:reader,remoteSort:true,sortInfo:{field:'natobra',direction:"DESC"},groupField:'natobra'});this.gStore.setDefaultSort('natobra','DESC');this.gStore.on('beforeload',function(){var params=this.store.baseParams;var jsonData="{";for(var k in params){jsonData+="'"+k+"':'"+params[k]+"',"}
if(jsonData.length>1){jsonData=jsonData.substring(0,jsonData.length-1);}
jsonData+="}";this.store.proxy.conn.jsonData=jsonData;},this.formPanel);var cmPedidos=new Ext.grid.ColumnModel([{id:'n_planta',header:"Planta",dataIndex:'n_planta',width:50,hidden:false,sortable:true,renderer:renderNPlanta},{id:'natobraColumn',header:"Tipo Obra",dataIndex:'natobra',width:100,hidden:false,sortable:true,renderer:renderTopic},{id:'localColumn',header:"Local",dataIndex:'localpedido',width:50,align:'center',sortable:true,hidden:false},{id:'dataColumn',header:"Data",dataIndex:'data',width:50,hidden:false,align:'center',sortable:true,renderer:Ext.util.Format.dateRenderer('d-m-Y')}]);cmPedidos.defaultSortable=true;var pesquisaPedidos=new Ext.grid.GridPanel({rowHeight:1.0,collapsed:false,frame:true,fitToFrame:true,cm:cmPedidos,trackMouseOver:true,loadMask:true,store:this.gStore,sm:new Ext.grid.RowSelectionModel({singleSelect:true}),autoExpandColumn:'natobraColumn',viewConfig:{forceFit:true,enableRowBody:false},view:new Ext.grid.GroupingView({forceFit:true,showGroupName:false,enableNoGroups:false,hideGroupedColumn:false,enableGroupingMenu:true,startCollapsed:true,startCollapsed:true})});pesquisaPedidos.getSelectionModel().on('rowselect',function(sm,rowIdx,rec){var map=this.grid.ownerCt.map;var vectorLayer=this.grid.ownerCt.vectorsLayer;if(map&&vectorLayer){var in_options={'internalProjection':map.baseLayer.projection,'externalProjection':new OpenLayers.Projection(rec.json.datum)};var formatWKT=new OpenLayers.Format.WKT(in_options);var features=formatWKT.read(rec.json.featurewkt);var bounds;if(features){if(features.constructor!=Array){features=[features];}
for(var i=0;i<features.length;++i){var feature=features[i];if(!bounds){bounds=feature.geometry.getBounds();}else{bounds.extend(feature.geometry.getBounds());}
var params={};params.id=rec.json.id;params.nome=rec.json.nome;params.contribuinte=rec.json.contribuinte;params.freguesia=rec.json.freguesia;params.local=rec.json.localpedido;params.natobra=rec.json.natobra;params.idNatObra=rec.json.idnatobra;params.idPretensao=rec.json.idpretensao;params.dataemissao=rec.json.data;OpenLayers.Util.extend(feature.attributes,params);}
vectorLayer.destroyFeatures();vectorLayer.addFeatures(features);map.zoomToExtent(bounds);this.grid.buttons[0].enable();}else{Ext.MessageBox.alert(OpenLayers.i18n('print.information'),OpenLayers.i18n('plantas.pedidos.errorFeatureWKT'),null);}}});pesquisaPedidos.addButton({text:OpenLayers.i18n('plantas.pedidos.imprimir'),id:'btnprintpedido',scope:this,handler:this.initImprimirPedido,disabled:true});return pesquisaPedidos;}});Ext.reg('plantas-localizacao-pedidos',Municipia.controls.plLocalizacao.PedidosForm);OpenLayers.Util.applyDefaults(Municipia.controls.plLocalizacao.PedidosForm.prototype,Municipia.controls.plLocalizacao.Base);Ext.namespace('Municipia.controls');Ext.namespace('Municipia.controls.plLocalizacao');Municipia.controls.plLocalizacao.LoginForm=Ext.extend(Ext.Panel,{formConfig:null,formPanel:null,infoPanel:null,layout:'',gStore:null,initComponent:function(){Municipia.controls.plLocalizacao.LoginForm.superclass.initComponent.call(this);this.on('render',function(){var mask=this.mask=new Ext.LoadMask(this.body,{msg:OpenLayers.i18n('plantas.generatingPDF')});},this);this.fillComponent();},configReceived:function(config){Municipia.controls.plLocalizacao.base.configReceived.call(this,config);this.fillComponent();this.doLayout();this.fireEvent("configloaded");},configFailed:function(){Municipia.controls.plLocalizacao.Base.configFailed.call(this);this.add({border:false,region:'center',html:OpenLayers.i18n('plantas.serverDown')});this.doLayout();this.config=false;},fillComponent:function(){var formConfig=OpenLayers.Util.extend({border:false,bodyBorder:false,defaults:{allowBlank:false,selectOnFocus:true,msgTarget:'side'}},this.formConfig);this.formPanel=new Ext.form.FormPanel(formConfig);if(this.infoPanel!=null){this.formPanel.add(this.infoPanel);}
var fieldsetLogin={xtype:'fieldset',checkboxToggle:false,title:OpenLayers.i18n('plantas.fieldsetlogin'),collapsible:false,autoHeight:true,defaults:{width:130,listWidth:200,allowBlank:false,selectOnFocus:true,msgTarget:'side'},defaultType:'textfield',items:[this.createUserTextField(),this.createPassTextField()]};this.formPanel.add(fieldsetLogin);this.formPanel.addButton({text:OpenLayers.i18n('plantas.login'),scope:this,handler:this.login});this.add(this.formPanel);this.formPanel.store=this.gStore;},login:function(){if(this.formPanel.getForm().isValid()){Ext.MessageBox.wait(OpenLayers.i18n('plantas.msgLogin'));var form=this.formPanel.getForm();var jsonData="{";for(var i=0;i<form.items.length;i++){var objAtt=form.items.items[i].name;var objVal=form.items.items[i].getValue();jsonData+="'"+objAtt+"':'"+objVal+"',"}
jsonData+="'appID':'"+app.appID+"'";if(jsonData.length>1&&(jsonData.lastIndexOf(',')==jsonData.length-1)){jsonData=jsonData.substring(0,jsonData.length-1);}
jsonData+="}";OpenLayers.Request.POST({url:'GeocidMadeira.asmx/AuthenticateUser',data:jsonData,headers:{'Content-type':"application/json",'Content-length':1,'Connection':"close"},success:function(response){Ext.MessageBox.updateProgress(1);Ext.MessageBox.hide();var json=new OpenLayers.Format.JSON();var answer=json.read(eval(response.responseText));if(answer&&answer.authenticate){app.tabsPlantas.remove(this);var tab=app.tabsPlantas.add(app.pedidosPlantas);app.tabsPlantas.setActiveTab(tab);}else{this.requestFailure(this,response);}},failure:function(response){this.requestFailure(this,response);},scope:this});}},requestFailure:function(context,response){Ext.Msg.alert(OpenLayers.i18n('print.error'),OpenLayers.i18n('plantas.login.failed'));context.formPanel.getForm().reset();},createUserTextField:function(){return new Ext.form.TextField({fieldLabel:OpenLayers.i18n('plantas.username'),name:'username',allowBlank:false});},createPassTextField:function(){return new Ext.form.TextField({fieldLabel:OpenLayers.i18n('plantas.password'),name:'password',inputType:'password',allowBlank:false});}});Ext.reg('plantas-localizacao-login',Municipia.controls.plLocalizacao.LoginForm);OpenLayers.Util.applyDefaults(Municipia.controls.plLocalizacao.LoginForm.prototype,Municipia.controls.plLocalizacao.Base);Municipia.PlantasProtocol=Ext.extend(Municipia.PrintProtocol,{addMapParams:function(overrides,map,dpi){var spec=this.spec;spec.dpi=dpi;spec.units=map.baseLayer.units;spec.srs=map.baseLayer.projection.getCode();var layers=spec.layers=[];overrides=this.fixOverrides(overrides,map);var name;for(var i=0;i<map.layers.length;++i){var olLayer=map.layers[i];if(olLayer.id_layer)
name=new String(olLayer.id_layer).camelize();else{if(olLayer.CLASS_NAME=="OpenLayers.Layer.Vector")
name=new String("_"+olLayer.name).camelize();else
name=new String(olLayer.name).camelize();}
var layerOverrides=OpenLayers.Util.extend({},overrides[name]);OpenLayers.Util.extend(layerOverrides,layerOverrides[dpi]);var type=olLayer.CLASS_NAME;var handler=Municipia.PrintProtocol.SUPPORTED_TYPES[type];if(handler){if(type=="OpenLayers.Layer.Vector"&&olLayer.features.length==0)
continue;var layer=handler.call(this,olLayer);if(layer){this.applyOverrides(layer,layerOverrides);this.applyCustomParams(layer,olLayer);if(olLayer.isBaseLayer){layers.unshift(layer);}else{layers.push(layer);}}}else if(!handler){OpenLayers.Console.error("Don't know how to print a layer of type "+type+" ("+olLayer.name+")");}}},applyCustomParams:function(layer,olLayer){for(var paramName in olLayer.params){var paramNameLow=paramName.toLowerCase();layer.customParams[paramName]=olLayer.params[paramName];}
for(var optionName in olLayer.options){var optionNameLow=optionName.toLowerCase();layer.customOptions[optionName]=olLayer.options[optionName];}},convertLayer:function(olLayer){var url=olLayer.url;if(url instanceof Array){url=url[0];}
if(url!=undefined){if(url.lastIndexOf(app.proxyWMS)>-1){url=url.substring((url.lastIndexOf(app.proxyWMS)+app.proxyWMS.length),url.length);if(url.lastIndexOf('?')!=-1)
{url=Base64.decode(url.substring(0,url.lastIndexOf('?')))+url.substring(url.lastIndexOf('?'));}
else
{url=Base64.decode(url);}}else if(url.lastIndexOf(app.proxyWFS)>-1){url=url.substring((url.lastIndexOf(app.proxyWFS)+app.proxyWFS.length),url.length);if(url.lastIndexOf('?')!=-1)
{url=Base64.decode(url.substring(0,url.lastIndexOf('?')))+url.substring(url.lastIndexOf('?'));}
else
{url=Base64.decode(url);}}}
return{baseURL:Municipia.Util.relativeToAbsoluteURL(url),opacity:(olLayer.opacity!=null)?olLayer.opacity:1.0,singleTile:olLayer.singleTile,id_layer:this.getProperty(olLayer,"id_layer"),customParams:{},customOptions:{}};},createPDF:function(success,popup,failure,context){var specTxt=new OpenLayers.Format.JSON().write(this.spec);OpenLayers.Console.info(specTxt);try{var charset="UTF-8";var params=OpenLayers.Util.applyDefaults({},this.params);OpenLayers.Request.POST({url:'GeocidMadeira.asmx/getMapasPlantasLocalizacao',data:"{\"appID\":\""+app.appID+"\", \"spec\": \""+escape(specTxt)+"\"}",params:params,headers:{'Content-type':"application/json",'Content-length':1,'Connection':"close"},callback:function(request){if(request.status>=200&&request.status<300){var json=new OpenLayers.Format.JSON();var answer=json.read(eval(request.responseText))
if(answer==null&&request.responseXML!=null&&request.responseXML.firstChild!=null&&request.responseXML.firstChild.nextSibling!=null){answer=json.read(request.responseXML.firstChild.nextSibling.text);}
if(answer&&answer.getURL){this.openPdf(answer,success,popup,context);}else{failure.call(context,request);}}else{failure.call(context,request);}},scope:this});}catch(err){OpenLayers.Console.warn("Cannot request the print service by AJAX. You must set "+"the 'OpenLayers.ProxyHost' variable. Fallback to GET method");window.open(this.getAllInOneUrl());success.call(context,err);}},openPdf:function(answer,success,popup,context){OpenLayers.Console.info(answer.getURL);popup.call(context,answer);},getProperty:function(layer,prop){var property=prop;var result="";if(layer[property]!=undefined)
result=layer[property];else if(layer.params!=null&&layer.params[property]!=undefined)
result=layer.params[property];else if(layer.params!=null&&layer.params[property.toUpperCase()]!=undefined)
result=layer.params[property.toUpperCase()];return result;},CLASS_NAME:"Municipia.PlantasProtocol"});Municipia.Color=OpenLayers.Class({getColorRgb:function(){}});Municipia.ColorRgb=OpenLayers.Class(Municipia.Color,{redLevel:null,greenLevel:null,blueLevel:null,initialize:function(red,green,blue){this.redLevel=red;this.greenLevel=green;this.blueLevel=blue;},equals:function(color){return color.redLevel==this.redLevel&&color.greenLevel==this.greenLevel&&color.blueLevel==this.blueLevel;},getColorRgb:function(){return this;},getRgbArray:function(){return[this.redLevel,this.greenLevel,this.blueLevel];},hex2rgbArray:function(rgbHexString){if(rgbHexString.charAt(0)=='#'){rgbHexString=rgbHexString.substr(1);}
var rgbArray=[parseInt(rgbHexString.substring(0,2),16),parseInt(rgbHexString.substring(2,4),16),parseInt(rgbHexString.substring(4,6),16)];for(var i=0;i<rgbArray.length;i++){if(rgbArray[i]<0||rgbArray[i]>255){OpenLayers.Console.error("Invalid rgb hex color string: rgbHexString");}}
return rgbArray;},setFromHex:function(rgbHexString){var rgbArray=this.hex2rgbArray(rgbHexString);this.redLevel=rgbArray[0];this.greenLevel=rgbArray[1];this.blueLevel=rgbArray[2];},setFromRgb:function(rgbString){var color=dojo.colorFromString(rgbString);this.redLevel=color.r;this.greenLevel=color.g;this.blueLevel=color.b;},toHexString:function(){var r=this.toHex(this.redLevel);var g=this.toHex(this.greenLevel);var b=this.toHex(this.blueLevel);return'#'+r+g+b;},toHex:function(dec){var hexCharacters="0123456789ABCDEF";if(dec<0||dec>255){var msg="Invalid decimal value for color level";OpenLayers.Console.error(msg);}
var i=Math.floor(dec/16);var j=dec%16;return hexCharacters.charAt(i)+hexCharacters.charAt(j);},CLASS_NAME:"Municipia.ColorRgb"});Municipia.ColorRgb.getColorsArrayByRgbInterpolation=function(firstColor,lastColor,nbColors){var resultColors=[];var colorA=firstColor.getColorRgb();var colorB=lastColor.getColorRgb();var colorAVal=colorA.getRgbArray();var colorBVal=colorB.getRgbArray();if(nbColors==1){return[colorA];}
for(var i=0;i<nbColors;i++){var rgbTriplet=[];rgbTriplet[0]=colorAVal[0]+
i*(colorBVal[0]-colorAVal[0])/(nbColors-1);rgbTriplet[1]=colorAVal[1]+
i*(colorBVal[1]-colorAVal[1])/(nbColors-1);rgbTriplet[2]=colorAVal[2]+
i*(colorBVal[2]-colorAVal[2])/(nbColors-1);resultColors[i]=new Municipia.ColorRgb(parseInt(rgbTriplet[0]),parseInt(rgbTriplet[1]),parseInt(rgbTriplet[2]));}
return resultColors;};Municipia.GeoStat=OpenLayers.Class({layer:null,sld:null,popup:null,format:null,url:null,requestSuccess:function(request){},requestFailure:function(request){},featureSelection:true,nameAttribute:null,indicator:null,defaultSymbolizer:{},selectSymbolizer:{'strokeColor':'#000000'},legendDiv:null,initialize:function(map,options){this.map=map;this.addOptions(options);if(this.url){OpenLayers.loadURL(this.url,'',this,this.onSuccess,this.onFailure);}
this.symbolizer={Point:{graphicName:"star",pointRadius:8,fillColor:"AAAAAA",strokeColor:"#000000",strokeWidth:1},Line:{strokeColor:"#000000",strokeWidth:3},Polygon:{fillColor:"#AAAAAA",fillOpacity:1.0,strokeColor:"#000000",strokeWidth:2,strokeDashstyle:"dot"}};this.legendDiv=Ext.get(options.legendDiv);},onSuccess:function(request){var format=new OpenLayers.Format.SLD();this.sld=format.read(request.responseXML||request.responseText);this.requestSuccess(request);},onFailure:function(request){this.requestFailure(request);},addOptions:function(newOptions){if(newOptions){if(!this.options){this.options={};}
OpenLayers.Util.extend(this.options,newOptions);OpenLayers.Util.extend(this,newOptions);}},extendStyle:function(rules,symbolizer,context){for(var namedLayer in this.sld.namedLayers){break;}
var layer=this.sld.namedLayers[namedLayer];layer.name=this.layer.params['LAYERS'];var userStyle=this.sld.namedLayers[namedLayer].userStyles[0];var symb=userStyle.rules[0].clone();var aux=OpenLayers.Util.extend({},symb.symbolizer);for(var symbName in symb.symbolizer){break;}
userStyle.rules=[];if(rules){for(var i=0;i<rules.length;i++){var rule=rules[i];aux[symbName]=OpenLayers.Util.applyDefaults(rule.symbolizer,aux[symbName]);rule.symbolizer=OpenLayers.Util.extend({},aux);userStyle.rules[userStyle.rules.length]=rule;}}
if(symbolizer){style.setDefaultStyle(OpenLayers.Util.applyDefaults(symbolizer,style.defaultStyle));}
if(context){if(!style.context){style.context={};}
OpenLayers.Util.extend(style.context,context);}},applyClassification:function(options){var format=new OpenLayers.Format.SLD();var sld=null;try{sld=format.write(this.sld);}catch(err){if(err.lineNumber!=undefined){alert(" (line "+err.lineNumber+" "+err.fileName+")");}}
var params=OpenLayers.Util.applyDefaults({appID:app.appID},params);if(this.loadMask){this.loadMask.msg=OpenLayers.i18n('estatisticos.generatingMapa');this.loadMask.show();}
OpenLayers.Request.POST({url:'GeocidMadeira.asmx/createTempSLD',data:'<?xml version="1.0" encoding="ISO-8859-1"?><Request><Header><sessionID>'+app.sessionID+'</sessionID><appID>'+app.appID+'</appID><method>'+this.method+'</method><classes>'+this.numClasses+'</classes><variavel>'+this.indicator+'</variavel><titulo>'+this.nomeA+' de '+this.nomeB+' por '+this.nomeC+'</titulo><variaveltext>'+this.indicatorText+'</variaveltext><ano>'+Ext.getCmp('rbCensos').getValue()+'</ano><tabela>'+Municipia.Util.getProperty(this.layer,"layers")+'</tabela><tipo>'+this.tipo+'</tipo><subtipo>'+this.subtipo+'</subtipo><filter>'+this.filter+'</filter></Header><Body>'+sld+'</Body></Request>',params:params,headers:{'Content-type':"application/xml",'Connection':"close"},success:this.commitSuccess,failure:this.commitFailure,scope:this});},commitSuccess:function(request){if(this.loadMask){this.loadMask.hide();}
var xml=new OpenLayers.Format.XML();var answer=xml.read(request.responseText);var url="";var html="";var titulo="";if(answer&&answer.childNodes.length>0){var nodes=answer.childNodes;for(var i=0;i<nodes.length;i++){if(nodes[i].nodeName=="RESULT")
{var nodes1Level=nodes[i].childNodes;for(var j=0;j<nodes1Level.length;j++){if(nodes1Level[j].nodeName=="URL"){url=nodes1Level[j].text||nodes1Level[j].textContent;url=unescape(url);}
if(nodes1Level[j].nodeName=="TABLEHTML"){html=nodes1Level[j].text||nodes1Level[j].textContent;html=unescape(html);}
if(nodes1Level[j].nodeName=="TITULO"){titulo=nodes1Level[j].text||nodes1Level[j].textContent;titulo=unescape(titulo);}}}}}
if(url!=undefined&&url!=""&&html!=undefined&&html!=""){var urlLegenda=app.urlWMS+"REQUEST=GetLegendGraphic&VERSION=1.0.0&TRANSPARENT=true&FORMAT=image/png&WIDTH=30&HEIGHT=18&LEGEND_OPTIONS=forceRule:True;fontStyle:bold;fontName:arial;fontColor:808594;fontSize:10&LAYER="+this.layer.params.LAYERS+"&SLD="+url+"&random="+Math.random();this.updateLegend(urlLegenda);this.layer.params.urlLegendEstatisticos=app.baseUrl+urlLegenda;this.layer.params.tituloLegendEstatisticos=this.indicatorText;this.layer.params.tituloEstatisticos=titulo;this.layer.params.SLD=url;this.layer.params.random=Math.random();this.layer.setVisibility(false);var pointToCenter=null;var boundsZoom=null;if(Proj4js.defs[this.datum]){var xymin=new OpenLayers.LonLat(parseFloat(this.xmin.replace(",",".")),parseFloat(this.ymin.replace(",",".")));var xymax=new OpenLayers.LonLat(parseFloat(this.xmax.replace(",",".")),parseFloat(this.ymax.replace(",",".")));var bounds=new OpenLayers.Bounds(xymin.lon,xymin.lat,xymax.lon,xymax.lat);var proj=new OpenLayers.Projection(this.datum);if(this.xmin==this.xmax&&this.ymin==this.ymax){pointToCenter=bounds.getCenterLonLat().transform(proj,new OpenLayers.Projection(app.srsGlobal));if(new OpenLayers.Projection(app.srsGlobal)==new OpenLayers.Projection("EPSG:4326")){pointToCenter.lon=pointToCenter.lon+0.000668;}}else{boundsZoom=bounds.transform(proj,new OpenLayers.Projection(app.srsGlobal));}}
if(pointToCenter!=null){this.map.setCenter(pointToCenter,zoom!=null?zoom:this.map.getNumZoomLevels()-2);}else if(boundsZoom!=null){this.map.zoomToExtent(boundsZoom);}else{this.map.zoomToMaxExtent();}
this.layer.setVisibility(true);if(this.popup!=null){this.popup.close();}
this.popup=new Ext.Window({bodyStyle:'padding: 7px;',width:330,id:"estatisticosPopup",autoHeight:true,resizable:false,closable:true,title:OpenLayers.i18n('estatisticos.information'),html:html});this.popup.show();}else{Ext.Msg.alert(OpenLayers.i18n('estatisticos.information'),OpenLayers.i18n('estatisticos.resultErrorMapa'));}},commitFailure:function(request){if(this.loadMask){this.loadMask.hide();}},CLASS_NAME:"Municipia.GeoStat"});Municipia.GeoStat.Distribution=OpenLayers.Class({labelGenerator:function(bin,binIndex,nbBins){return this.defaultLabelGenerator(bin,binIndex,nbBins)},values:null,nbVal:null,minVal:null,maxVal:null,initialize:function(values,options){OpenLayers.Util.extend(this,options);this.values=values;this.nbVal=values.length;this.minVal=this.nbVal?Municipia.Util.min(this.values):0;this.maxVal=this.nbVal?Municipia.Util.max(this.values):0;},defaultLabelGenerator:function(bin,binIndex,nbBins){return bin.lowerBound.toFixed(3)+' - '+bin.upperBound.toFixed(3)+' ('+bin.nbVal+')'},classifyWithBounds:function(bounds){var bins=[];var binCount=[];var sortedValues=[];for(var i=0;i<this.values.length;i++){sortedValues.push(this.values[i]);}
sortedValues.sort(function(a,b){return a-b;});var nbBins=bounds.length-1;for(var i=0;i<nbBins;i++){binCount[i]=0;}
for(var i=0;i<nbBins-1;i){if(sortedValues[0]<bounds[i+1]){binCount[i]=binCount[i]+1;sortedValues.shift();}else{i++;}}
binCount[nbBins-1]=this.nbVal-Municipia.Util.sum(binCount);for(var i=0;i<nbBins;i++){bins[i]=new Municipia.GeoStat.Bin(binCount[i],bounds[i],bounds[i+1],i==(nbBins-1));var labelGenerator=this.labelGenerator||this.defaultLabelGenerator;bins[i].label=labelGenerator(bins[i],i,nbBins);}
return new Municipia.GeoStat.Classification(bins);},classifyByEqIntervals:function(nbBins){var bounds=[];for(var i=0;i<=nbBins;i++){bounds[i]=this.minVal+
i*(this.maxVal-this.minVal)/nbBins;}
return this.classifyWithBounds(bounds);},classifyByQuantils:function(nbBins){var bounds=[];for(var i=0;i<=nbBins;i++){bounds[i]=this.minVal+
i*(this.maxVal-this.minVal)/nbBins;}
return this.classifyWithBounds(bounds);},sturgesRule:function(){return Math.floor(1+3.3*Math.log(this.nbVal,10));},classify:function(method,nbBins,bounds){var classification=null;if(!nbBins){nbBins=this.sturgesRule();}
switch(method){case Municipia.GeoStat.Distribution.CLASSIFY_WITH_BOUNDS:classification=this.classifyWithBounds(bounds);break;case Municipia.GeoStat.Distribution.CLASSIFY_BY_EQUAL_INTERVALS:classification=this.classifyByEqIntervals(nbBins);break;case Municipia.GeoStat.Distribution.CLASSIFY_BY_QUANTILS:classification=this.classifyByQuantils(nbBins);break;default:OpenLayers.Console.error("unsupported or invalid classification method");}
return classification;},CLASS_NAME:"Municipia.GeoStat.Distribution"});Municipia.GeoStat.Distribution.CLASSIFY_WITH_BOUNDS=0;Municipia.GeoStat.Distribution.CLASSIFY_BY_EQUAL_INTERVALS=1;Municipia.GeoStat.Distribution.CLASSIFY_BY_QUANTILS=2;Municipia.GeoStat.Bin=OpenLayers.Class({label:null,nbVal:null,lowerBound:null,upperBound:null,isLast:false,initialize:function(nbVal,lowerBound,upperBound,isLast){this.nbVal=nbVal;this.lowerBound=lowerBound;this.upperBound=upperBound;this.isLast=isLast;},CLASS_NAME:"Municipia.GeoStat.Bin"});Municipia.GeoStat.Classification=OpenLayers.Class({bins:[],initialize:function(bins){this.bins=bins;},getBoundsArray:function(){var bounds=[];for(var i=0;i<this.bins.length;i++){bounds.push(this.bins[i].lowerBound);}
if(this.bins.length>0){bounds.push(this.bins[this.bins.length-1].upperBound);}
return bounds;},addLayer:function(){if(!this.layer){var styleMap=new OpenLayers.StyleMap({'default':new OpenLayers.Style(OpenLayers.Util.applyDefaults(this.defaultSymbolizer,OpenLayers.Feature.Vector.style['default'])),'select':new OpenLayers.Style(this.selectSymbolizer)});var layer=new OpenLayers.Layer.Vector('geostat',{'displayInLayerSwitcher':false,'visibility':false,'styleMap':styleMap});map.addLayer(layer);this.layer=layer;}},CLASS_NAME:"Municipia.GeoStat.Classification"});Municipia.GeoStat.Choropleth=OpenLayers.Class(Municipia.GeoStat,{colors:[new Municipia.ColorRgb(120,120,0),new Municipia.ColorRgb(255,0,0)],method:Municipia.GeoStat.Distribution.CLASSIFY_BY_QUANTILS,numClasses:5,defaultSymbolizer:{'fillOpacity':1},classification:null,colorInterpolation:null,initialize:function(map,options){Municipia.GeoStat.prototype.initialize.apply(this,arguments);},updateOptions:function(newOptions){var oldOptions=OpenLayers.Util.extend({},this.options);this.addOptions(newOptions);var alterado=false;if(newOptions){if(newOptions.method!=oldOptions.method||newOptions.indicator!=oldOptions.indicator||newOptions.numClasses!=oldOptions.numClasses){alterado=true;this.setClassification();}else if(newOptions.colors&&(!newOptions.colors[0].equals(oldOptions.colors[0])||!newOptions.colors[1].equals(oldOptions.colors[1]))){alterado=true;this.createColorInterpolation();}}
return alterado;},createColorInterpolation:function(){var initialColors=this.colors;var numColors=this.classification.bins.length;this.colorInterpolation=Municipia.ColorRgb.getColorsArrayByRgbInterpolation(initialColors[0],initialColors[1],numColors);},setClassification:function(){var values=[];var distOptions={'labelGenerator':this.options.labelGenerator};var dist=new Municipia.GeoStat.Distribution(values,distOptions);this.classification=dist.classify(this.method,this.numClasses,null);this.createColorInterpolation();},applyClassification:function(options){this.updateOptions(options);var boundsArray=this.classification.getBoundsArray();var rules=new Array(boundsArray.length-1);for(var i=0;i<boundsArray.length-1;i++){var filter=new OpenLayers.Filter.Logical({type:OpenLayers.Filter.Logical.AND,filters:[new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO,property:this.indicator,value:boundsArray[i]}),new OpenLayers.Filter.Comparison({type:(i!=boundsArray.length-2)?OpenLayers.Filter.Comparison.LESS_THAN:OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO,property:this.indicator,value:boundsArray[i+1]})]});var rule=new OpenLayers.Rule({symbolizer:{fillColor:this.colorInterpolation[i].toHexString()},filter:filter});rules[i]=rule;}
this.extendStyle(rules);Municipia.GeoStat.prototype.applyClassification.apply(this,arguments);},updateLegend:function(url){if(!this.legendDiv){return;}
this.legendDiv.update("");var tbl=document.createElement("table");var tblBody=document.createElement("tbody");var rowLegenda=document.createElement("tr");var cellT=document.createElement("td");var element=document.createElement("legend");element.className="x-fieldset-header x-unselectable";var spanElement=document.createElement("span");spanElement.className="x-fieldset-header-text";spanElement.innerHTML=this.options.indicatorText;element.appendChild(spanElement);cellT.appendChild(element);rowLegenda.appendChild(cellT);var rowImagem=document.createElement("tr");var cellI=document.createElement("td");var element=document.createElement("img");element.className="x-unselectable";element.src=url;element.style.marginTop="5px";element.style.marginLeft="5px";cellI.appendChild(element);rowImagem.appendChild(cellI);tblBody.appendChild(rowLegenda);tblBody.appendChild(rowImagem);tbl.appendChild(tblBody);this.legendDiv.appendChild(tbl);},CLASS_NAME:"Municipia.GeoStat.Choropleth"});Ext.override(Ext.form.RadioGroup,{getName:function(){return this.items.first().getName();},getValue:function(){var v;this.items.each(function(item){v=item.getRawValue();return!item.getValue();});return v;},setValue:function(v){this.items.each(function(item){item.setValue(item.getRawValue()==v);});}});Ext.override(Ext.form.RadioGroup,{afterRender:function(){var group=this;this.items.each(function(field){field.on("check",function(self,checked){if(checked)
group.fireEvent('change',group,self.getRawValue());});});Ext.form.RadioGroup.superclass.afterRender.call(this)}});Ext.override(Ext.form.Field,{showContainer:function(){this.setVisible(true);this.enable();this.getEl().up('.x-form-item').setDisplayed(true);},hideContainer:function(){this.disable();this.setVisible(false);this.getEl().up('.x-form-item').setDisplayed(false);},setContainerVisible:function(visible){if(visible){this.showContainer();}else{this.hideContainer();}
return this;}});Ext.form.Field.prototype.onRender=Ext.form.Field.prototype.onRender.createSequence(function(config){if(Ext.isEmpty(this.wrap))
{if(this.hiddenContainer==true){function hide(field)
{field.hideContainer();field.un('render',hide);}
this.on('render',hide);}}
else
{if(this.hiddenContainer==true){this.hideContainer();}}});Ext.override(Ext.form.Field,{showField:function(){this.enable();this.show();this.container.up('div.x-form-item').setDisplayed(true);},hideField:function(){this.disable();this.hide();this.container.up('div.x-form-item').setDisplayed(false);}});Ext.namespace('Ext.Municipia.Estatisticos.data');Ext.Municipia.Estatisticos.data.bgeografica=[['3','Concelho','cb_concelhos'],['4','Freguesia','cb_freguesias'],['6','Lugar','cb_lugares']];Ext.Municipia.Estatisticos.data.distritos=[['1','Lisboa']];Ext.Municipia.Estatisticos.data.concelhos=[['1','Oeiras']];Ext.Municipia.Estatisticos.data.distrito_por_=[['3','Concelho'],['4','Freguesia']];Ext.Municipia.Estatisticos.data.concelho_por_=[['4','Freguesia'],['6','Lugar']];Ext.Municipia.Estatisticos.data.freguesia_por_=[['6','Lugar'],['7','Sub-Seco']];Ext.Municipia.Estatisticos.data.lugar_por_=[['7','Sub-Seco']];Ext.namespace('Municipia.controls','Municipia.controls.estatisticos');Municipia.controls.estatisticos.ColorForm=Ext.extend(Ext.FormPanel,{layer:null,format:null,url:null,featureSelection:true,nameAttribute:null,indicator:null,indicatorText:null,idBasePor:null,coreComp:null,classificationApplied:false,ready:false,border:false,loadMask:false,labelGenerator:null,buttonAlign:'center',initComponent:function(){var censos={xtype:'radiogroup',fieldLabel:OpenLayers.i18n('estatisticos.censos'),labelWidth:25,name:'rbCensos',id:'rbCensos',listeners:{change:{fn:function(){var cbGeografica=Ext.getCmp('cb_bgeografica');cbGeografica.ownerCt.items.each(function(cur){if(cur!=cbGeografica){cur.reset();cur.hideField();}else{cur.reset();}},this);var cbgrupo=Ext.getCmp('cb_grupos');cbgrupo.ownerCt.items.each(function(cur){cur.reset();if(cur.mode=='remote')
cur.store.reload();},this);var cbmethod=Ext.getCmp('cb_method');cbmethod.reset();if(this.ownerCt&&this.ownerCt.coreComp&&this.ownerCt.coreComp.legendDiv){this.ownerCt.coreComp.legendDiv.update("");var options={};options.indicator="";options.indicatorText="";options.method="";options.tipo="";options.subtipo="";options.nomeA="";options.nomeB="";options.nomeC="";this.ownerCt.coreComp.addOptions(options);}}},scope:this},items:[{checked:false,boxLabel:'1991',name:'rb-censos',inputValue:1991},{checked:true,boxLabel:'2001',name:'rb-censos',inputValue:2001}]};var baseGeoGraficaF=Ext.data.Record.create([{name:"id"},{name:"descricao"},{name:"target"}]);var bgeograficaStore=new Ext.data.Store({proxy:new Ext.data.HttpProxy({method:'POST',scope:this,jsonData:"{}",url:'GeocidMadeira.asmx/getBaseGeografica'}),baseParams:{'appID':app.appID,'tipoBase':'BG'},remoteSort:false,reader:new Ext.data.JsonReader({totalProperty:"totalRegistos",root:"listaPesquisa",id:'id'},baseGeoGraficaF)});var combobgeografica=new Ext.form.ComboBox({fieldLabel:OpenLayers.i18n('estatisticos.basegeografica'),name:'cb_bgeografica',id:'cb_bgeografica',hiddenContainer:false,editable:false,typeAhead:true,forceSelection:true,valueField:'target',hiddenValue:'id',displayField:'descricao',mode:'remote',emptyText:OpenLayers.i18n('estatisticos.emptytext_basegeografica'),triggerAction:'all',store:bgeograficaStore,listeners:{'select':{fn:function(combo,record,index){this.activeCbVariaveis(false);combo.ownerCt.items.each(function(cur){if(cur!=combo){cur.reset();cur.hideField();}},this);var nameTarget=combobgeografica.getValue();if(nameTarget!=''){var itemTarget=Ext.getCmp(nameTarget);itemTarget.store.removeAll();itemTarget.reset();if(itemTarget.mode=='remote')
itemTarget.store.reload();itemTarget.showField();if(combo.ownerCt&&combo.ownerCt.ownerCt&&combo.ownerCt.ownerCt.coreComp){var options={};options.subtipo=record.json.id;options.nomeA=record.json.descricao;combo.ownerCt.ownerCt.coreComp.addOptions(options);}}},scope:this}}});bgeograficaStore.on('beforeload',function(){var params=this.store.baseParams
var jsonData="{";for(var k in params){if(params[k]!="")
jsonData+="'"+k+"':'"+params[k]+"',"}
if(jsonData.length>1&&(jsonData.lastIndexOf(',')==jsonData.length-1)){jsonData=jsonData.substring(0,jsonData.length-1);}
jsonData+="}";this.store.proxy.conn.jsonData=jsonData;},combobgeografica);var distritosF=Ext.data.Record.create([{name:"di"},{name:"descricao",mapping:"nome"},{name:"shape"},{name:"xmin"},{name:"ymin"},{name:"xmax"},{name:"ymax"},{name:"datum"}]);var distritosStore=new Ext.data.Store({proxy:new Ext.data.HttpProxy({method:'POST',scope:this,jsonData:"{}",url:'GeocidMadeira.asmx/getDistritos'}),baseParams:{'appID':app.appID},remoteSort:false,reader:new Ext.data.JsonReader({totalProperty:"totalRegistos",root:"listaDistritos",id:'di'},distritosF)});var combodistritos=new Ext.form.ComboBox({fieldLabel:OpenLayers.i18n('estatisticos.distrito'),name:'cb_distritos',id:'cb_distritos',hiddenContainer:true,disabled:true,editable:false,typeAhead:true,forceSelection:true,valueField:'di',displayField:'descricao',mode:'remote',emptyText:OpenLayers.i18n('estatisticos.emptytext_distrito'),triggerAction:'all',store:distritosStore,listeners:{'select':{fn:function(combo,record,index){this.activeCbVariaveis(false);if(combo.ownerCt&&combo.ownerCt.ownerCt&&combo.ownerCt.ownerCt.coreComp){var options={};options.nomeB=record.json.nome;options.xmin=record.json.xmin;options.ymin=record.json.ymin;options.xmax=record.json.xmax;options.ymax=record.json.ymax;options.datum=record.json.datum;combo.ownerCt.ownerCt.coreComp.addOptions(options);}
combodistritospor.reset();combodistritospor.showField();},scope:this}}});distritosStore.on('beforeload',function(){var params=this.store.baseParams
var jsonData="{";for(var k in params){if(params[k]!="")
jsonData+="'"+k+"':'"+params[k]+"',"}
jsonData+="'ano':'"+Ext.getCmp('rbCensos').getValue()+"'";if(jsonData.length>1&&(jsonData.lastIndexOf(',')==jsonData.length-1)){jsonData=jsonData.substring(0,jsonData.length-1);}
jsonData+="}";this.store.proxy.conn.jsonData=jsonData;},combodistritos);var distritosporF=Ext.data.Record.create([{name:"id"},{name:"descricao"}]);var distritosporStore=new Ext.data.Store({proxy:new Ext.data.HttpProxy({method:'POST',scope:this,jsonData:"{}",url:'GeocidMadeira.asmx/getBaseGeografica'}),baseParams:{'appID':app.appID,'tipoBase':'DP'},remoteSort:false,reader:new Ext.data.JsonReader({totalProperty:"totalRegistos",root:"listaPesquisa",id:'id'},distritosporF)});var combodistritospor=new Ext.form.ComboBox({fieldLabel:OpenLayers.i18n('estatisticos.por'),name:'cb_distritos_por',id:'cb_distritos_por',hiddenContainer:true,disabled:true,editable:false,typeAhead:true,forceSelection:true,valueField:'id',displayField:'descricao',mode:'remote',emptyText:OpenLayers.i18n('estatisticos.emptytext_por'),triggerAction:'all',store:distritosporStore,listeners:{'select':{fn:function(combo,record,index){if(combo.ownerCt&&combo.ownerCt.ownerCt&&combo.ownerCt.ownerCt.coreComp){var options={};this.idBasePor=record.json.id;options.nomeC=record.json.descricao;combo.ownerCt.ownerCt.coreComp.addOptions(options);}
var di=Ext.getCmp('cb_distritos').getValue();var filter=new OpenLayers.Filter.Logical({type:OpenLayers.Filter.Logical.AND,filters:[new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO,property:(record.json.id==3?"DICO":"DICOFRE"),value:di+(record.json.id==3?"99":"9999")}),new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO,property:(record.json.id==3?"DICO":"DICOFRE"),value:di+(record.json.id==3?"00":"0000")})]});this.combo_por_activada(combo,filter,di);},scope:this}}});distritosporStore.on('beforeload',function(){var params=this.store.baseParams
var jsonData="{";for(var k in params){if(params[k]!="")
jsonData+="'"+k+"':'"+params[k]+"',"}
if(jsonData.length>1&&(jsonData.lastIndexOf(',')==jsonData.length-1)){jsonData=jsonData.substring(0,jsonData.length-1);}
jsonData+="}";this.store.proxy.conn.jsonData=jsonData;},combodistritospor);var concF=Ext.data.Record.create([{name:"dico"},{name:"descricao",mapping:"nome"},{name:"shape"},{name:"xmin"},{name:"ymin"},{name:"xmax"},{name:"ymax"},{name:"datum"}]);var concelhosStore=new Ext.data.Store({proxy:new Ext.data.HttpProxy({method:'POST',scope:this,jsonData:"{}",url:'GeocidMadeira.asmx/getConcelhos'}),baseParams:{'appID':app.appID},remoteSort:false,reader:new Ext.data.JsonReader({totalProperty:"totalRegistos",root:"listaConcelhos",id:'dico'},concF)});var comboconcelhos=new Ext.form.ComboBox({fieldLabel:OpenLayers.i18n('estatisticos.concelho'),name:'cb_concelhos',id:'cb_concelhos',hiddenContainer:true,disabled:true,editable:false,typeAhead:true,forceSelection:true,valueField:'dico',displayField:'descricao',mode:'remote',emptyText:OpenLayers.i18n('estatisticos.emptytext_concelho'),triggerAction:'all',store:concelhosStore,listeners:{'select':{fn:function(combo,record,index){this.activeCbVariaveis(false);if(combo.ownerCt&&combo.ownerCt.ownerCt&&combo.ownerCt.ownerCt.coreComp){var options={};options.nomeB=record.json.nome;options.xmin=record.json.xmin;options.ymin=record.json.ymin;options.xmax=record.json.xmax;options.ymax=record.json.ymax;options.datum=record.json.datum;combo.ownerCt.ownerCt.coreComp.addOptions(options);}
comboconcelhospor.reset();comboconcelhospor.showField();},scope:this}}});concelhosStore.on('beforeload',function(){var params=this.store.baseParams
var jsonData="{";for(var k in params){if(params[k]!="")
jsonData+="'"+k+"':'"+params[k]+"',"}
jsonData+="'ano':'"+Ext.getCmp('rbCensos').getValue()+"'";if(jsonData.length>1&&(jsonData.lastIndexOf(',')==jsonData.length-1)){jsonData=jsonData.substring(0,jsonData.length-1);}
jsonData+="}";this.store.proxy.conn.jsonData=jsonData;},comboconcelhos);var concelhosporF=Ext.data.Record.create([{name:"id"},{name:"descricao"}]);var concelhosporStore=new Ext.data.Store({proxy:new Ext.data.HttpProxy({method:'POST',scope:this,jsonData:"{}",url:'GeocidMadeira.asmx/getBaseGeografica'}),baseParams:{'appID':app.appID,'tipoBase':'CP'},remoteSort:false,reader:new Ext.data.JsonReader({totalProperty:"totalRegistos",root:"listaPesquisa",id:'id'},concelhosporF)});var comboconcelhospor=new Ext.form.ComboBox({fieldLabel:OpenLayers.i18n('estatisticos.por'),name:'cb_concelhos_por',id:'cb_concelhos_por',hiddenContainer:true,disabled:true,editable:false,typeAhead:true,forceSelection:true,valueField:'id',displayField:'descricao',mode:'remote',emptyText:OpenLayers.i18n('estatisticos.emptytext_por'),triggerAction:'all',store:concelhosporStore,listeners:{'select':{fn:function(combo,record,index){if(combo.ownerCt&&combo.ownerCt.ownerCt&&combo.ownerCt.ownerCt.coreComp){var options={};this.idBasePor=record.json.id;options.nomeC=record.json.descricao;combo.ownerCt.ownerCt.coreComp.addOptions(options);}
var dico=Ext.getCmp('cb_concelhos').getValue();var filter_1_1=new OpenLayers.Format.Filter({version:"1.1.0"});var xml=new OpenLayers.Format.XML();var filter=new OpenLayers.Filter.Logical({type:OpenLayers.Filter.Logical.AND,filters:[new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO,property:"DICOFRE",value:dico+"99"}),new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO,property:"DICOFRE",value:dico+"00"})]});this.combo_por_activada(combo,filter,dico);},scope:this}}});concelhosporStore.on('beforeload',function(){var params=this.store.baseParams
var jsonData="{";for(var k in params){if(params[k]!="")
jsonData+="'"+k+"':'"+params[k]+"',"}
if(jsonData.length>1&&(jsonData.lastIndexOf(',')==jsonData.length-1)){jsonData=jsonData.substring(0,jsonData.length-1);}
jsonData+="}";this.store.proxy.conn.jsonData=jsonData;},comboconcelhospor);var fregF=Ext.data.Record.create([{name:"dicofre",mapping:"dicofre"},{name:"descricao",mapping:"nome"},{name:"shape"},{name:"xmin"},{name:"ymin"},{name:"xmax"},{name:"ymax"},{name:"datum"}]);var freguesiasStore=new Ext.data.Store({proxy:new Ext.data.HttpProxy({method:'POST',scope:this,jsonData:"{}",url:'GeocidMadeira.asmx/getFreguesias'}),baseParams:{'appID':app.appID},remoteSort:false,reader:new Ext.data.JsonReader({totalProperty:"totalRegistos",root:"listaFreguesias",id:'dicofre'},fregF)});var combofreguesias=new Ext.form.ComboBox({fieldLabel:OpenLayers.i18n('estatisticos.freguesia'),name:'cb_freguesias',id:'cb_freguesias',hiddenContainer:true,disabled:true,editable:false,typeAhead:true,forceSelection:true,valueField:'dicofre',displayField:'descricao',mode:'remote',emptyText:OpenLayers.i18n('estatisticos.emptytext_freguesia'),triggerAction:'all',store:freguesiasStore,listeners:{'select':{fn:function(combo,record,index){this.activeCbVariaveis(false);if(combo.ownerCt&&combo.ownerCt.ownerCt&&combo.ownerCt.ownerCt.coreComp){var options={};options.nomeB=record.json.nome;options.xmin=record.json.xmin;options.ymin=record.json.ymin;options.xmax=record.json.xmax;options.ymax=record.json.ymax;options.datum=record.json.datum;combo.ownerCt.ownerCt.coreComp.addOptions(options);}
combofreguesiaspor.reset();combofreguesiaspor.showField();},scope:this}}});freguesiasStore.on('beforeload',function(){var params=this.store.baseParams
var jsonData="{";for(var k in params){if(params[k]!="")
jsonData+="'"+k+"':'"+params[k]+"',"}
jsonData+="'ano':'"+Ext.getCmp('rbCensos').getValue()+"'";if(jsonData.length>1&&(jsonData.lastIndexOf(',')==jsonData.length-1)){jsonData=jsonData.substring(0,jsonData.length-1);}
jsonData+="}";this.store.proxy.conn.jsonData=jsonData;},combofreguesias);var freguesiasporF=Ext.data.Record.create([{name:"id"},{name:"descricao"}]);var freguesiasporStore=new Ext.data.Store({proxy:new Ext.data.HttpProxy({method:'POST',scope:this,jsonData:"{}",url:'GeocidMadeira.asmx/getBaseGeografica'}),baseParams:{'appID':app.appID,'tipoBase':'FP'},remoteSort:false,reader:new Ext.data.JsonReader({totalProperty:"totalRegistos",root:"listaPesquisa",id:'id'},freguesiasporF)});var combofreguesiaspor=new Ext.form.ComboBox({fieldLabel:OpenLayers.i18n('estatisticos.por'),name:'cb_freguesias_por',id:'cb_freguesias_por',hiddenContainer:true,disabled:true,editable:false,typeAhead:true,forceSelection:true,valueField:'id',displayField:'descricao',mode:'remote',emptyText:OpenLayers.i18n('estatisticos.emptytext_por'),triggerAction:'all',store:freguesiasporStore,listeners:{'select':{fn:function(combo,record,index){if(combo.ownerCt&&combo.ownerCt.ownerCt&&combo.ownerCt.ownerCt.coreComp){var options={};this.idBasePor=record.json.id;options.nomeC=record.json.descricao;combo.ownerCt.ownerCt.coreComp.addOptions(options);}
var dicofre=Ext.getCmp('cb_freguesias').getValue();var filter_1_1=new OpenLayers.Format.Filter({version:"1.1.0"});var xml=new OpenLayers.Format.XML();var filter=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.EQUAL_TO,property:"DICOFRE",value:dicofre});this.combo_por_activada(combo,filter,dicofre);},scope:this}}});freguesiasporStore.on('beforeload',function(){var params=this.store.baseParams
var jsonData="{";for(var k in params){if(params[k]!="")
jsonData+="'"+k+"':'"+params[k]+"',"}
if(jsonData.length>1&&(jsonData.lastIndexOf(',')==jsonData.length-1)){jsonData=jsonData.substring(0,jsonData.length-1);}
jsonData+="}";this.store.proxy.conn.jsonData=jsonData;},combofreguesiaspor);var lugaresF=Ext.data.Record.create([{name:"cod"},{name:"lugar"},{name:"dicofre"},{name:"descricao",mapping:"nome"},{name:"shape"},{name:"xmin"},{name:"ymin"},{name:"xmax"},{name:"ymax"},{name:"datum"}]);var lugaresStore=new Ext.data.Store({proxy:new Ext.data.HttpProxy({method:'POST',scope:this,jsonData:"{}",url:'GeocidMadeira.asmx/getLugares'}),baseParams:{'appID':app.appID,'ano':''},remoteSort:false,reader:new Ext.data.JsonReader({totalProperty:"totalRegistos",root:"listaLugares",id:'cod'},lugaresF)});var combolugares=new Ext.form.ComboBox({fieldLabel:OpenLayers.i18n('estatisticos.lugares'),name:'cb_lugares',id:'cb_lugares',hiddenContainer:true,disabled:true,editable:false,typeAhead:true,forceSelection:true,valueField:'cod',displayField:'descricao',mode:'remote',emptyText:OpenLayers.i18n('estatisticos.emptytext_lugares'),triggerAction:'all',store:lugaresStore,listeners:{'select':{fn:function(combo,record,index){this.activeCbVariaveis(false);if(combo.ownerCt&&combo.ownerCt.ownerCt&&combo.ownerCt.ownerCt.coreComp){var options={};options.nomeB=record.json.nome;options.xmin=record.json.xmin;options.ymin=record.json.ymin;options.xmax=record.json.xmax;options.ymax=record.json.ymax;options.datum=record.json.datum;combo.ownerCt.ownerCt.coreComp.addOptions(options);}
combolugarespor.reset();combolugarespor.showField();},scope:this}}});lugaresStore.on('beforeload',function(){var params=this.store.baseParams
var jsonData="{";for(var k in params){if(params[k]!="")
jsonData+="'"+k+"':'"+params[k]+"',"}
jsonData+="'ano':'"+Ext.getCmp('rbCensos').getValue()+"'";if(jsonData.length>1&&(jsonData.lastIndexOf(',')==jsonData.length-1)){jsonData=jsonData.substring(0,jsonData.length-1);}
jsonData+="}";this.store.proxy.conn.jsonData=jsonData;},combolugares);lugaresStore.on('load',function(){var jsonData="{";},combolugares);var lugaresporF=Ext.data.Record.create([{name:"id"},{name:"descricao"}]);var lugaresporStore=new Ext.data.Store({proxy:new Ext.data.HttpProxy({method:'POST',scope:this,jsonData:"{}",url:'GeocidMadeira.asmx/getBaseGeografica'}),baseParams:{'appID':app.appID,'tipoBase':'LP'},remoteSort:false,reader:new Ext.data.JsonReader({totalProperty:"totalRegistos",root:"listaPesquisa",id:'id'},lugaresporF)});var combolugarespor=new Ext.form.ComboBox({fieldLabel:OpenLayers.i18n('estatisticos.por'),name:'cb_lugares_por',id:'cb_lugares_por',hiddenContainer:true,disabled:true,editable:false,typeAhead:true,forceSelection:true,valueField:'id',displayField:'descricao',mode:'remote',emptyText:OpenLayers.i18n('estatisticos.emptytext_por'),triggerAction:'all',store:lugaresporStore,listeners:{'select':{fn:function(combo,record,index){if(combo.ownerCt&&combo.ownerCt.ownerCt&&combo.ownerCt.ownerCt.coreComp){var options={};this.idBasePor=record.json.id;options.nomeC=record.json.descricao;combo.ownerCt.ownerCt.coreComp.addOptions(options);}
var cod=Ext.getCmp('cb_lugares').getValue();var lugar=cod.split('_')[0];var dicofre=cod.split('_')[1];var filter_1_1=new OpenLayers.Format.Filter({version:"1.1.0"});var xml=new OpenLayers.Format.XML();var filter=new OpenLayers.Filter.Logical({type:OpenLayers.Filter.Logical.AND,filters:[new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.EQUAL_TO,property:"LUGAR",value:lugar}),new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO,property:"DICOFRE",value:dicofre}),new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO,property:"DICOFRE",value:dicofre})]});this.combo_por_activada(combo,filter,lugar);},scope:this}}});lugaresporStore.on('beforeload',function(){var params=this.store.baseParams
var jsonData="{";for(var k in params){if(params[k]!="")
jsonData+="'"+k+"':'"+params[k]+"',"}
if(jsonData.length>1&&(jsonData.lastIndexOf(',')==jsonData.length-1)){jsonData=jsonData.substring(0,jsonData.length-1);}
jsonData+="}";this.store.proxy.conn.jsonData=jsonData;},combolugarespor);var subseccaoF=Ext.data.Record.create([{name:"cod"},{name:"lugar"},{name:"dicofre"},{name:"descricao",mapping:"nome"}]);var subseccaoStore=new Ext.data.Store({proxy:new Ext.data.HttpProxy({method:'POST',scope:this,jsonData:"{}",url:'GeocidMadeira.asmx/getSubSeccoes'}),baseParams:{'appID':app.appID},remoteSort:false,reader:new Ext.data.JsonReader({totalProperty:"totalRegistos",root:"listaSubSeccao",id:'cod'},subseccaoF)});var combosubseccao=new Ext.form.ComboBox({fieldLabel:OpenLayers.i18n('estatisticos.subseccao'),name:'cb_subseccao',id:'cb_subseccao',hiddenContainer:true,disabled:true,editable:false,typeAhead:true,forceSelection:true,valueField:'cod',displayField:'descricao',mode:'remote',emptyText:OpenLayers.i18n('estatisticos.emptytext_subseccao'),triggerAction:'all',store:subseccaoStore});subseccaoStore.on('beforeload',function(){var params=this.store.baseParams
var jsonData="{";for(var k in params){if(params[k]!="")
jsonData+="'"+k+"':'"+params[k]+"',"}
jsonData+="'ano':'"+Ext.getCmp('rbCensos').getValue()+"'";if(jsonData.length>1&&(jsonData.lastIndexOf(',')==jsonData.length-1)){jsonData=jsonData.substring(0,jsonData.length-1);}
jsonData+="}";this.store.proxy.conn.jsonData=jsonData;},combosubseccao);var subseccaoporF=Ext.data.Record.create([{name:"id"},{name:"descricao"}]);var subseccaoporStore=new Ext.data.Store({proxy:new Ext.data.HttpProxy({method:'POST',scope:this,jsonData:"{}",url:'GeocidMadeira.asmx/getBaseGeografica'}),baseParams:{'appID':app.appID,'tipoBase':'SSP'},remoteSort:false,reader:new Ext.data.JsonReader({totalProperty:"totalRegistos",root:"listaPesquisa",id:'id'},subseccaoporF)});var combosubseccaopor=new Ext.form.ComboBox({fieldLabel:OpenLayers.i18n('estatisticos.por'),name:'cb_subseccao_por',id:'cb_subseccao_por',hiddenContainer:true,disabled:true,editable:false,typeAhead:true,forceSelection:true,valueField:'id',displayField:'descricao',mode:'remote',emptyText:OpenLayers.i18n('estatisticos.emptytext_por'),triggerAction:'all',store:subseccaoporStore,listeners:{'select':{fn:function(combo,record,index){if(combo.ownerCt&&combo.ownerCt.ownerCt&&combo.ownerCt.ownerCt.coreComp){var options={};this.idBasePor=record.json.id;options.nomeC=record.json.descricao;combo.ownerCt.ownerCt.coreComp.addOptions(options);}
var cod=Ext.getCmp('cb_subseccao').getValue();var lugar=cod.split('_')[0];var dicofre=cod.split('_')[1];var filter_1_1=new OpenLayers.Format.Filter({version:"1.1.0"});var xml=new OpenLayers.Format.XML();var filter=new OpenLayers.Filter.Logical({type:OpenLayers.Filter.Logical.AND,filters:[new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.EQUAL_TO,property:"LUGAR",value:lugar}),new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO,property:"DICOFRE",value:dicofre}),new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO,property:"DICOFRE",value:dicofre})]});var sqlFilter="lugar="+lugar+" and dicofre="+dicofre;this.combo_por_activada(combo,filter,sqlFilter);},scope:this}}});subseccaoporStore.on('beforeload',function(){var params=this.store.baseParams
var jsonData="{";for(var k in params){if(params[k]!="")
jsonData+="'"+k+"':'"+params[k]+"',"}
if(jsonData.length>1&&(jsonData.lastIndexOf(',')==jsonData.length-1)){jsonData=jsonData.substring(0,jsonData.length-1);}
jsonData+="}";this.store.proxy.conn.jsonData=jsonData;},combosubseccaopor);var baseGeografica={xtype:'fieldset',title:OpenLayers.i18n('estatisticos.fs_basegeografica'),autoHeight:true,defaultType:'combo',items:[combobgeografica,combodistritos,comboconcelhos,combofreguesias,combolugares,combodistritospor,comboconcelhospor,combofreguesiaspor,combolugarespor]};var grupoF=Ext.data.Record.create([{name:"id"},{name:"descricao"}]);var gruposStore=new Ext.data.Store({proxy:new Ext.data.HttpProxy({method:'POST',scope:this,jsonData:"{}",url:'GeocidMadeira.asmx/getGrupos'}),baseParams:{'appID':app.appID},remoteSort:false,reader:new Ext.data.JsonReader({totalProperty:"totalRegistos",root:"listaGrupos",id:'id'},grupoF),listeners:{'beforeload':{fn:function(store,options){var params=store.baseParams
var jsonData="{";for(var k in params){if(params[k]!="")
jsonData+="'"+k+"':'"+params[k]+"',"}
jsonData+="'ano':'"+Ext.getCmp('rbCensos').getValue()+"',";jsonData+="'idBasePor':'"+this.idBasePor+"',";if(jsonData.length>1&&(jsonData.lastIndexOf(',')==jsonData.length-1)){jsonData=jsonData.substring(0,jsonData.length-1);}
jsonData+="}";store.proxy.conn.jsonData=jsonData;},scope:this}}});var combogrupos=new Ext.form.ComboBox({fieldLabel:OpenLayers.i18n('estatisticos.grupo'),name:'cb_grupos',id:'cb_grupos',hiddenContainer:false,disabled:true,editable:false,typeAhead:true,forceSelection:true,valueField:'id',displayField:'descricao',mode:'remote',emptyText:OpenLayers.i18n('estatisticos.emptytext_grupo'),triggerAction:'all',store:gruposStore});var variavelF=Ext.data.Record.create([{name:"id"},{name:"descricao"},{name:"coluna_ref"}]);var variaveisStore=new Ext.data.Store({proxy:new Ext.data.HttpProxy({method:'POST',scope:this,jsonData:"{}",url:'GeocidMadeira.asmx/getVariaveis'}),baseParams:{'appID':app.appID},remoteSort:false,reader:new Ext.data.JsonReader({totalProperty:"totalRegistos",root:"listaVariaveis",id:'id'},variavelF),listeners:{'beforeload':{fn:function(store,options){var params=store.baseParams
var jsonData="{";for(var k in params){if(params[k]!="")
jsonData+="'"+k+"':'"+params[k]+"',";}
jsonData+="'idBasePor':'"+this.idBasePor+"',";jsonData+="'grupo':'"+Ext.getCmp('cb_grupos').getValue()+"',";jsonData+="'ano':'"+Ext.getCmp('rbCensos').getValue()+"'";if(jsonData.length>1&&(jsonData.lastIndexOf(',')==jsonData.length-1)){jsonData=jsonData.substring(0,jsonData.length-1);}
jsonData+="}";store.proxy.conn.jsonData=jsonData;},scope:this}}});var combovariaveis=new Ext.form.ComboBox({fieldLabel:OpenLayers.i18n('estatisticos.variavel'),name:'indicator',id:'indicator',hiddenContainer:false,disabled:true,editable:false,typeAhead:true,forceSelection:true,valueField:'coluna_ref',displayField:'descricao',mode:'remote',emptyText:OpenLayers.i18n('estatisticos.emptytext_variavel'),triggerAction:'all',store:variaveisStore,listWidth:230,listeners:{'select':{fn:function(){},scope:this}}});var variaveisFS=new Ext.form.FieldSet({title:OpenLayers.i18n('estatisticos.fs_variavel'),hidden:false,autoHeight:true,defaultType:'combo',items:[combogrupos,combovariaveis]});combogrupos.on('select',function(combo,record,index){combovariaveis.reset();combovariaveis.store.reload();combovariaveis.showField();});var classesFS=new Ext.form.FieldSet({title:OpenLayers.i18n('estatisticos.fs_classes'),hidden:false,autoHeight:true,defaultType:'combo',items:[{xtype:'combo',fieldLabel:OpenLayers.i18n('estatisticos.metodo'),name:'method',id:'cb_method',hiddenName:'method',editable:false,valueField:'value',displayField:'text',mode:'local',emptyText:OpenLayers.i18n('estatisticos.emptytext_metodo'),triggerAction:'all',store:new Ext.data.SimpleStore({fields:['value','text'],data:[['CLASSIFY_BY_EQUAL_INTERVALS',OpenLayers.i18n('estatisticos.metodo.intervalo_igual')],['CLASSIFY_BY_QUANTILS',OpenLayers.i18n('estatisticos.metodo.quantidades')]]}),listeners:{'select':{fn:function(){},scope:this}}},{xtype:'combo',fieldLabel:OpenLayers.i18n('estatisticos.n_classes'),name:'numClasses',editable:false,valueField:'value',displayField:'value',mode:'local',value:5,triggerAction:'all',store:new Ext.data.SimpleStore({fields:['value'],data:[[3],[4],[5],[6],[7]]}),listeners:{'select':{fn:function(){},scope:this}}},{xtype:'colorfield',fieldLabel:OpenLayers.i18n('estatisticos.cor_1'),name:'colorA',width:100,allowBlank:false,readOnly:true,value:"#FFFF00",listeners:{'valid':{fn:function(){},scope:this}}},{xtype:'colorfield',fieldLabel:OpenLayers.i18n('estatisticos.cor_2'),name:'colorB',width:100,readOnly:true,allowBlank:false,value:"#FF0000",listeners:{'valid':{fn:function(){},scope:this}}}]});var btnPanel=new Ext.Panel({autoScroll:false,buttonAlign:'center'});btnPanel.addButton({text:OpenLayers.i18n('estatisticos.btn'),handler:function(){this.classify(true,true);},scope:this});var legenda=new Ext.Panel({fitContainer:true,fitToFrame:true,contentEl:"legendaEstatisticosDiv",layout:'fit',autoScroll:false});this.items=[censos,baseGeografica,variaveisFS,classesFS,btnPanel,legenda];Municipia.controls.estatisticos.ColorForm.superclass.initComponent.apply(this);},requestSuccess:function(request){this.ready=true;if(this.loadMask&&this.rendered){this.loadMask.hide();}},requestFailure:function(request){OpenLayers.Console.error('Ajax request failed');},activarLayer:function(exception,idLayer,xmlfilter,sqlFilter){var map=this.map;var options={};var layer=null;for(var i=0;i<map.layers.length;++i){var olLayer=map.layers[i];if(!olLayer.isBaseLayer&&olLayer.CLASS_NAME&&olLayer.CLASS_NAME=='OpenLayers.Layer.WMS'){olLayer.setVisibility(false);var idEstatisticos=Municipia.Util.getProperty(olLayer,"id_estatisticos");if(idEstatisticos==idLayer+'_'+Ext.getCmp('rbCensos').getValue()){layer=olLayer;options.tipo=idLayer;}}}
options.layer=layer;options.filter=sqlFilter;if(!options.layer){if(exception){Ext.MessageBox.alert('Erro',OpenLayers.i18n('estatisticos.empty_layer'));}
this.ready=false;return;}
this.ready=true;if(xmlfilter){layer.params.filter="("+xmlfilter+")";}
this.coreComp.addOptions(options);},combo_por_activada:function(combo,filter,sqlFilter){var filter_1_1=new OpenLayers.Format.Filter({version:"1.1.0"});var xml=new OpenLayers.Format.XML();var xmlFilter=null;try{xmlFilter=xml.write(filter_1_1.write(filter));}catch(err){if(err.lineNumber!=undefined){alert(" (line "+err.lineNumber+" "+err.fileName+")");}}
this.activarLayer(false,combo.getValue(),xmlFilter,sqlFilter);this.activeCbVariaveis(true);},activeCbVariaveis:function(flag){var cbVariaveis=Ext.getCmp('indicator');if(cbVariaveis){cbVariaveis.reset();if(flag){cbVariaveis.enable();}else{cbVariaveis.disable();}}
var cbGrupos=Ext.getCmp('cb_grupos');if(cbGrupos){cbGrupos.reset();cbGrupos.store.reload();if(flag){cbGrupos.enable();}else{cbGrupos.disable();}}},getColors:function(){var colorA=new Municipia.ColorRgb();colorA.setFromHex(this.form.findField('colorA').getValue());var colorB=new Municipia.ColorRgb();colorB.setFromHex(this.form.findField('colorB').getValue());return[colorA,colorB];},classify:function(exception,forceRedraw){if(!this.ready||!this.coreComp.layer){if(exception){Ext.MessageBox.alert('Erro',OpenLayers.i18n('estatisticos.empty_bg'));}
return false;}
var options={};this.indicator=this.form.findField('indicator').getValue();this.indicatorText=this.form.findField('indicator').getRawValue()+' ('+Ext.getCmp('rbCensos').getValue()+')';options.indicator=this.indicator;options.indicatorText=this.indicatorText;if(!options.indicator){if(exception){Ext.MessageBox.alert('Erro',OpenLayers.i18n('estatisticos.empty_variavel'));}
return false;}
options.method=this.form.findField('method').getValue();if(!options.method){if(exception){Ext.MessageBox.alert('Erro',OpenLayers.i18n('estatisticos.empty_indicador'));}
return false;}
options.method=Municipia.GeoStat.Distribution[options.method];options.numClasses=this.form.findField('numClasses').getValue();options.colors=this.getColors();var alteracao=this.coreComp.updateOptions(options);if(alteracao||forceRedraw){this.coreComp.applyClassification();}
this.classificationApplied=true;return true;},onRender:function(ct,position){Municipia.controls.estatisticos.ColorForm.superclass.onRender.apply(this,arguments);if(this.loadMask){this.loadMask=new Ext.LoadMask(this.bwrap,this.loadMask);this.loadMask.show();}
var coreOptions={'layer':this.layer,'format':this.format,'url':this.url,'requestSuccess':this.requestSuccess.createDelegate(this),'requestFailure':this.requestFailure.createDelegate(this),'featureSelection':this.featureSelection,'nameAttribute':this.nameAttribute,'legendDiv':this.legendDiv,'labelGenerator':this.labelGenerator,'loadMask':this.loadMask};this.coreComp=new Municipia.GeoStat.Choropleth(this.map,coreOptions);}});Ext.reg('ColorForm',Municipia.controls.estatisticos.ColorForm);