
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return!a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();
if(typeof(SAPO)=='undefined'){window.SAPO={};}
else{window.SAPO=SAPO;}
if(typeof(SAPO.Maps)=='undefined'){window.SAPO.Maps={};}
else{window.SAPO.Maps=SAPO.Maps;}
if(typeof(OpenLayers)=='undefined'){window.OpenLayers={_getScriptLocation:function(){var scriptLocation="";var scriptName=SAPO.Maps._scriptName;var scripts=document.getElementsByTagName('script');for(var i=0,len=scripts.length;i<len;i++){var src=scripts[i].getAttribute('src');if(src){var index=src.lastIndexOf(scriptName);var pathLength=src.lastIndexOf('?');if(pathLength<0){pathLength=src.length;}
if((index>-1)&&(index+scriptName.length==pathLength)){scriptLocation=src.slice(0,pathLength-scriptName.length);break;}}}
return scriptLocation+"OpenLayers-2.7/";}};}
else{window.OpenLayers=OpenLayers;}
OpenLayers.Util={};OpenLayers.Util.getElement=function(){var elements=[];for(var i=0,len=arguments.length;i<len;i++){var element=arguments[i];if(typeof element=='string'){element=document.getElementById(element);}
if(arguments.length==1){return element;}
elements.push(element);}
return elements;};OpenLayers.Util.extend=function(destination,source){destination=destination||{};if(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;};OpenLayers.Util.removeItem=function(array,item){for(var i=array.length-1;i>=0;i--){if(array[i]==item){array.splice(i,1);}}
return array;};OpenLayers.Util.clearArray=function(array){OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",{'newMethod':'array = []'}));array.length=0;};OpenLayers.Util.indexOf=function(array,obj){for(var i=0,len=array.length;i<len;i++){if(array[i]==obj){return i;}}
return-1;};OpenLayers.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='';}};OpenLayers.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=OpenLayers.Util.createUniqueID("OpenLayersDiv");}
if(!position){position="absolute";}
OpenLayers.Util.modifyDOMElement(dom,id,px,sz,position,border,overflow,opacity);return dom;};OpenLayers.Util.createImage=function(id,px,sz,imgURL,position,border,opacity,delayDisplay){var image=document.createElement("img");if(!id){id=OpenLayers.Util.createUniqueID("OpenLayersDiv");}
if(!position){position="relative";}
OpenLayers.Util.modifyDOMElement(image,id,px,sz,position,border,null,opacity);if(delayDisplay){image.style.display="none";OpenLayers.Event.observe(image,"load",OpenLayers.Function.bind(OpenLayers.Util.onImageLoad,image));OpenLayers.Event.observe(image,"error",OpenLayers.Function.bind(OpenLayers.Util.onImageLoadError,image));}
image.style.alt=id;image.galleryImg="no";if(imgURL){image.src=imgURL;}
return image;};OpenLayers.Util.setOpacity=function(element,opacity){OpenLayers.Util.modifyDOMElement(element,null,null,null,null,null,null,opacity);};OpenLayers.Util.onImageLoad=function(){if(!this.viewRequestID||(this.map&&this.viewRequestID==this.map.viewRequestID)){this.style.backgroundColor="transparent";this.style.display="";}};OpenLayers.Util.onImageLoadErrorColor="pink";OpenLayers.IMAGE_RELOAD_ATTEMPTS=0;OpenLayers.Util.onImageLoadError=function(){this._attempts=(this._attempts)?(this._attempts+1):1;if(this._attempts<=OpenLayers.IMAGE_RELOAD_ATTEMPTS){var urls=this.urls;if(urls&&urls instanceof Array&&urls.length>1){var src=this.src.toString();var current_url,k;for(k=0;current_url=urls[k];k++){if(src.indexOf(current_url)!=-1){break;}}
var guess=Math.floor(urls.length*Math.random());var new_url=urls[guess];k=0;while(new_url==current_url&&k++<4){guess=Math.floor(urls.length*Math.random());new_url=urls[guess];}
this.src=src.replace(current_url,new_url);}else{this.src=this.src;}}else{this.style.backgroundColor=OpenLayers.Util.onImageLoadErrorColor;}
this.style.display="";};OpenLayers.Util.alphaHackNeeded=null;OpenLayers.Util.alphaHack=function(){if(OpenLayers.Util.alphaHackNeeded==null){var arVersion=navigator.appVersion.split("MSIE");var version=parseFloat(arVersion[1]);var filter=false;try{filter=!!(document.body.filters);}catch(e){}
OpenLayers.Util.alphaHackNeeded=(filter&&(version>=5.5)&&(version<7));}
return OpenLayers.Util.alphaHackNeeded;};OpenLayers.Util.modifyAlphaImageDiv=function(div,id,px,sz,imgURL,position,border,sizing,opacity){OpenLayers.Util.modifyDOMElement(div,id,px,sz,position,null,null,opacity);var img=div.childNodes[0];if(imgURL){img.src=imgURL;}
OpenLayers.Util.modifyDOMElement(img,div.id+"_innerImage",null,sz,"relative",border);if(OpenLayers.Util.alphaHack()){if(div.style.display!="none"){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)";}};OpenLayers.Util.createAlphaImageDiv=function(id,px,sz,imgURL,position,border,sizing,opacity,delayDisplay){var div=OpenLayers.Util.createDiv();var img=OpenLayers.Util.createImage(null,null,null,null,null,null,null,false);div.appendChild(img);if(delayDisplay){img.style.display="none";OpenLayers.Event.observe(img,"load",OpenLayers.Function.bind(OpenLayers.Util.onImageLoad,div));OpenLayers.Event.observe(img,"error",OpenLayers.Function.bind(OpenLayers.Util.onImageLoadError,div));}
OpenLayers.Util.modifyAlphaImageDiv(div,id,px,sz,imgURL,position,border,sizing,opacity);return div;};OpenLayers.Util.upperCaseObject=function(object){var uObject={};for(var key in object){uObject[key.toUpperCase()]=object[key];}
return uObject;};OpenLayers.Util.applyDefaults=function(to,from){to=to||{};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&&from.hasOwnProperty&&from.hasOwnProperty('toString')&&!to.hasOwnProperty('toString')){to.toString=from.toString;}
return to;};OpenLayers.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,len=value.length;itemIndex<len;itemIndex++){encodedItemArray.push(encodeURIComponent(value[itemIndex]));}
encodedValue=encodedItemArray.join(",");}
else{encodedValue=encodeURIComponent(value);}
paramsArray.push(encodeURIComponent(key)+"="+encodedValue);}}
return paramsArray.join("&");};OpenLayers.ImgPath='';OpenLayers.Util.getImagesLocation=function(){return OpenLayers.ImgPath||(OpenLayers._getScriptLocation()+"img/");};OpenLayers.Util.Try=function(){var returnValue=null;for(var i=0,len=arguments.length;i<len;i++){var lambda=arguments[i];try{returnValue=lambda();break;}catch(e){}}
return returnValue;};OpenLayers.Util.getNodes=function(p,tagName){var nodes=OpenLayers.Util.Try(function(){return OpenLayers.Util._getNodes(p.documentElement.childNodes,tagName);},function(){return OpenLayers.Util._getNodes(p.childNodes,tagName);});return nodes;};OpenLayers.Util._getNodes=function(nodes,tagName){var retArray=[];for(var i=0,len=nodes.length;i<len;i++){if(nodes[i].nodeName==tagName){retArray.push(nodes[i]);}}
return retArray;};OpenLayers.Util.getTagText=function(parent,item,index){var result=OpenLayers.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"";}};OpenLayers.Util.getXmlNodeValue=function(node){var val=null;OpenLayers.Util.Try(function(){val=node.text;if(!val){val=node.textContent;}
if(!val){val=node.firstChild.nodeValue;}},function(){val=node.textContent;});return val;};OpenLayers.Util.mouseLeft=function(evt,div){var target=(evt.relatedTarget)?evt.relatedTarget:evt.toElement;while(target!=div&&target!=null){target=target.parentNode;}
return(target!=div);};OpenLayers.Util.DEFAULT_PRECISION=14;OpenLayers.Util.toFloat=function(number,precision){if(precision==null){precision=OpenLayers.Util.DEFAULT_PRECISION;}
var number;if(precision==0){number=parseFloat(number);}else{number=parseFloat(parseFloat(number).toPrecision(precision));}
return number;};OpenLayers.Util.rad=function(x){return x*Math.PI/180;};OpenLayers.Util.distVincenty=function(p1,p2){var a=6378137,b=6356752.3142,f=1/298.257223563;var L=OpenLayers.Util.rad(p2.lon-p1.lon);var U1=Math.atan((1-f)*Math.tan(OpenLayers.Util.rad(p1.lat)));var U2=Math.atan((1-f)*Math.tan(OpenLayers.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;};OpenLayers.Util.getParameters=function(url){url=url||window.location.href;var paramsString="";if(OpenLayers.String.contains(url,'?')){var start=url.indexOf('?')+1;var end=OpenLayers.String.contains(url,"#")?url.indexOf('#'):url.length;paramsString=url.substring(start,end);}
var parameters={};var pairs=paramsString.split(/[&;]/);for(var i=0,len=pairs.length;i<len;++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,jlen=value.length;j<jlen;j++){value[j]=decodeURIComponent(value[j]);}
if(value.length==1){value=value[0];}
parameters[key]=value;}}
return parameters;};OpenLayers.Util.getArgs=function(url){OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",{'newMethod':'OpenLayers.Util.getParameters'}));return OpenLayers.Util.getParameters(url);};OpenLayers.Util.lastSeqID=0;OpenLayers.Util.createUniqueID=function(prefix){if(prefix==null){prefix="id_";}
OpenLayers.Util.lastSeqID+=1;return prefix+OpenLayers.Util.lastSeqID;};OpenLayers.INCHES_PER_UNIT={'inches':1.0,'ft':12.0,'mi':63360.0,'m':39.3701,'km':39370.1,'dd':4374754,'yd':36};OpenLayers.INCHES_PER_UNIT["in"]=OpenLayers.INCHES_PER_UNIT.inches;OpenLayers.INCHES_PER_UNIT["degrees"]=OpenLayers.INCHES_PER_UNIT.dd;OpenLayers.INCHES_PER_UNIT["nmi"]=1852*OpenLayers.INCHES_PER_UNIT.m;OpenLayers.METERS_PER_INCH=0.02540005080010160020;OpenLayers.Util.extend(OpenLayers.INCHES_PER_UNIT,{"Inch":OpenLayers.INCHES_PER_UNIT.inches,"Meter":1.0/OpenLayers.METERS_PER_INCH,"Foot":0.30480060960121920243/OpenLayers.METERS_PER_INCH,"IFoot":0.30480000000000000000/OpenLayers.METERS_PER_INCH,"ClarkeFoot":0.3047972651151/OpenLayers.METERS_PER_INCH,"SearsFoot":0.30479947153867624624/OpenLayers.METERS_PER_INCH,"GoldCoastFoot":0.30479971018150881758/OpenLayers.METERS_PER_INCH,"IInch":0.02540000000000000000/OpenLayers.METERS_PER_INCH,"MicroInch":0.00002540000000000000/OpenLayers.METERS_PER_INCH,"Mil":0.00000002540000000000/OpenLayers.METERS_PER_INCH,"Centimeter":0.01000000000000000000/OpenLayers.METERS_PER_INCH,"Kilometer":1000.00000000000000000000/OpenLayers.METERS_PER_INCH,"Yard":0.91440182880365760731/OpenLayers.METERS_PER_INCH,"SearsYard":0.914398414616029/OpenLayers.METERS_PER_INCH,"IndianYard":0.91439853074444079983/OpenLayers.METERS_PER_INCH,"IndianYd37":0.91439523/OpenLayers.METERS_PER_INCH,"IndianYd62":0.9143988/OpenLayers.METERS_PER_INCH,"IndianYd75":0.9143985/OpenLayers.METERS_PER_INCH,"IndianFoot":0.30479951/OpenLayers.METERS_PER_INCH,"IndianFt37":0.30479841/OpenLayers.METERS_PER_INCH,"IndianFt62":0.3047996/OpenLayers.METERS_PER_INCH,"IndianFt75":0.3047995/OpenLayers.METERS_PER_INCH,"Mile":1609.34721869443738887477/OpenLayers.METERS_PER_INCH,"IYard":0.91440000000000000000/OpenLayers.METERS_PER_INCH,"IMile":1609.34400000000000000000/OpenLayers.METERS_PER_INCH,"NautM":1852.00000000000000000000/OpenLayers.METERS_PER_INCH,"Lat-66":110943.316488932731/OpenLayers.METERS_PER_INCH,"Lat-83":110946.25736872234125/OpenLayers.METERS_PER_INCH,"Decimeter":0.10000000000000000000/OpenLayers.METERS_PER_INCH,"Millimeter":0.00100000000000000000/OpenLayers.METERS_PER_INCH,"Dekameter":10.00000000000000000000/OpenLayers.METERS_PER_INCH,"Decameter":10.00000000000000000000/OpenLayers.METERS_PER_INCH,"Hectometer":100.00000000000000000000/OpenLayers.METERS_PER_INCH,"GermanMeter":1.0000135965/OpenLayers.METERS_PER_INCH,"CaGrid":0.999738/OpenLayers.METERS_PER_INCH,"ClarkeChain":20.1166194976/OpenLayers.METERS_PER_INCH,"GunterChain":20.11684023368047/OpenLayers.METERS_PER_INCH,"BenoitChain":20.116782494375872/OpenLayers.METERS_PER_INCH,"SearsChain":20.11676512155/OpenLayers.METERS_PER_INCH,"ClarkeLink":0.201166194976/OpenLayers.METERS_PER_INCH,"GunterLink":0.2011684023368047/OpenLayers.METERS_PER_INCH,"BenoitLink":0.20116782494375872/OpenLayers.METERS_PER_INCH,"SearsLink":0.2011676512155/OpenLayers.METERS_PER_INCH,"Rod":5.02921005842012/OpenLayers.METERS_PER_INCH,"IntnlChain":20.1168/OpenLayers.METERS_PER_INCH,"IntnlLink":0.201168/OpenLayers.METERS_PER_INCH,"Perch":5.02921005842012/OpenLayers.METERS_PER_INCH,"Pole":5.02921005842012/OpenLayers.METERS_PER_INCH,"Furlong":201.1684023368046/OpenLayers.METERS_PER_INCH,"Rood":3.778266898/OpenLayers.METERS_PER_INCH,"CapeFoot":0.3047972615/OpenLayers.METERS_PER_INCH,"Brealey":375.00000000000000000000/OpenLayers.METERS_PER_INCH,"ModAmFt":0.304812252984505969011938/OpenLayers.METERS_PER_INCH,"Fathom":1.8288/OpenLayers.METERS_PER_INCH,"NautM-UK":1853.184/OpenLayers.METERS_PER_INCH,"50kilometers":50000.0/OpenLayers.METERS_PER_INCH,"150kilometers":150000.0/OpenLayers.METERS_PER_INCH});OpenLayers.Util.extend(OpenLayers.INCHES_PER_UNIT,{"mm":OpenLayers.INCHES_PER_UNIT["Meter"]/1000.0,"cm":OpenLayers.INCHES_PER_UNIT["Meter"]/100.0,"dm":OpenLayers.INCHES_PER_UNIT["Meter"]*100.0,"km":OpenLayers.INCHES_PER_UNIT["Meter"]*1000.0,"kmi":OpenLayers.INCHES_PER_UNIT["nmi"],"fath":OpenLayers.INCHES_PER_UNIT["Fathom"],"ch":OpenLayers.INCHES_PER_UNIT["IntnlChain"],"link":OpenLayers.INCHES_PER_UNIT["IntnlLink"],"us-in":OpenLayers.INCHES_PER_UNIT["inches"],"us-ft":OpenLayers.INCHES_PER_UNIT["Foot"],"us-yd":OpenLayers.INCHES_PER_UNIT["Yard"],"us-ch":OpenLayers.INCHES_PER_UNIT["GunterChain"],"us-mi":OpenLayers.INCHES_PER_UNIT["Mile"],"ind-yd":OpenLayers.INCHES_PER_UNIT["IndianYd37"],"ind-ft":OpenLayers.INCHES_PER_UNIT["IndianFt37"],"ind-ch":20.11669506/OpenLayers.METERS_PER_INCH});OpenLayers.DOTS_PER_INCH=72;OpenLayers.Util.normalizeScale=function(scale){var normScale=(scale>1.0)?(1.0/scale):scale;return normScale;};OpenLayers.Util.getResolutionFromScale=function(scale,units){if(units==null){units="degrees";}
var normScale=OpenLayers.Util.normalizeScale(scale);var resolution=1/(normScale*OpenLayers.INCHES_PER_UNIT[units]*OpenLayers.DOTS_PER_INCH);return resolution;};OpenLayers.Util.getScaleFromResolution=function(resolution,units){if(units==null){units="degrees";}
var scale=resolution*OpenLayers.INCHES_PER_UNIT[units]*OpenLayers.DOTS_PER_INCH;return scale;};OpenLayers.Util.safeStopPropagation=function(evt){OpenLayers.Event.stop(evt,true);};OpenLayers.Util.pagePosition=function(forElement){var valueT=0,valueL=0;var element=forElement;var child=forElement;while(element){if(element==document.body){if(OpenLayers.Element.getStyle(child,'position')=='absolute'){break;}}
valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;child=element;try{element=element.offsetParent;}catch(e){OpenLayers.Console.error(OpenLayers.i18n("pagePositionFailed",{'elemId':element.id}));break;}}
element=forElement;while(element){valueT-=element.scrollTop||0;valueL-=element.scrollLeft||0;element=element.parentNode;}
return[valueL,valueT];};OpenLayers.Util.isEquivalentUrl=function(url1,url2,options){options=options||{};OpenLayers.Util.applyDefaults(options,{ignoreCase:true,ignorePort80:true,ignoreHash:true});var urlObj1=OpenLayers.Util.createUrlObject(url1,options);var urlObj2=OpenLayers.Util.createUrlObject(url2,options);for(var key in urlObj1){if(key!=="args"){if(urlObj1[key]!=urlObj2[key]){return false;}}}
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;};OpenLayers.Util.createUrlObject=function(url,options){options=options||{};if(!(/^\w+:\/\//).test(url)){var loc=window.location;var port=loc.port?":"+loc.port:"";var fullUrl=loc.protocol+"//"+loc.host.split(":").shift()+port;if(url.indexOf("/")===0){url=fullUrl+url;}else{var parts=loc.pathname.split("/");parts.pop();url=fullUrl+parts.join("/")+"/"+url;}}
if(options.ignoreCase){url=url.toLowerCase();}
var a=document.createElement('a');a.href=url;var urlObject={};urlObject.host=a.host.split(":").shift();urlObject.protocol=a.protocol;if(options.ignorePort80){urlObject.port=(a.port=="80"||a.port=="0")?"":a.port;}else{urlObject.port=(a.port==""||a.port=="0")?"80":a.port;}
urlObject.hash=(options.ignoreHash||a.hash==="#")?"":a.hash;var queryString=a.search;if(!queryString){var qMark=url.indexOf("?");queryString=(qMark!=-1)?url.substr(qMark):"";}
urlObject.args=OpenLayers.Util.getParameters(queryString);urlObject.pathname=(a.pathname.charAt(0)=="/")?a.pathname:"/"+a.pathname;return urlObject;};OpenLayers.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;};OpenLayers.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;};OpenLayers.Util.getRenderedDimensions=function(contentHTML,size,options){var w,h;var container=document.createElement("div");container.style.visibility="hidden";var containerElement=(options&&options.containerElement)?options.containerElement:document.body;if(size){if(size.w){w=size.w;container.style.width=w+"px";}else if(size.h){h=size.h;container.style.height=h+"px";}}
if(options&&options.displayClass){container.className=options.displayClass;}
var content=document.createElement("div");content.innerHTML=contentHTML;content.style.overflow="visible";if(content.childNodes){for(var i=0,l=content.childNodes.length;i<l;i++){if(!content.childNodes[i].style)continue;content.childNodes[i].style.overflow="visible";}}
container.appendChild(content);containerElement.appendChild(container);var parentHasPositionAbsolute=false;var parent=container.parentNode;while(parent&&parent.tagName.toLowerCase()!="body"){var parentPosition=OpenLayers.Element.getStyle(parent,"position");if(parentPosition=="absolute"){parentHasPositionAbsolute=true;break;}else if(parentPosition&&parentPosition!="static"){break;}
parent=parent.parentNode;}
if(!parentHasPositionAbsolute){container.style.position="absolute";}
if(!w){w=parseInt(content.scrollWidth);container.style.width=w+"px";}
if(!h){h=parseInt(content.scrollHeight);}
container.removeChild(content);containerElement.removeChild(container);return new OpenLayers.Size(w,h);};OpenLayers.Util.getScrollbarWidth=function(){var scrollbarWidth=OpenLayers.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);OpenLayers.Util._scrollbarWidth=(wNoScroll-wScroll);scrollbarWidth=OpenLayers.Util._scrollbarWidth;}
return scrollbarWidth;};OpenLayers.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*/,'').replace(/\s\s*$/,'');},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 replacer=function(str,match){var replacement;var subs=match.split(/\.+/);for(var i=0;i<subs.length;i++){if(i==0){replacement=context;}
replacement=replacement[subs[i]];}
if(typeof replacement=="function"){replacement=args?replacement.apply(null,args):replacement();}
if(typeof replacement=='undefined'){return'undefined';}else{return replacement;}};return template.replace(OpenLayers.String.tokenRegEx,replacer);},tokenRegEx:/\$\{([\w.]+?)\}/g,numberRegEx:/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/,isNumeric:function(value){return OpenLayers.String.numberRegEx.test(value);},numericIf:function(value){return OpenLayers.String.isNumeric(value)?parseFloat(value):value;}};if(!String.prototype.startsWith){String.prototype.startsWith=function(sStart){OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",{'newMethod':'OpenLayers.String.startsWith'}));return OpenLayers.String.startsWith(this,sStart);};}
if(!String.prototype.contains){String.prototype.contains=function(str){OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",{'newMethod':'OpenLayers.String.contains'}));return OpenLayers.String.contains(this,str);};}
if(!String.prototype.trim){String.prototype.trim=function(){OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",{'newMethod':'OpenLayers.String.trim'}));return OpenLayers.String.trim(this);};}
if(!String.prototype.camelize){String.prototype.camelize=function(){OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",{'newMethod':'OpenLayers.String.camelize'}));return OpenLayers.String.camelize(this);};}
OpenLayers.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:OpenLayers.Number.thousandsSeparator;dsep=(typeof dsep!="undefined")?dsep:OpenLayers.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){OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",{'newMethod':'OpenLayers.Number.limitSigDigs'}));return OpenLayers.Number.limitSigDigs(this,sig);};}
OpenLayers.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(){OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",{'newMethod':'OpenLayers.Function.bind'}));Array.prototype.unshift.apply(arguments,[this]);return OpenLayers.Function.bind.apply(null,arguments);};}
if(!Function.prototype.bindAsEventListener){Function.prototype.bindAsEventListener=function(object){OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",{'newMethod':'OpenLayers.Function.bindAsEventListener'}));return OpenLayers.Function.bindAsEventListener(this,object);};}
OpenLayers.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;}};OpenLayers.Class=function(){var Class=function(){if(arguments&&arguments[0]!=OpenLayers.Class.isPrototype){this.initialize.apply(this,arguments);}};var extended={};var parent,initialize;for(var i=0,len=arguments.length;i<len;++i){if(typeof arguments[i]=="function"){if(i==0&&len>1){initialize=arguments[i].prototype.initialize;arguments[i].prototype.initialize=function(){};extended=new arguments[i];if(initialize===undefined){delete arguments[i].prototype.initialize;}else{arguments[i].prototype.initialize=initialize;}}
parent=arguments[i].prototype;}else{parent=arguments[i];}
OpenLayers.Util.extend(extended,parent);}
Class.prototype=extended;return Class;};OpenLayers.Class.isPrototype=function(){};OpenLayers.Class.create=function(){return function(){if(arguments&&arguments[0]!=OpenLayers.Class.isPrototype){this.initialize.apply(this,arguments);}};};OpenLayers.Class.inherit=function(){var superClass=arguments[0];var proto=new superClass(OpenLayers.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(OpenLayers.Class.isPrototype);}
OpenLayers.Util.extend(proto,arguments[i]);}
return proto;};OpenLayers.Bounds=OpenLayers.Class({left:null,bottom:null,right:null,top:null,centerLonLat:null,initialize:function(left,bottom,right,top){if(left!=null){this.left=OpenLayers.Util.toFloat(left);}
if(bottom!=null){this.bottom=OpenLayers.Util.toFloat(bottom);}
if(right!=null){this.right=OpenLayers.Util.toFloat(right);}
if(top!=null){this.top=OpenLayers.Util.toFloat(top);}},clone:function(){return new OpenLayers.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 OpenLayers.Geometry.Polygon([new OpenLayers.Geometry.LinearRing([new OpenLayers.Geometry.Point(this.left,this.bottom),new OpenLayers.Geometry.Point(this.right,this.bottom),new OpenLayers.Geometry.Point(this.right,this.top),new OpenLayers.Geometry.Point(this.left,this.top)])]);},getWidth:function(){return(this.right-this.left);},getHeight:function(){return(this.top-this.bottom);},getSize:function(){return new OpenLayers.Size(this.getWidth(),this.getHeight());},getCenterPixel:function(){return new OpenLayers.Pixel((this.left+this.right)/2,(this.bottom+this.top)/2);},getCenterLonLat:function(){if(!this.centerLonLat){this.centerLonLat=new OpenLayers.LonLat((this.left+this.right)/2,(this.bottom+this.top)/2);}
return this.centerLonLat;},scale:function(ratio,origin){if(origin==null){origin=this.getCenterLonLat();}
var bounds=[];var origx,origy;if(origin.CLASS_NAME=="OpenLayers.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 OpenLayers.Bounds(left,bottom,right,top);},add:function(x,y){if((x==null)||(y==null)){var msg=OpenLayers.i18n("boundsAddError");OpenLayers.Console.error(msg);return null;}
return new OpenLayers.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"OpenLayers.LonLat":bounds=new OpenLayers.Bounds(object.lon,object.lat,object.lon,object.lat);break;case"OpenLayers.Geometry.Point":bounds=new OpenLayers.Bounds(object.x,object.y,object.x,object.y);break;case"OpenLayers.Bounds":bounds=object;break;}
if(bounds){this.centerLonLat=null;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;}
if(x==null||y==null){return false;}
x=OpenLayers.Util.toFloat(x);y=OpenLayers.Util.toFloat(y);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 intersects=false;var mightTouch=(this.left==bounds.right||this.right==bounds.left||this.top==bounds.bottom||this.bottom==bounds.top);if(inclusive||!mightTouch){var inBottom=(((bounds.bottom>=this.bottom)&&(bounds.bottom<=this.top))||((this.bottom>=bounds.bottom)&&(this.bottom<=bounds.top)));var inTop=(((bounds.top>=this.bottom)&&(bounds.top<=this.top))||((this.top>bounds.bottom)&&(this.top<bounds.top)));var inLeft=(((bounds.left>=this.left)&&(bounds.left<=this.right))||((this.left>=bounds.left)&&(this.left<=bounds.right)));var inRight=(((bounds.right>=this.left)&&(bounds.right<=this.right))||((this.right>=bounds.left)&&(this.right<=bounds.right)));intersects=((inBottom||inTop)&&(inLeft||inRight));}
return intersects;},containsBounds:function(bounds,partial,inclusive){if(partial==null){partial=false;}
if(inclusive==null){inclusive=true;}
var bottomLeft=this.contains(bounds.left,bounds.bottom,inclusive);var bottomRight=this.contains(bounds.right,bounds.bottom,inclusive);var topLeft=this.contains(bounds.left,bounds.top,inclusive);var topRight=this.contains(bounds.right,bounds.top,inclusive);return(partial)?(bottomLeft||bottomRight||topLeft||topRight):(bottomLeft&&bottomRight&&topLeft&&topRight);},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){this.centerLonLat=null;var ll=OpenLayers.Projection.transform({'x':this.left,'y':this.bottom},source,dest);var lr=OpenLayers.Projection.transform({'x':this.right,'y':this.bottom},source,dest);var ul=OpenLayers.Projection.transform({'x':this.left,'y':this.top},source,dest);var ur=OpenLayers.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:"OpenLayers.Bounds"});OpenLayers.Bounds.fromString=function(str){var bounds=str.split(",");return OpenLayers.Bounds.fromArray(bounds);};OpenLayers.Bounds.fromArray=function(bbox){return new OpenLayers.Bounds(parseFloat(bbox[0]),parseFloat(bbox[1]),parseFloat(bbox[2]),parseFloat(bbox[3]));};OpenLayers.Bounds.fromSize=function(size){return new OpenLayers.Bounds(0,size.h,size.w,0);};OpenLayers.Bounds.oppositeQuadrant=function(quadrant){var opp="";opp+=(quadrant.charAt(0)=='t')?'b':'t';opp+=(quadrant.charAt(1)=='l')?'r':'l';return opp;};OpenLayers.Element={visible:function(element){return OpenLayers.Util.getElement(element).style.display!='none';},toggle:function(){for(var i=0,len=arguments.length;i<len;i++){var element=OpenLayers.Util.getElement(arguments[i]);var display=OpenLayers.Element.visible(element)?'hide':'show';OpenLayers.Element[display](element);}},hide:function(){for(var i=0,len=arguments.length;i<len;i++){var element=OpenLayers.Util.getElement(arguments[i]);element.style.display='none';}},show:function(){for(var i=0,len=arguments.length;i<len;i++){var element=OpenLayers.Util.getElement(arguments[i]);element.style.display='';}},remove:function(element){element=OpenLayers.Util.getElement(element);element.parentNode.removeChild(element);},getHeight:function(element){element=OpenLayers.Util.getElement(element);return element.offsetHeight;},getDimensions:function(element){element=OpenLayers.Util.getElement(element);if(OpenLayers.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(!OpenLayers.Element.hasClass(element,name)){element.className+=(element.className?" ":"")+name;}
return element;},removeClass:function(element,name){var names=element.className;if(names){element.className=OpenLayers.String.trim(names.replace(new RegExp("(^|\\s+)"+name+"(\\s+|$)")," "));}
return element;},toggleClass:function(element,name){if(OpenLayers.Element.hasClass(element,name)){OpenLayers.Element.removeClass(element,name);}else{OpenLayers.Element.addClass(element,name);}
return element;},getStyle:function(element,style){element=OpenLayers.Util.getElement(element);var value=null;if(element&&element.style){value=element.style[OpenLayers.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[OpenLayers.String.camelize(style)];}}
var positions=['left','top','right','bottom'];if(window.opera&&(OpenLayers.Util.indexOf(positions,style)!=-1)&&(OpenLayers.Element.getStyle(element,'position')=='static')){value='auto';}}
return value=='auto'?null:value;}};OpenLayers.LonLat=OpenLayers.Class({lon:0.0,lat:0.0,initialize:function(lon,lat){this.lon=OpenLayers.Util.toFloat(lon);this.lat=OpenLayers.Util.toFloat(lat);},toString:function(){return("lon="+this.lon+",lat="+this.lat);},toShortString:function(){return(this.lon+", "+this.lat);},clone:function(){return new OpenLayers.LonLat(this.lon,this.lat);},add:function(lon,lat){if((lon==null)||(lat==null)){var msg=OpenLayers.i18n("lonlatAddError");OpenLayers.Console.error(msg);return null;}
return new OpenLayers.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=OpenLayers.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:"OpenLayers.LonLat"});OpenLayers.LonLat.fromString=function(str){var pair=str.split(",");return new OpenLayers.LonLat(parseFloat(pair[0]),parseFloat(pair[1]));};OpenLayers.Pixel=OpenLayers.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 OpenLayers.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=OpenLayers.i18n("pixelAddError");OpenLayers.Console.error(msg);return null;}
return new OpenLayers.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:"OpenLayers.Pixel"});OpenLayers.Size=OpenLayers.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 OpenLayers.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:"OpenLayers.Size"});OpenLayers.Console={log:function(){},debug:function(){},info:function(){},warn:function(){},error:function(){},userError:function(error){alert(error);},assert:function(){},dir:function(){},dirxml:function(){},trace:function(){},group:function(){},groupEnd:function(){},time:function(){},timeEnd:function(){},profile:function(){},profileEnd:function(){},count:function(){},CLASS_NAME:"OpenLayers.Console"};(function(){var scripts=document.getElementsByTagName("script");for(var i=0,len=scripts.length;i<len;++i){if(scripts[i].src.indexOf("firebug.js")!=-1){if(console){OpenLayers.Util.extend(OpenLayers.Console,console);break;}}}})();OpenLayers.Tween=OpenLayers.Class({INTERVAL:10,easing:null,begin:null,finish:null,duration:null,callbacks:null,time:null,interval:null,playing:false,initialize:function(easing){this.easing=(easing)?easing:OpenLayers.Easing.Expo.easeOut;},start:function(begin,finish,duration,options){this.playing=true;this.begin=begin;this.finish=finish;this.duration=duration;this.callbacks=options.callbacks;this.time=0;if(this.interval){window.clearInterval(this.interval);this.interval=null;}
if(this.callbacks&&this.callbacks.start){this.callbacks.start.call(this,this.begin);}
this.interval=window.setInterval(OpenLayers.Function.bind(this.play,this),this.INTERVAL);},stop:function(){if(!this.playing){return;}
if(this.callbacks&&this.callbacks.done){this.callbacks.done.call(this,this.finish);}
window.clearInterval(this.interval);this.interval=null;this.playing=false;},play:function(){var value={};for(var i in this.begin){var b=this.begin[i];var f=this.finish[i];if(b==null||f==null||isNaN(b)||isNaN(f)){OpenLayers.Console.error('invalid value for Tween');}
var c=f-b;value[i]=this.easing.apply(this,[this.time,b,c,this.duration]);}
this.time++;if(this.callbacks&&this.callbacks.eachStep){this.callbacks.eachStep.call(this,value);}
if(this.time>this.duration){if(this.callbacks&&this.callbacks.done){this.callbacks.done.call(this,this.finish);this.playing=false;}
window.clearInterval(this.interval);this.interval=null;}},CLASS_NAME:"OpenLayers.Tween"});OpenLayers.Easing={CLASS_NAME:"OpenLayers.Easing"};OpenLayers.Easing.Linear={easeIn:function(t,b,c,d){return c*t/d+b;},easeOut:function(t,b,c,d){return c*t/d+b;},easeInOut:function(t,b,c,d){return c*t/d+b;},CLASS_NAME:"OpenLayers.Easing.Linear"};OpenLayers.Easing.Expo={easeIn:function(t,b,c,d){return(t==0)?b:c*Math.pow(2,10*(t/d-1))+b;},easeOut:function(t,b,c,d){return(t==d)?b+c:c*(-Math.pow(2,-10*t/d)+1)+b;},easeInOut:function(t,b,c,d){if(t==0)return b;if(t==d)return b+c;if((t/=d/2)<1)return c/2*Math.pow(2,10*(t-1))+b;return c/2*(-Math.pow(2,-10*--t)+2)+b;},CLASS_NAME:"OpenLayers.Easing.Expo"};OpenLayers.Easing.Quad={easeIn:function(t,b,c,d){return c*(t/=d)*t+b;},easeOut:function(t,b,c,d){return-c*(t/=d)*(t-2)+b;},easeInOut:function(t,b,c,d){if((t/=d/2)<1)return c/2*t*t+b;return-c/2*((--t)*(t-2)-1)+b;},CLASS_NAME:"OpenLayers.Easing.Quad"};OpenLayers.ProxyHost="";OpenLayers.nullHandler=function(request){OpenLayers.Console.userError(OpenLayers.i18n("unhandledRequest",{'statusText':request.statusText}));};OpenLayers.loadURL=function(uri,params,caller,onComplete,onFailure){if(typeof params=='string'){params=OpenLayers.Util.getParameters(params);}
var success=(onComplete)?onComplete:OpenLayers.nullHandler;var failure=(onFailure)?onFailure:OpenLayers.nullHandler;return OpenLayers.Request.GET({url:uri,params:params,success:success,failure:failure,scope:caller});};OpenLayers.parseXMLString=function(text){var index=text.indexOf('<');if(index>0){text=text.substring(index);}
var ajaxResponse=OpenLayers.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;};OpenLayers.Ajax={emptyFunction:function(){},getTransport:function(){return OpenLayers.Util.Try(function(){return new XMLHttpRequest();},function(){return new ActiveXObject('Msxml2.XMLHTTP');},function(){return new ActiveXObject('Microsoft.XMLHTTP');})||false;},activeRequestCount:0};OpenLayers.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){OpenLayers.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){}}}}};OpenLayers.Ajax.Responders.register({onCreate:function(){OpenLayers.Ajax.activeRequestCount++;},onComplete:function(){OpenLayers.Ajax.activeRequestCount--;}});OpenLayers.Ajax.Base=OpenLayers.Class({initialize:function(options){this.options={method:'post',asynchronous:true,contentType:'application/xml',parameters:''};OpenLayers.Util.extend(this.options,options||{});this.options.method=this.options.method.toLowerCase();if(typeof this.options.parameters=='string'){this.options.parameters=OpenLayers.Util.getParameters(this.options.parameters);}}});OpenLayers.Ajax.Request=OpenLayers.Class(OpenLayers.Ajax.Base,{_complete:false,initialize:function(url,options){OpenLayers.Ajax.Base.prototype.initialize.apply(this,[options]);if(OpenLayers.ProxyHost&&OpenLayers.String.startsWith(url,"http")){url=OpenLayers.ProxyHost+encodeURIComponent(url);}
this.transport=OpenLayers.Ajax.getTransport();this.request(url);},request:function(url){this.url=url;this.method=this.options.method;var params=OpenLayers.Util.extend({},this.options.parameters);if(this.method!='get'&&this.method!='post'){params['_method']=this.method;this.method='post';}
this.parameters=params;if(params=OpenLayers.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 OpenLayers.Ajax.Response(this);if(this.options.onCreate){this.options.onCreate(response);}
OpenLayers.Ajax.Responders.dispatch('onCreate',this,response);this.transport.open(this.method.toUpperCase(),this.url,this.options.asynchronous);if(this.options.asynchronous){window.setTimeout(OpenLayers.Function.bind(this.respondToReadyState,this,1),10);}
this.transport.onreadystatechange=OpenLayers.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, */*','OpenLayers':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=OpenLayers.Ajax.Request.Events[readyState];var response=new OpenLayers.Ajax.Response(this);if(state=='Complete'){try{this._complete=true;(this.options['on'+response.status]||this.options['on'+(this.success()?'Success':'Failure')]||OpenLayers.Ajax.emptyFunction)(response);}catch(e){this.dispatchException(e);}
var contentType=response.getHeader('Content-type');}
try{(this.options['on'+state]||OpenLayers.Ajax.emptyFunction)(response);OpenLayers.Ajax.Responders.dispatch('on'+state,this,response);}catch(e){this.dispatchException(e);}
if(state=='Complete'){this.transport.onreadystatechange=OpenLayers.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);OpenLayers.Ajax.Responders.dispatch('onException',this,exception);}else{var listener=false;var responders=OpenLayers.Ajax.Responders.responders;for(var i=0;i<responders.length;i++){if(responders[i].onException){listener=true;break;}}
if(listener){OpenLayers.Ajax.Responders.dispatch('onException',this,exception);}else{throw exception;}}}});OpenLayers.Ajax.Request.Events=['Uninitialized','Loading','Loaded','Interactive','Complete'];OpenLayers.Ajax.Response=OpenLayers.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:OpenLayers.Ajax.Request.prototype.getStatus,getStatusText:function(){try{return this.transport.statusText||'';}catch(e){return'';}},getHeader:OpenLayers.Ajax.Request.prototype.getHeader,getResponseHeader:function(name){return this.transport.getResponseHeader(name);}});OpenLayers.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;};OpenLayers.Ajax.serializeXMLToString=function(xmldom){var serializer=new XMLSerializer();var data=serializer.serializeToString(xmldom);return data;};OpenLayers.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=OpenLayers.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=OpenLayers.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=OpenLayers.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=OpenLayers.Util.getElement(elementParam);var cacheID=element._eventCacheID;this._removeElementObservers(OpenLayers.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=OpenLayers.Event.stopObserving.apply(this,args);}}},stopObserving:function(elementParam,name,observer,useCapture){useCapture=useCapture||false;var element=OpenLayers.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=OpenLayers.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 OpenLayers.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(OpenLayers.Event&&OpenLayers.Event.observers){for(var cacheID in OpenLayers.Event.observers){var elementObservers=OpenLayers.Event.observers[cacheID];OpenLayers.Event._removeElementObservers.apply(this,[elementObservers]);}
OpenLayers.Event.observers=false;}},CLASS_NAME:"OpenLayers.Event"};OpenLayers.Event.observe(window,'unload',OpenLayers.Event.unloadCache,false);if(window.Event){OpenLayers.Util.applyDefaults(window.Event,OpenLayers.Event);}else{var Event=OpenLayers.Event;}
OpenLayers.Events=OpenLayers.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,clearMouseListener:null,initialize:function(object,element,eventTypes,fallThrough,options){OpenLayers.Util.extend(this,options);this.object=object;this.fallThrough=fallThrough;this.listeners={};this.eventHandler=OpenLayers.Function.bindAsEventListener(this.handleBrowserEvent,this);this.clearMouseListener=OpenLayers.Function.bind(this.clearMouseCache,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){OpenLayers.Event.stopObservingElement(this.element);if(this.element.hasScrollEvent){OpenLayers.Event.stopObserving(window,"scroll",this.clearMouseListener);}}
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){OpenLayers.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);OpenLayers.Event.observe(element,eventType,this.eventHandler);}
OpenLayers.Event.observe(element,"dragstart",OpenLayers.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)&&(OpenLayers.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){OpenLayers.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){OpenLayers.Event.observe(window,"scroll",this.clearMouseListener);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=OpenLayers.Util.pagePosition(this.element);this.element.offsets[0]+=this.element.scrolls[0];this.element.offsets[1]+=this.element.scrolls[1];}
return new OpenLayers.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:"OpenLayers.Events"});OpenLayers.Request={DEFAULT_CONFIG:{method:"GET",url:window.location.href,async:true,user:undefined,password:undefined,params:null,proxy:OpenLayers.ProxyHost,headers:{},data:null,callback:function(){},success:null,failure:null,scope:null},events:new OpenLayers.Events(this,null,["complete","success","failure"]),issue:function(config){var defaultConfig=OpenLayers.Util.extend(this.DEFAULT_CONFIG,{proxy:OpenLayers.ProxyHost});config=OpenLayers.Util.applyDefaults(config,defaultConfig);var request=new OpenLayers.Request.XMLHttpRequest();var url=config.url;if(config.params){var paramString=OpenLayers.Util.getParameterString(config.params);if(paramString.length>0){var separator=(url.indexOf('?')>-1)?'&':'?';url+=separator+paramString;}}
if(config.proxy&&(url.indexOf("http")==0)){url=config.proxy+encodeURIComponent(url);}
request.open(config.method,url,config.async,config.user,config.password);for(var header in config.headers){request.setRequestHeader(header,config.headers[header]);}
var complete=(config.scope)?OpenLayers.Function.bind(config.callback,config.scope):config.callback;var success;if(config.success){success=(config.scope)?OpenLayers.Function.bind(config.success,config.scope):config.success;}
var failure;if(config.failure){failure=(config.scope)?OpenLayers.Function.bind(config.failure,config.scope):config.failure;}
var events=this.events;request.onreadystatechange=function(){if(request.readyState==OpenLayers.Request.XMLHttpRequest.DONE){var proceed=events.triggerEvent("complete",{request:request,config:config,requestUrl:url});if(proceed!==false){complete(request);if(!request.status||(request.status>=200&&request.status<300)){events.triggerEvent("success",{request:request,config:config,requestUrl:url});if(success){success(request);}}
if(request.status&&(request.status<200||request.status>=300)){events.triggerEvent("failure",{request:request,config:config,requestUrl:url});if(failure){failure(request);}}}}};if(config.async===false){request.send(config.data);}else{window.setTimeout(function(){request.send(config.data);},0);}
return request;},GET:function(config){config=OpenLayers.Util.extend(config,{method:"GET"});return OpenLayers.Request.issue(config);},POST:function(config){config=OpenLayers.Util.extend(config,{method:"POST"});config.headers=config.headers?config.headers:{};if(!("CONTENT-TYPE"in OpenLayers.Util.upperCaseObject(config.headers))){config.headers["Content-Type"]="application/xml";}
return OpenLayers.Request.issue(config);},PUT:function(config){config=OpenLayers.Util.extend(config,{method:"PUT"});config.headers=config.headers?config.headers:{};if(!("CONTENT-TYPE"in OpenLayers.Util.upperCaseObject(config.headers))){config.headers["Content-Type"]="application/xml";}
return OpenLayers.Request.issue(config);},DELETE:function(config){config=OpenLayers.Util.extend(config,{method:"DELETE"});return OpenLayers.Request.issue(config);},HEAD:function(config){config=OpenLayers.Util.extend(config,{method:"HEAD"});return OpenLayers.Request.issue(config);},OPTIONS:function(config){config=OpenLayers.Util.extend(config,{method:"OPTIONS"});return OpenLayers.Request.issue(config);}};(function(){var oXMLHttpRequest=window.XMLHttpRequest;var bGecko=!!window.controllers,bIE=window.document.all&&!window.opera;function cXMLHttpRequest(){this._object=oXMLHttpRequest?new oXMLHttpRequest:new window.ActiveXObject('Microsoft.XMLHTTP');};if(bGecko&&oXMLHttpRequest.wrapped)
cXMLHttpRequest.wrapped=oXMLHttpRequest.wrapped;cXMLHttpRequest.UNSENT=0;cXMLHttpRequest.OPENED=1;cXMLHttpRequest.HEADERS_RECEIVED=2;cXMLHttpRequest.LOADING=3;cXMLHttpRequest.DONE=4;cXMLHttpRequest.prototype.readyState=cXMLHttpRequest.UNSENT;cXMLHttpRequest.prototype.responseText="";cXMLHttpRequest.prototype.responseXML=null;cXMLHttpRequest.prototype.status=0;cXMLHttpRequest.prototype.statusText="";cXMLHttpRequest.prototype.onreadystatechange=null;cXMLHttpRequest.onreadystatechange=null;cXMLHttpRequest.onopen=null;cXMLHttpRequest.onsend=null;cXMLHttpRequest.onabort=null;cXMLHttpRequest.prototype.open=function(sMethod,sUrl,bAsync,sUser,sPassword){this._async=bAsync;var oRequest=this,nState=this.readyState;if(bIE){var fOnUnload=function(){if(oRequest._object.readyState!=cXMLHttpRequest.DONE)
fCleanTransport(oRequest);};if(bAsync)
window.attachEvent("onunload",fOnUnload);}
this._object.onreadystatechange=function(){if(bGecko&&!bAsync)
return;oRequest.readyState=oRequest._object.readyState;fSynchronizeValues(oRequest);if(oRequest._aborted){oRequest.readyState=cXMLHttpRequest.UNSENT;return;}
if(oRequest.readyState==cXMLHttpRequest.DONE){fCleanTransport(oRequest);if(bIE&&bAsync)
window.detachEvent("onunload",fOnUnload);}
if(nState!=oRequest.readyState)
fReadyStateChange(oRequest);nState=oRequest.readyState;};if(cXMLHttpRequest.onopen)
cXMLHttpRequest.onopen.apply(this,arguments);this._object.open(sMethod,sUrl,bAsync,sUser,sPassword);if(!bAsync&&bGecko){this.readyState=cXMLHttpRequest.OPENED;fReadyStateChange(this);}};cXMLHttpRequest.prototype.send=function(vData){if(cXMLHttpRequest.onsend)
cXMLHttpRequest.onsend.apply(this,arguments);if(vData&&vData.nodeType){vData=window.XMLSerializer?new window.XMLSerializer().serializeToString(vData):vData.xml;if(!this._headers["Content-Type"])
this._object.setRequestHeader("Content-Type","application/xml");}
this._object.send(vData);if(bGecko&&!this._async){this.readyState=cXMLHttpRequest.OPENED;fSynchronizeValues(this);while(this.readyState<cXMLHttpRequest.DONE){this.readyState++;fReadyStateChange(this);if(this._aborted)
return;}}};cXMLHttpRequest.prototype.abort=function(){if(cXMLHttpRequest.onabort)
cXMLHttpRequest.onabort.apply(this,arguments);if(this.readyState>cXMLHttpRequest.UNSENT)
this._aborted=true;this._object.abort();fCleanTransport(this);};cXMLHttpRequest.prototype.getAllResponseHeaders=function(){return this._object.getAllResponseHeaders();};cXMLHttpRequest.prototype.getResponseHeader=function(sName){return this._object.getResponseHeader(sName);};cXMLHttpRequest.prototype.setRequestHeader=function(sName,sValue){if(!this._headers)
this._headers={};this._headers[sName]=sValue;return this._object.setRequestHeader(sName,sValue);};cXMLHttpRequest.prototype.toString=function(){return'['+"object"+' '+"XMLHttpRequest"+']';};cXMLHttpRequest.toString=function(){return'['+"XMLHttpRequest"+']';};function fReadyStateChange(oRequest){if(oRequest.onreadystatechange)
oRequest.onreadystatechange.apply(oRequest);if(cXMLHttpRequest.onreadystatechange)
cXMLHttpRequest.onreadystatechange.apply(oRequest);};function fGetDocument(oRequest){var oDocument=oRequest.responseXML;if(bIE&&oDocument&&!oDocument.documentElement&&oRequest.getResponseHeader("Content-Type").match(/[^\/]+\/[^\+]+\+xml/)){oDocument=new ActiveXObject('Microsoft.XMLDOM');oDocument.loadXML(oRequest.responseText);}
if(oDocument)
if((bIE&&oDocument.parseError!=0)||(oDocument.documentElement&&oDocument.documentElement.tagName=="parsererror"))
return null;return oDocument;};function fSynchronizeValues(oRequest){try{oRequest.responseText=oRequest._object.responseText;}catch(e){}
try{oRequest.responseXML=fGetDocument(oRequest._object);}catch(e){}
try{oRequest.status=oRequest._object.status;}catch(e){}
try{oRequest.statusText=oRequest._object.statusText;}catch(e){}};function fCleanTransport(oRequest){oRequest._object.onreadystatechange=new window.Function;delete oRequest._headers;};if(!window.Function.prototype.apply){window.Function.prototype.apply=function(oRequest,oArguments){if(!oArguments)
oArguments=[];oRequest.__func=this;oRequest.__func(oArguments[0],oArguments[1],oArguments[2],oArguments[3],oArguments[4]);delete oRequest.__func;};};OpenLayers.Request.XMLHttpRequest=cXMLHttpRequest;})();OpenLayers.Projection=OpenLayers.Class({proj:null,projCode:null,initialize:function(projCode,options){OpenLayers.Util.extend(this,options);this.projCode=projCode;if(window.Proj4js){this.proj=new Proj4js.Proj(projCode);}},getCode:function(){return this.proj?this.proj.srsCode:this.projCode;},getUnits:function(){return this.proj?this.proj.units:null;},toString:function(){return this.getCode();},equals:function(projection){if(projection&&projection.getCode){return this.getCode()==projection.getCode();}else{return false;}},destroy:function(){delete this.proj;delete this.projCode;},CLASS_NAME:"OpenLayers.Projection"});OpenLayers.Projection.transforms={};OpenLayers.Projection.addTransform=function(from,to,method){if(!OpenLayers.Projection.transforms[from]){OpenLayers.Projection.transforms[from]={};}
OpenLayers.Projection.transforms[from][to]=method;};OpenLayers.Projection.transform=function(point,source,dest){if(source.proj&&dest.proj){point=Proj4js.transform(source.proj,dest.proj,point);}else if(source&&dest&&OpenLayers.Projection.transforms[source.getCode()]&&OpenLayers.Projection.transforms[source.getCode()][dest.getCode()]){OpenLayers.Projection.transforms[source.getCode()][dest.getCode()](point);}
return point;};OpenLayers.Map=OpenLayers.Class({Z_INDEX_BASE:{BaseLayer:100,Overlay:325,Feature:725,Popup:750,Control:1000},EVENT_TYPES:["preaddlayer","addlayer","removelayer","changelayer","movestart","move","moveend","zoomend","popupopen","popupclose","addmarker","removemarker","clearmarkers","mouseover","mouseout","mousemove","dragstart","drag","dragend","changebaselayer"],id:null,fractionalZoom:false,events:null,allOverlays:false,div:null,dragging:false,size:null,viewPortDiv:null,layerContainerOrigin:null,layerContainerDiv:null,layers:null,controls:null,popups:null,baseLayer:null,center:null,resolution:null,zoom:0,panRatio:1.5,viewRequestID:0,tileSize:null,projection:"EPSG:4326",units:'degrees',resolutions:null,maxResolution:1.40625,minResolution:null,maxScale:null,minScale:null,maxExtent:null,minExtent:null,restrictedExtent:null,numZoomLevels:16,theme:null,displayProjection:null,fallThrough:true,panTween:null,eventListeners:null,panMethod:OpenLayers.Easing.Expo.easeOut,panDuration:50,paddingForPopups:null,initialize:function(div,options){if(arguments.length===1&&typeof div==="object"){options=div;div=options&&options.div;}
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);this.theme=OpenLayers._getScriptLocation()+'theme/default/style.css';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,this.updateSize);}else{this.updateSizeDestroy=OpenLayers.Function.bind(this.updateSize,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);},render:function(div){this.div=OpenLayers.Util.getElement(div);OpenLayers.Element.addClass(this.div,'olMap');this.events.attachToElement(this.div);this.viewPortDiv.parentNode.removeChild(this.viewPortDiv);this.div.appendChild(this.viewPortDiv);this.updateSize();},unloadDestroy:null,updateSizeDestroy:null,destroy:function(){if(!this.unloadDestroy){return false;}
OpenLayers.Event.stopObserving(window,'unload',this.unloadDestroy);this.unloadDestroy=null;if(this.updateSizeDestroy){OpenLayers.Event.stopObserving(window,'resize',this.updateSizeDestroy);}else{this.events.unregister("resize",this,this.updateSize);}
this.paddingForPopups=null;if(this.controls!=null){for(var i=this.controls.length-1;i>=0;--i){this.controls[i].destroy();}
this.controls=null;}
if(this.layers!=null){for(var i=this.layers.length-1;i>=0;--i){this.layers[i].destroy(false);}
this.layers=null;}
if(this.viewPortDiv){this.div.removeChild(this.viewPortDiv);}
this.viewPortDiv=null;if(this.eventListeners){this.events.un(this.eventListeners);this.eventListeners=null;}
this.events.destroy();this.events=null;},setOptions:function(options){OpenLayers.Util.extend(this,options);},getTileSize:function(){return this.tileSize;},getBy:function(array,property,match){var test=(typeof match.test=="function");var found=OpenLayers.Array.filter(this[array],function(item){return item[property]==match||(test&&match.test(item[property]));});return found;},getLayersBy:function(property,match){return this.getBy("layers",property,match);},getLayersByName:function(match){return this.getLayersBy("name",match);},getLayersByClass:function(match){return this.getLayersBy("CLASS_NAME",match);},getControlsBy:function(property,match){return this.getBy("controls",property,match);},getControlsByClass:function(match){return this.getControlsBy("CLASS_NAME",match);},getLayer:function(id){var foundLayer=null;for(var i=0,len=this.layers.length;i<len;i++){var layer=this.layers[i];if(layer.id==id){foundLayer=layer;break;}}
return foundLayer;},setLayerZIndex:function(layer,zIdx){layer.setZIndex(this.Z_INDEX_BASE[layer.isBaseLayer?'BaseLayer':'Overlay']
+zIdx*5);},resetLayersZIndex:function(){for(var i=0,len=this.layers.length;i<len;i++){var layer=this.layers[i];this.setLayerZIndex(layer,i);}},addLayer:function(layer){for(var i=0,len=this.layers.length;i<len;i++){if(this.layers[i]==layer){var msg=OpenLayers.i18n('layerAlreadyAdded',{'layerName':layer.name});OpenLayers.Console.warn(msg);return false;}}
if(this.allOverlays){layer.isBaseLayer=false;}
this.events.triggerEvent("preaddlayer",{layer:layer});layer.div.className="olLayerDiv";layer.div.style.overflow="";this.setLayerZIndex(layer,this.layers.length);if(layer.isFixed){this.viewPortDiv.appendChild(layer.div);}else{this.layerContainerDiv.appendChild(layer.div);}
this.layers.push(layer);layer.setMap(this);if(layer.isBaseLayer||(this.allOverlays&&!this.baseLayer)){if(this.baseLayer==null){this.setBaseLayer(layer);}else{layer.setVisibility(false);}}else{layer.redraw();}
this.events.triggerEvent("addlayer",{layer:layer});layer.afterAdd();},addLayers:function(layers){for(var i=0,len=layers.length;i<len;i++){this.addLayer(layers[i]);}},removeLayer:function(layer,setNewBaseLayer){if(setNewBaseLayer==null){setNewBaseLayer=true;}
if(layer.isFixed){this.viewPortDiv.removeChild(layer.div);}else{this.layerContainerDiv.removeChild(layer.div);}
OpenLayers.Util.removeItem(this.layers,layer);layer.removeMap(this);layer.map=null;if(this.baseLayer==layer){this.baseLayer=null;if(setNewBaseLayer){for(var i=0,len=this.layers.length;i<len;i++){var iLayer=this.layers[i];if(iLayer.isBaseLayer||this.allOverlays){this.setBaseLayer(iLayer);break;}}}}
this.resetLayersZIndex();this.events.triggerEvent("removelayer",{layer:layer});},getNumLayers:function(){return this.layers.length;},getLayerIndex:function(layer){return OpenLayers.Util.indexOf(this.layers,layer);},setLayerIndex:function(layer,idx){var base=this.getLayerIndex(layer);if(idx<0){idx=0;}else if(idx>this.layers.length){idx=this.layers.length;}
if(base!=idx){this.layers.splice(base,1);this.layers.splice(idx,0,layer);for(var i=0,len=this.layers.length;i<len;i++){this.setLayerZIndex(this.layers[i],i);}
this.events.triggerEvent("changelayer",{layer:layer,property:"order"});if(this.allOverlays){if(idx===0){this.setBaseLayer(layer);}else if(this.baseLayer!==this.layers[0]){this.setBaseLayer(this.layers[0]);}}}},raiseLayer:function(layer,delta){var idx=this.getLayerIndex(layer)+delta;this.setLayerIndex(layer,idx);},setBaseLayer:function(newBaseLayer){var oldExtent=null;if(this.baseLayer){oldExtent=this.baseLayer.getExtent();}
if(newBaseLayer!=this.baseLayer){if(OpenLayers.Util.indexOf(this.layers,newBaseLayer)!=-1){if(this.baseLayer!=null&&!this.allOverlays){this.baseLayer.setVisibility(false);}
this.baseLayer=newBaseLayer;this.viewRequestID++;if(!this.allOverlays){this.baseLayer.visibility=true;}
var center=this.getCenter();if(center!=null){var newCenter=(oldExtent)?oldExtent.getCenterLonLat():center;var newZoom=(oldExtent)?this.getZoomForExtent(oldExtent,true):this.getZoomForResolution(this.resolution,true);this.setCenter(newCenter,newZoom,false,true);}
this.events.triggerEvent("changebaselayer",{layer:this.baseLayer});}}},addControl:function(control,px){this.controls.push(control);this.addControlToMap(control,px);},addControlToMap:function(control,px){control.outsideViewport=(control.div!=null);if(this.displayProjection&&!control.displayProjection){control.displayProjection=this.displayProjection;}
control.setMap(this);var div=control.draw(px);if(div){if(!control.outsideViewport){div.style.zIndex=this.Z_INDEX_BASE['Control']+
this.controls.length;this.viewPortDiv.appendChild(div);}}},getControl:function(id){var returnControl=null;for(var i=0,len=this.controls.length;i<len;i++){var control=this.controls[i];if(control.id==id){returnControl=control;break;}}
return returnControl;},removeControl:function(control){if((control)&&(control==this.getControl(control.id))){if(control.div&&(control.div.parentNode==this.viewPortDiv)){this.viewPortDiv.removeChild(control.div);}
OpenLayers.Util.removeItem(this.controls,control);}},addPopup:function(popup,exclusive){if(exclusive){for(var i=this.popups.length-1;i>=0;--i){this.removePopup(this.popups[i]);}}
popup.map=this;this.popups.push(popup);var popupDiv=popup.draw();if(popupDiv){popupDiv.style.zIndex=this.Z_INDEX_BASE['Popup']+
this.popups.length;this.layerContainerDiv.appendChild(popupDiv);}},removePopup:function(popup){OpenLayers.Util.removeItem(this.popups,popup);if(popup.div){try{this.layerContainerDiv.removeChild(popup.div);}
catch(e){}}
popup.map=null;},getSize:function(){var size=null;if(this.size!=null){size=this.size.clone();}
return size;},updateSize:function(){this.events.clearMouseCache();var newSize=this.getCurrentSize();var oldSize=this.getSize();if(oldSize==null){this.size=oldSize=newSize;}
if(!newSize.equals(oldSize)){this.size=newSize;for(var i=0,len=this.layers.length;i<len;i++){this.layers[i].onMapResize();}
if(this.baseLayer!=null){var center=new OpenLayers.Pixel(newSize.w/2,newSize.h/2);var centerLL=this.getLonLatFromViewPortPx(center);var zoom=this.getZoom();this.zoom=null;this.setCenter(this.getCenter(),zoom);}}},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;},calculateBounds:function(center,resolution){var extent=null;if(center==null){center=this.getCenter();}
if(resolution==null){resolution=this.getResolution();}
if((center!=null)&&(resolution!=null)){var size=this.getSize();var w_deg=size.w*resolution;var h_deg=size.h*resolution;extent=new OpenLayers.Bounds(center.lon-w_deg/2,center.lat-h_deg/2,center.lon+w_deg/2,center.lat+h_deg/2);}
return extent;},getCenter:function(){var center=null;if(this.center){center=this.center.clone();}
return center;},getZoom:function(){return this.zoom;},pan:function(dx,dy,options){options=OpenLayers.Util.applyDefaults(options,{animate:true,dragging:false});var centerPx=this.getViewPortPxFromLonLat(this.getCenter());var newCenterPx=centerPx.add(dx,dy);if(!options.dragging||!newCenterPx.equals(centerPx)){var newCenterLonLat=this.getLonLatFromViewPortPx(newCenterPx);if(options.animate){this.panTo(newCenterLonLat);}else{this.setCenter(newCenterLonLat,null,options.dragging);}}},panTo:function(lonlat){if(this.panMethod&&this.getExtent().scale(this.panRatio).containsLonLat(lonlat)){if(!this.panTween){this.panTween=new OpenLayers.Tween(this.panMethod);}
var center=this.getCenter();if(lonlat.lon==center.lon&&lonlat.lat==center.lat){return;}
var from={lon:center.lon,lat:center.lat};var to={lon:lonlat.lon,lat:lonlat.lat};this.panTween.start(from,to,this.panDuration,{callbacks:{start:OpenLayers.Function.bind(function(lonlat){this.events.triggerEvent("movestart");},this),eachStep:OpenLayers.Function.bind(function(lonlat){lonlat=new OpenLayers.LonLat(lonlat.lon,lonlat.lat);this.moveTo(lonlat,this.zoom,{'dragging':true,'noEvent':true});},this),done:OpenLayers.Function.bind(function(lonlat){lonlat=new OpenLayers.LonLat(lonlat.lon,lonlat.lat);this.moveTo(lonlat,this.zoom,{'noEvent':true});this.events.triggerEvent("moveend");},this)}});}else{this.setCenter(lonlat);}},setCenter:function(lonlat,zoom,dragging,forceZoomChange){this.moveTo(lonlat,zoom,{'dragging':dragging,'forceZoomChange':forceZoomChange,'caller':'setCenter'});},moveTo:function(lonlat,zoom,options){if(!options){options={};}
var dragging=options.dragging;var forceZoomChange=options.forceZoomChange;var noEvent=options.noEvent;if(this.panTween&&options.caller=="setCenter"){this.panTween.stop();}
if(!this.center&&!this.isValidLonLat(lonlat)){lonlat=this.maxExtent.getCenterLonLat();}
if(this.restrictedExtent!=null){if(lonlat==null){lonlat=this.getCenter();}
if(zoom==null){zoom=this.getZoom();}
var resolution=this.getResolutionForZoom(zoom);var extent=this.calculateBounds(lonlat,resolution);if(!this.restrictedExtent.containsBounds(extent)){var maxCenter=this.restrictedExtent.getCenterLonLat();if(extent.getWidth()>this.restrictedExtent.getWidth()){lonlat=new OpenLayers.LonLat(maxCenter.lon,lonlat.lat);}else if(extent.left<this.restrictedExtent.left){lonlat=lonlat.add(this.restrictedExtent.left-
extent.left,0);}else if(extent.right>this.restrictedExtent.right){lonlat=lonlat.add(this.restrictedExtent.right-
extent.right,0);}
if(extent.getHeight()>this.restrictedExtent.getHeight()){lonlat=new OpenLayers.LonLat(lonlat.lon,maxCenter.lat);}else if(extent.bottom<this.restrictedExtent.bottom){lonlat=lonlat.add(0,this.restrictedExtent.bottom-
extent.bottom);}
else if(extent.top>this.restrictedExtent.top){lonlat=lonlat.add(0,this.restrictedExtent.top-
extent.top);}}}
var zoomChanged=forceZoomChange||((this.isValidZoomLevel(zoom))&&(zoom!=this.getZoom()));var centerChanged=(this.isValidLonLat(lonlat))&&(!lonlat.equals(this.center));if(zoomChanged||centerChanged||!dragging){if(!this.dragging&&!noEvent){this.events.triggerEvent("movestart");}
if(centerChanged){if((!zoomChanged)&&(this.center)){this.centerLayerContainer(lonlat);}
this.center=lonlat.clone();}
if((zoomChanged)||(this.layerContainerOrigin==null)){this.layerContainerOrigin=this.center.clone();this.layerContainerDiv.style.left="0px";this.layerContainerDiv.style.top="0px";}
if(zoomChanged){this.zoom=zoom;this.resolution=this.getResolutionForZoom(zoom);this.viewRequestID++;}
var bounds=this.getExtent();if(this.baseLayer.visibility){this.baseLayer.moveTo(bounds,zoomChanged,dragging);if(dragging){this.baseLayer.events.triggerEvent("move");}else{this.baseLayer.events.triggerEvent("moveend",{"zoomChanged":zoomChanged});}}
bounds=this.baseLayer.getExtent();for(var i=0,len=this.layers.length;i<len;i++){var layer=this.layers[i];if(layer!==this.baseLayer&&!layer.isBaseLayer){var inRange=layer.calculateInRange();if(layer.inRange!=inRange){layer.inRange=inRange;if(!inRange){layer.display(false);}
this.events.triggerEvent("changelayer",{layer:layer,property:"visibility"});}
if(inRange&&layer.visibility){layer.moveTo(bounds,zoomChanged,dragging);if(dragging){layer.events.triggerEvent("move");}else{layer.events.triggerEvent("moveend",{"zoomChanged":zoomChanged});}}}}
if(zoomChanged){for(var i=0,len=this.popups.length;i<len;i++){this.popups[i].updatePosition();}}
this.events.triggerEvent("move");if(zoomChanged){this.events.triggerEvent("zoomend");}}
if(!dragging&&!noEvent){this.events.triggerEvent("moveend");}
this.dragging=!!dragging;},centerLayerContainer:function(lonlat){var originPx=this.getViewPortPxFromLonLat(this.layerContainerOrigin);var newPx=this.getViewPortPxFromLonLat(lonlat);if((originPx!=null)&&(newPx!=null)){this.layerContainerDiv.style.left=Math.round(originPx.x-newPx.x)+"px";this.layerContainerDiv.style.top=Math.round(originPx.y-newPx.y)+"px";}},isValidZoomLevel:function(zoomLevel){return((zoomLevel!=null)&&(zoomLevel>=0)&&(zoomLevel<this.getNumZoomLevels()));},isValidLonLat:function(lonlat){var valid=false;if(lonlat!=null){var maxExtent=this.getMaxExtent();valid=maxExtent.containsLonLat(lonlat);}
return valid;},getProjection:function(){var projection=this.getProjectionObject();return projection?projection.getCode():null;},getProjectionObject:function(){var projection=null;if(this.baseLayer!=null){projection=this.baseLayer.projection;}
return projection;},getMaxResolution:function(){var maxResolution=null;if(this.baseLayer!=null){maxResolution=this.baseLayer.maxResolution;}
return maxResolution;},getMaxExtent:function(options){var maxExtent=null;if(options&&options.restricted&&this.restrictedExtent){maxExtent=this.restrictedExtent;}else if(this.baseLayer!=null){maxExtent=this.baseLayer.maxExtent;}
return maxExtent;},getNumZoomLevels:function(){var numZoomLevels=null;if(this.baseLayer!=null){numZoomLevels=this.baseLayer.numZoomLevels;}
return numZoomLevels;},getExtent:function(){var extent=null;if(this.baseLayer!=null){extent=this.baseLayer.getExtent();}
return extent;},getResolution:function(){var resolution=null;if(this.baseLayer!=null){resolution=this.baseLayer.getResolution();}
return resolution;},getUnits:function(){var units=null;if(this.baseLayer!=null){units=this.baseLayer.units;}
return units;},getScale:function(){var scale=null;if(this.baseLayer!=null){var res=this.getResolution();var units=this.baseLayer.units;scale=OpenLayers.Util.getScaleFromResolution(res,units);}
return scale;},getZoomForExtent:function(bounds,closest){var zoom=null;if(this.baseLayer!=null){zoom=this.baseLayer.getZoomForExtent(bounds,closest);}
return zoom;},getResolutionForZoom:function(zoom){var resolution=null;if(this.baseLayer){resolution=this.baseLayer.getResolutionForZoom(zoom);}
return resolution;},getZoomForResolution:function(resolution,closest){var zoom=null;if(this.baseLayer!=null){zoom=this.baseLayer.getZoomForResolution(resolution,closest);}
return zoom;},zoomTo:function(zoom){if(this.isValidZoomLevel(zoom)){this.setCenter(null,zoom);}},zoomIn:function(){this.zoomTo(this.getZoom()+1);},zoomOut:function(){this.zoomTo(this.getZoom()-1);},zoomToExtent:function(bounds,closest){var center=bounds.getCenterLonLat();if(this.baseLayer.wrapDateLine){var maxExtent=this.getMaxExtent();bounds=bounds.clone();while(bounds.right<bounds.left){bounds.right+=maxExtent.getWidth();}
center=bounds.getCenterLonLat().wrapDateLine(maxExtent);}
this.setCenter(center,this.getZoomForExtent(bounds,closest));},zoomToMaxExtent:function(options){var restricted=(options)?options.restricted:true;var maxExtent=this.getMaxExtent({'restricted':restricted});this.zoomToExtent(maxExtent);},zoomToScale:function(scale,closest){var res=OpenLayers.Util.getResolutionFromScale(scale,this.baseLayer.units);var size=this.getSize();var w_deg=size.w*res;var h_deg=size.h*res;var center=this.getCenter();var extent=new OpenLayers.Bounds(center.lon-w_deg/2,center.lat-h_deg/2,center.lon+w_deg/2,center.lat+h_deg/2);this.zoomToExtent(extent,closest);},getLonLatFromViewPortPx:function(viewPortPx){var lonlat=null;if(this.baseLayer!=null){lonlat=this.baseLayer.getLonLatFromViewPortPx(viewPortPx);}
return lonlat;},getViewPortPxFromLonLat:function(lonlat){var px=null;if(this.baseLayer!=null){px=this.baseLayer.getViewPortPxFromLonLat(lonlat);}
return px;},getLonLatFromPixel:function(px){return this.getLonLatFromViewPortPx(px);},getPixelFromLonLat:function(lonlat){var px=this.getViewPortPxFromLonLat(lonlat);px.x=Math.round(px.x);px.y=Math.round(px.y);return px;},getViewPortPxFromLayerPx:function(layerPx){var viewPortPx=null;if(layerPx!=null){var dX=parseInt(this.layerContainerDiv.style.left);var dY=parseInt(this.layerContainerDiv.style.top);viewPortPx=layerPx.add(dX,dY);}
return viewPortPx;},getLayerPxFromViewPortPx:function(viewPortPx){var layerPx=null;if(viewPortPx!=null){var dX=-parseInt(this.layerContainerDiv.style.left);var dY=-parseInt(this.layerContainerDiv.style.top);layerPx=viewPortPx.add(dX,dY);if(isNaN(layerPx.x)||isNaN(layerPx.y)){layerPx=null;}}
return layerPx;},getLonLatFromLayerPx:function(px){px=this.getViewPortPxFromLayerPx(px);return this.getLonLatFromViewPortPx(px);},getLayerPxFromLonLat:function(lonlat){var px=this.getPixelFromLonLat(lonlat);return this.getLayerPxFromViewPortPx(px);},CLASS_NAME:"OpenLayers.Map"});OpenLayers.Map.TILE_WIDTH=256;OpenLayers.Map.TILE_HEIGHT=256;OpenLayers.Layer=OpenLayers.Class({id:null,name:null,div:null,opacity:null,alwaysInRange:null,EVENT_TYPES:["loadstart","loadend","loadcancel","visibilitychanged","move","moveend"],events:null,map:null,isBaseLayer:false,alpha:false,displayInLayerSwitcher:true,visibility:true,attribution:null,inRange:false,imageSize:null,imageOffset:null,options:null,eventListeners:null,gutter:0,projection:null,units:null,scales:null,resolutions:null,maxExtent:null,minExtent:null,maxResolution:null,minResolution:null,numZoomLevels:null,minScale:null,maxScale:null,displayOutsideMaxExtent:false,wrapDateLine:false,transitionEffect:null,SUPPORTED_TRANSITIONS:['resize'],initialize:function(name,options){this.addOptions(options);this.name=name;if(this.id==null){this.id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_");this.div=OpenLayers.Util.createDiv(this.id);this.div.style.width="100%";this.div.style.height="100%";this.div.dir="ltr";this.events=new OpenLayers.Events(this,this.div,this.EVENT_TYPES);if(this.eventListeners instanceof Object){this.events.on(this.eventListeners);}}
if(this.wrapDateLine){this.displayOutsideMaxExtent=true;}},destroy:function(setNewBaseLayer){if(setNewBaseLayer==null){setNewBaseLayer=true;}
if(this.map!=null){this.map.removeLayer(this,setNewBaseLayer);}
this.projection=null;this.map=null;this.name=null;this.div=null;this.options=null;if(this.events){if(this.eventListeners){this.events.un(this.eventListeners);}
this.events.destroy();}
this.eventListeners=null;this.events=null;},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer(this.name,this.options);}
OpenLayers.Util.applyDefaults(obj,this);obj.map=null;return obj;},setName:function(newName){if(newName!=this.name){this.name=newName;if(this.map!=null){this.map.events.triggerEvent("changelayer",{layer:this,property:"name"});}}},addOptions:function(newOptions){if(this.options==null){this.options={};}
OpenLayers.Util.extend(this.options,newOptions);OpenLayers.Util.extend(this,newOptions);},onMapResize:function(){},redraw:function(){var redrawn=false;if(this.map){this.inRange=this.calculateInRange();var extent=this.getExtent();if(extent&&this.inRange&&this.visibility){var zoomChanged=true;this.moveTo(extent,zoomChanged,false);this.events.triggerEvent("moveend",{"zoomChanged":zoomChanged});redrawn=true;}}
return redrawn;},moveTo:function(bounds,zoomChanged,dragging){var display=this.visibility;if(!this.isBaseLayer){display=display&&this.inRange;}
this.display(display);},setMap:function(map){if(this.map==null){this.map=map;this.maxExtent=this.maxExtent||this.map.maxExtent;this.projection=this.projection||this.map.projection;if(this.projection&&typeof this.projection=="string"){this.projection=new OpenLayers.Projection(this.projection);}
this.units=this.projection.getUnits()||this.units||this.map.units;this.initResolutions();if(!this.isBaseLayer){this.inRange=this.calculateInRange();var show=((this.visibility)&&(this.inRange));this.div.style.display=show?"":"none";}
this.setTileSize();}},afterAdd:function(){},removeMap:function(map){},getImageSize:function(){return(this.imageSize||this.tileSize);},setTileSize:function(size){var tileSize=(size)?size:((this.tileSize)?this.tileSize:this.map.getTileSize());this.tileSize=tileSize;if(this.gutter){this.imageOffset=new OpenLayers.Pixel(-this.gutter,-this.gutter);this.imageSize=new OpenLayers.Size(tileSize.w+(2*this.gutter),tileSize.h+(2*this.gutter));}},getVisibility:function(){return this.visibility;},setVisibility:function(visibility){if(visibility!=this.visibility){this.visibility=visibility;this.display(visibility);this.redraw();if(this.map!=null){this.map.events.triggerEvent("changelayer",{layer:this,property:"visibility"});}
this.events.triggerEvent("visibilitychanged");}},display:function(display){var inRange=this.calculateInRange();if(display!=(this.div.style.display!="none")){this.div.style.display=(display&&inRange)?"block":"none";}},calculateInRange:function(){var inRange=false;if(this.alwaysInRange){inRange=true;}else{if(this.map){var resolution=this.map.getResolution();inRange=((resolution>=this.minResolution)&&(resolution<=this.maxResolution));}}
return inRange;},setIsBaseLayer:function(isBaseLayer){if(isBaseLayer!=this.isBaseLayer){this.isBaseLayer=isBaseLayer;if(this.map!=null){this.map.events.triggerEvent("changebaselayer",{layer:this});}}},initResolutions:function(){var props=new Array('projection','units','scales','resolutions','maxScale','minScale','maxResolution','minResolution','minExtent','maxExtent','numZoomLevels','maxZoomLevel');var notScaleProps=['projection','units'];var useInRange=false;var confProps={};for(var i=0,len=props.length;i<len;i++){var property=props[i];if(this.options[property]&&OpenLayers.Util.indexOf(notScaleProps,property)==-1){useInRange=true;}
confProps[property]=this.options[property]||this.map[property];}
if(this.alwaysInRange==null){this.alwaysInRange=!useInRange;}
if((this.options.minScale!=null||this.options.maxScale!=null)&&this.options.scales==null){confProps.scales=null;}
if((this.options.minResolution!=null||this.options.maxResolution!=null)&&this.options.resolutions==null){confProps.resolutions=null;}
if((!confProps.numZoomLevels)&&(confProps.maxZoomLevel)){confProps.numZoomLevels=confProps.maxZoomLevel+1;}
if((confProps.scales!=null)||(confProps.resolutions!=null)){if(confProps.scales!=null){confProps.resolutions=[];for(var i=0,len=confProps.scales.length;i<len;i++){var scale=confProps.scales[i];confProps.resolutions[i]=OpenLayers.Util.getResolutionFromScale(scale,confProps.units);}}
confProps.numZoomLevels=confProps.resolutions.length;}else{if(confProps.minScale){confProps.maxResolution=OpenLayers.Util.getResolutionFromScale(confProps.minScale,confProps.units);}else if(confProps.maxResolution=="auto"){var viewSize=this.map.getSize();var wRes=confProps.maxExtent.getWidth()/viewSize.w;var hRes=confProps.maxExtent.getHeight()/viewSize.h;confProps.maxResolution=Math.max(wRes,hRes);}
if(confProps.maxScale!=null){confProps.minResolution=OpenLayers.Util.getResolutionFromScale(confProps.maxScale,confProps.units);}else if((confProps.minResolution=="auto")&&(confProps.minExtent!=null)){var viewSize=this.map.getSize();var wRes=confProps.minExtent.getWidth()/viewSize.w;var hRes=confProps.minExtent.getHeight()/viewSize.h;confProps.minResolution=Math.max(wRes,hRes);}
if(confProps.minResolution!=null&&this.options.numZoomLevels==undefined){var ratio=confProps.maxResolution/confProps.minResolution;confProps.numZoomLevels=Math.floor(Math.log(ratio)/Math.log(2))+1;}
confProps.resolutions=new Array(confProps.numZoomLevels);var base=2;if(typeof confProps.minResolution=="number"&&confProps.numZoomLevels>1){base=Math.pow((confProps.maxResolution/confProps.minResolution),(1/(confProps.numZoomLevels-1)));}
for(var i=0;i<confProps.numZoomLevels;i++){var res=confProps.maxResolution/Math.pow(base,i);confProps.resolutions[i]=res;}}
confProps.resolutions.sort(function(a,b){return(b-a);});this.resolutions=confProps.resolutions;this.maxResolution=confProps.resolutions[0];var lastIndex=confProps.resolutions.length-1;this.minResolution=confProps.resolutions[lastIndex];this.scales=[];for(var i=0,len=confProps.resolutions.length;i<len;i++){this.scales[i]=OpenLayers.Util.getScaleFromResolution(confProps.resolutions[i],confProps.units);}
this.minScale=this.scales[0];this.maxScale=this.scales[this.scales.length-1];this.numZoomLevels=confProps.numZoomLevels;},getResolution:function(){var zoom=this.map.getZoom();return this.getResolutionForZoom(zoom);},getExtent:function(){return this.map.calculateBounds();},getZoomForExtent:function(extent,closest){var viewSize=this.map.getSize();var idealResolution=Math.max(extent.getWidth()/viewSize.w,extent.getHeight()/viewSize.h);return this.getZoomForResolution(idealResolution,closest);},getDataExtent:function(){},getResolutionForZoom:function(zoom){zoom=Math.max(0,Math.min(zoom,this.resolutions.length-1));var resolution;if(this.map.fractionalZoom){var low=Math.floor(zoom);var high=Math.ceil(zoom);resolution=this.resolutions[low]-
((zoom-low)*(this.resolutions[low]-this.resolutions[high]));}else{resolution=this.resolutions[Math.round(zoom)];}
return resolution;},getZoomForResolution:function(resolution,closest){var zoom;if(this.map.fractionalZoom){var lowZoom=0;var highZoom=this.resolutions.length-1;var highRes=this.resolutions[lowZoom];var lowRes=this.resolutions[highZoom];var res;for(var i=0,len=this.resolutions.length;i<len;++i){res=this.resolutions[i];if(res>=resolution){highRes=res;lowZoom=i;}
if(res<=resolution){lowRes=res;highZoom=i;break;}}
var dRes=highRes-lowRes;if(dRes>0){zoom=lowZoom+((highRes-resolution)/dRes);}else{zoom=lowZoom;}}else{var diff;var minDiff=Number.POSITIVE_INFINITY;for(var i=0,len=this.resolutions.length;i<len;i++){if(closest){diff=Math.abs(this.resolutions[i]-resolution);if(diff>minDiff){break;}
minDiff=diff;}else{if(this.resolutions[i]<resolution){break;}}}
zoom=Math.max(0,i-1);}
return zoom;},getLonLatFromViewPortPx:function(viewPortPx){var lonlat=null;if(viewPortPx!=null){var size=this.map.getSize();var center=this.map.getCenter();if(center){var res=this.map.getResolution();var delta_x=viewPortPx.x-(size.w/2);var delta_y=viewPortPx.y-(size.h/2);lonlat=new OpenLayers.LonLat(center.lon+delta_x*res,center.lat-delta_y*res);if(this.wrapDateLine){lonlat=lonlat.wrapDateLine(this.maxExtent);}}}
return lonlat;},getViewPortPxFromLonLat:function(lonlat){var px=null;if(lonlat!=null){var resolution=this.map.getResolution();var extent=this.map.getExtent();px=new OpenLayers.Pixel((1/resolution*(lonlat.lon-extent.left)),(1/resolution*(extent.top-lonlat.lat)));}
return px;},setOpacity:function(opacity){if(opacity!=this.opacity){this.opacity=opacity;for(var i=0,len=this.div.childNodes.length;i<len;++i){var element=this.div.childNodes[i].firstChild;OpenLayers.Util.modifyDOMElement(element,null,null,null,null,null,null,opacity);}}},getZIndex:function(){return this.div.style.zIndex;},setZIndex:function(zIndex){this.div.style.zIndex=zIndex;},adjustBounds:function(bounds){if(this.gutter){var mapGutter=this.gutter*this.map.getResolution();bounds=new OpenLayers.Bounds(bounds.left-mapGutter,bounds.bottom-mapGutter,bounds.right+mapGutter,bounds.top+mapGutter);}
if(this.wrapDateLine){var wrappingOptions={'rightTolerance':this.getResolution()};bounds=bounds.wrapDateLine(this.maxExtent,wrappingOptions);}
return bounds;},CLASS_NAME:"OpenLayers.Layer"});OpenLayers.Popup=OpenLayers.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,disableFirefoxOverflowHack:false,fixPadding:function(){if(typeof this.padding=="number"){this.padding=new OpenLayers.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=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_");}
this.id=id;this.lonlat=lonlat;this.contentSize=(contentSize!=null)?contentSize:new OpenLayers.Size(OpenLayers.Popup.WIDTH,OpenLayers.Popup.HEIGHT);if(contentHTML!=null){this.contentHTML=contentHTML;}
this.backgroundColor=OpenLayers.Popup.COLOR;this.opacity=OpenLayers.Popup.OPACITY;this.border=OpenLayers.Popup.BORDER;this.div=OpenLayers.Util.createDiv(this.id,null,null,null,null,null,"hidden");this.div.className=this.displayClass;var groupDivId=this.id+"_GroupDiv";this.groupDiv=OpenLayers.Util.createDiv(groupDivId,null,null,null,"relative",null,"hidden");var id=this.div.id+"_contentDiv";this.contentDiv=OpenLayers.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(){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);}
this.events.destroy();this.events=null;if(this.closeDiv){OpenLayers.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;},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(!this.disableFirefoxOverflowHack&&OpenLayers.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 OpenLayers.Element.visible(this.div);},toggle:function(){if(this.visible()){this.hide();}else{this.show();}},show:function(){OpenLayers.Element.show(this.div);if(this.panMapIfOutOfView){this.panIntoView();}},hide:function(){OpenLayers.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(OpenLayers.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=OpenLayers.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 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(preparedHTML,fixedSize,{displayClass:this.contentDisplayClass,containerElement:containerElement});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);},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();}
OpenLayers.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=OpenLayers.Function.bind(onImgLoad,context);OpenLayers.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 OpenLayers.Bounds(OpenLayers.Element.getStyle(this.contentDiv,"padding-left"),OpenLayers.Element.getStyle(this.contentDiv,"padding-bottom"),OpenLayers.Element.getStyle(this.contentDiv,"padding-right"),OpenLayers.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=OpenLayers.Util.createDiv(this.id+"_close",null,new OpenLayers.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();OpenLayers.Event.stop(e);};OpenLayers.Event.observe(this.closeDiv,"click",OpenLayers.Function.bindAsEventListener(closePopup,this));},panIntoView:function(){var mapSize=this.map.getSize();var origTL=this.map.getViewPortPxFromLayerPx(new OpenLayers.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 OpenLayers.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;OpenLayers.Event.stop(evt,true);},onmousemove:function(evt){if(this.mousedown){OpenLayers.Event.stop(evt,true);}},onmouseup:function(evt){if(this.mousedown){this.mousedown=false;OpenLayers.Event.stop(evt,true);}},onclick:function(evt){OpenLayers.Event.stop(evt,true);},onmouseout:function(evt){this.mousedown=false;},ondblclick:function(evt){OpenLayers.Event.stop(evt,true);},CLASS_NAME:"OpenLayers.Popup"});OpenLayers.Popup.WIDTH=200;OpenLayers.Popup.HEIGHT=200;OpenLayers.Popup.COLOR="white";OpenLayers.Popup.OPACITY=1;OpenLayers.Popup.BORDER="0px";OpenLayers.Tile=OpenLayers.Class({EVENT_TYPES:["loadstart","loadend","reload","unload"],events:null,id:null,layer:null,url:null,bounds:null,size:null,position:null,isLoading:false,initialize:function(layer,position,bounds,url,size){this.layer=layer;this.position=position.clone();this.bounds=bounds.clone();this.url=url;this.size=size.clone();this.id=OpenLayers.Util.createUniqueID("Tile_");this.events=new OpenLayers.Events(this,null,this.EVENT_TYPES);},unload:function(){if(this.isLoading){this.isLoading=false;this.events.triggerEvent("unload");}},destroy:function(){this.layer=null;this.bounds=null;this.size=null;this.position=null;this.events.destroy();this.events=null;},clone:function(obj){if(obj==null){obj=new OpenLayers.Tile(this.layer,this.position,this.bounds,this.url,this.size);}
OpenLayers.Util.applyDefaults(obj,this);return obj;},draw:function(){var maxExtent=this.layer.maxExtent;var withinMaxExtent=(maxExtent&&this.bounds.intersectsBounds(maxExtent,false));this.shouldDraw=(withinMaxExtent||this.layer.displayOutsideMaxExtent);this.clear();return this.shouldDraw;},moveTo:function(bounds,position,redraw){if(redraw==null){redraw=true;}
this.bounds=bounds.clone();this.position=position.clone();if(redraw){this.draw();}},clear:function(){},getBoundsFromBaseLayer:function(position){var msg=OpenLayers.i18n('reprojectDeprecated',{'layerName':this.layer.name});OpenLayers.Console.warn(msg);var topLeft=this.layer.map.getLonLatFromLayerPx(position);var bottomRightPx=position.clone();bottomRightPx.x+=this.size.w;bottomRightPx.y+=this.size.h;var bottomRight=this.layer.map.getLonLatFromLayerPx(bottomRightPx);if(topLeft.lon>bottomRight.lon){if(topLeft.lon<0){topLeft.lon=-180-(topLeft.lon+180);}else{bottomRight.lon=180+bottomRight.lon+180;}}
var bounds=new OpenLayers.Bounds(topLeft.lon,bottomRight.lat,bottomRight.lon,topLeft.lat);return bounds;},showTile:function(){if(this.shouldDraw){this.show();}},show:function(){},hide:function(){},CLASS_NAME:"OpenLayers.Tile"});OpenLayers.Tile.Image=OpenLayers.Class(OpenLayers.Tile,{url:null,imgDiv:null,frame:null,layerAlphaHack:null,isBackBuffer:false,lastRatio:1,isFirstDraw:true,backBufferTile:null,initialize:function(layer,position,bounds,url,size){OpenLayers.Tile.prototype.initialize.apply(this,arguments);this.url=url;this.frame=document.createElement('div');this.frame.style.overflow='hidden';this.frame.style.position='absolute';this.layerAlphaHack=this.layer.alpha&&OpenLayers.Util.alphaHack();},destroy:function(){if(this.imgDiv!=null){if(this.layerAlphaHack){OpenLayers.Event.stopObservingElement(this.imgDiv.childNodes[0].id);}
OpenLayers.Event.stopObservingElement(this.imgDiv.id);if(this.imgDiv.parentNode==this.frame){this.frame.removeChild(this.imgDiv);this.imgDiv.map=null;}
this.imgDiv.urls=null;this.imgDiv.src=OpenLayers.Util.getImagesLocation()+"blank.gif";}
this.imgDiv=null;if((this.frame!=null)&&(this.frame.parentNode==this.layer.div)){this.layer.div.removeChild(this.frame);}
this.frame=null;if(this.backBufferTile){this.backBufferTile.destroy();this.backBufferTile=null;}
this.layer.events.unregister("loadend",this,this.resetBackBuffer);OpenLayers.Tile.prototype.destroy.apply(this,arguments);},clone:function(obj){if(obj==null){obj=new OpenLayers.Tile.Image(this.layer,this.position,this.bounds,this.url,this.size);}
obj=OpenLayers.Tile.prototype.clone.apply(this,[obj]);obj.imgDiv=null;return obj;},draw:function(){if(this.layer!=this.layer.map.baseLayer&&this.layer.reproject){this.bounds=this.getBoundsFromBaseLayer(this.position);}
var drawTile=OpenLayers.Tile.prototype.draw.apply(this,arguments);if(OpenLayers.Util.indexOf(this.layer.SUPPORTED_TRANSITIONS,this.layer.transitionEffect)!=-1){if(drawTile){if(!this.backBufferTile){this.backBufferTile=this.clone();this.backBufferTile.hide();this.backBufferTile.isBackBuffer=true;this.events.register('loadend',this,this.resetBackBuffer);this.layer.events.register("loadend",this,this.resetBackBuffer);}
this.startTransition();}else{if(this.backBufferTile){this.backBufferTile.clear();}}}else{if(drawTile&&this.isFirstDraw){this.events.register('loadend',this,this.showTile);this.isFirstDraw=false;}}
if(!drawTile){return false;}
if(this.isLoading){this.events.triggerEvent("reload");}else{this.isLoading=true;this.events.triggerEvent("loadstart");}
return this.renderTile();},resetBackBuffer:function(){this.showTile();if(this.backBufferTile&&(this.isFirstDraw||!this.layer.numLoadingTiles)){this.isFirstDraw=false;var maxExtent=this.layer.maxExtent;var withinMaxExtent=(maxExtent&&this.bounds.intersectsBounds(maxExtent,false));if(withinMaxExtent){this.backBufferTile.position=this.position;this.backBufferTile.bounds=this.bounds;this.backBufferTile.size=this.size;this.backBufferTile.imageSize=this.layer.imageSize||this.size;this.backBufferTile.imageOffset=this.layer.imageOffset;this.backBufferTile.resolution=this.layer.getResolution();this.backBufferTile.renderTile();}
this.backBufferTile.hide();}},renderTile:function(){if(this.imgDiv==null){this.initImgDiv();}
this.imgDiv.viewRequestID=this.layer.map.viewRequestID;if(this.layer.async){this.layer.getURLasync(this.bounds,this,"url",this.positionImage);}else{if(this.layer.url instanceof Array){this.imgDiv.urls=this.layer.url.slice();}
this.url=this.layer.getURL(this.bounds);this.positionImage();}
return true;},positionImage:function(){if(this.layer==null)
return;OpenLayers.Util.modifyDOMElement(this.frame,null,this.position,this.size);var imageSize=this.layer.getImageSize();if(this.layerAlphaHack){OpenLayers.Util.modifyAlphaImageDiv(this.imgDiv,null,null,imageSize,this.url);}else{OpenLayers.Util.modifyDOMElement(this.imgDiv,null,null,imageSize);this.imgDiv.src=this.url;}},clear:function(){if(this.imgDiv){this.hide();if(OpenLayers.Tile.Image.useBlankTile){this.imgDiv.src=OpenLayers.Util.getImagesLocation()+"blank.gif";}}},initImgDiv:function(){var offset=this.layer.imageOffset;var size=this.layer.getImageSize();if(this.layerAlphaHack){this.imgDiv=OpenLayers.Util.createAlphaImageDiv(null,offset,size,null,"relative",null,null,null,true);}else{this.imgDiv=OpenLayers.Util.createImage(null,offset,size,null,"relative",null,null,true);}
this.imgDiv.className='olTileImage';this.frame.style.zIndex=this.isBackBuffer?0:1;this.frame.appendChild(this.imgDiv);this.layer.div.appendChild(this.frame);if(this.layer.opacity!=null){OpenLayers.Util.modifyDOMElement(this.imgDiv,null,null,null,null,null,null,this.layer.opacity);}
this.imgDiv.map=this.layer.map;var onload=function(){if(this.isLoading){this.isLoading=false;this.events.triggerEvent("loadend");}};if(this.layerAlphaHack){OpenLayers.Event.observe(this.imgDiv.childNodes[0],'load',OpenLayers.Function.bind(onload,this));}else{OpenLayers.Event.observe(this.imgDiv,'load',OpenLayers.Function.bind(onload,this));}
var onerror=function(){if(this.imgDiv._attempts>OpenLayers.IMAGE_RELOAD_ATTEMPTS){onload.call(this);}};OpenLayers.Event.observe(this.imgDiv,"error",OpenLayers.Function.bind(onerror,this));},checkImgURL:function(){if(this.layer){var loaded=this.layerAlphaHack?this.imgDiv.firstChild.src:this.imgDiv.src;if(!OpenLayers.Util.isEquivalentUrl(loaded,this.url)){this.hide();}}},startTransition:function(){if(!this.backBufferTile||!this.backBufferTile.imgDiv){return;}
var ratio=1;if(this.backBufferTile.resolution){ratio=this.backBufferTile.resolution/this.layer.getResolution();}
if(ratio!=this.lastRatio){if(this.layer.transitionEffect=='resize'){var upperLeft=new OpenLayers.LonLat(this.backBufferTile.bounds.left,this.backBufferTile.bounds.top);var size=new OpenLayers.Size(this.backBufferTile.size.w*ratio,this.backBufferTile.size.h*ratio);var px=this.layer.map.getLayerPxFromLonLat(upperLeft);OpenLayers.Util.modifyDOMElement(this.backBufferTile.frame,null,px,size);var imageSize=this.backBufferTile.imageSize;imageSize=new OpenLayers.Size(imageSize.w*ratio,imageSize.h*ratio);var imageOffset=this.backBufferTile.imageOffset;if(imageOffset){imageOffset=new OpenLayers.Pixel(imageOffset.x*ratio,imageOffset.y*ratio);}
OpenLayers.Util.modifyDOMElement(this.backBufferTile.imgDiv,null,imageOffset,imageSize);this.backBufferTile.show();}}else{if(this.layer.singleTile){this.backBufferTile.show();}else{this.backBufferTile.hide();}}
this.lastRatio=ratio;},show:function(){this.frame.style.display='';if(OpenLayers.Util.indexOf(this.layer.SUPPORTED_TRANSITIONS,this.layer.transitionEffect)!=-1){if(navigator.userAgent.toLowerCase().indexOf("gecko")!=-1){this.frame.scrollLeft=this.frame.scrollLeft;}}},hide:function(){this.frame.style.display='none';},CLASS_NAME:"OpenLayers.Tile.Image"});OpenLayers.Tile.Image.useBlankTile=(OpenLayers.Util.getBrowserName()=="safari"||OpenLayers.Util.getBrowserName()=="opera");OpenLayers.Layer.SphericalMercator={getExtent:function(){var extent=null;if(this.sphericalMercator){extent=this.map.calculateBounds();}else{extent=OpenLayers.Layer.FixedZoomLevels.prototype.getExtent.apply(this);}
return extent;},initMercatorParameters:function(){this.RESOLUTIONS=[];var maxResolution=156543.0339;for(var zoom=0;zoom<=this.MAX_ZOOM_LEVEL;++zoom){this.RESOLUTIONS[zoom]=maxResolution/Math.pow(2,zoom);}
this.units="m";this.projection="EPSG:900913";},forwardMercator:function(lon,lat){var x=lon*20037508.34/180;var y=Math.log(Math.tan((90+lat)*Math.PI/360))/(Math.PI/180);y=y*20037508.34/180;return new OpenLayers.LonLat(x,y);},inverseMercator:function(x,y){var lon=(x/20037508.34)*180;var lat=(y/20037508.34)*180;lat=180/Math.PI*(2*Math.atan(Math.exp(lat*Math.PI/180))-Math.PI/2);return new OpenLayers.LonLat(lon,lat);},projectForward:function(point){var lonlat=OpenLayers.Layer.SphericalMercator.forwardMercator(point.x,point.y);point.x=lonlat.lon;point.y=lonlat.lat;return point;},projectInverse:function(point){var lonlat=OpenLayers.Layer.SphericalMercator.inverseMercator(point.x,point.y);point.x=lonlat.lon;point.y=lonlat.lat;return point;}};OpenLayers.Projection.addTransform("EPSG:4326","EPSG:900913",OpenLayers.Layer.SphericalMercator.projectForward);OpenLayers.Projection.addTransform("EPSG:900913","EPSG:4326",OpenLayers.Layer.SphericalMercator.projectInverse);OpenLayers.Layer.HTTPRequest=OpenLayers.Class(OpenLayers.Layer,{URL_HASH_FACTOR:(Math.sqrt(5)-1)/2,url:null,params:null,reproject:false,initialize:function(name,url,params,options){var newArguments=arguments;newArguments=[name,options];OpenLayers.Layer.prototype.initialize.apply(this,newArguments);this.url=url;this.params=OpenLayers.Util.extend({},params);},destroy:function(){this.url=null;this.params=null;OpenLayers.Layer.prototype.destroy.apply(this,arguments);},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.HTTPRequest(this.name,this.url,this.params,this.options);}
obj=OpenLayers.Layer.prototype.clone.apply(this,[obj]);return obj;},setUrl:function(newUrl){this.url=newUrl;},mergeNewParams:function(newParams){this.params=OpenLayers.Util.extend(this.params,newParams);return this.redraw();},redraw:function(force){if(force){return this.mergeNewParams({"_olSalt":Math.random()});}else{return OpenLayers.Layer.prototype.redraw.apply(this,[]);}},selectUrl:function(paramString,urls){var product=1;for(var i=0,len=paramString.length;i<len;i++){product*=paramString.charCodeAt(i)*this.URL_HASH_FACTOR;product-=Math.floor(product);}
return urls[Math.floor(product*urls.length)];},getFullRequestString:function(newParams,altUrl){var url=altUrl||this.url;var allParams=OpenLayers.Util.extend({},this.params);allParams=OpenLayers.Util.extend(allParams,newParams);var paramsString=OpenLayers.Util.getParameterString(allParams);if(url instanceof Array){url=this.selectUrl(paramsString,url);}
var urlParams=OpenLayers.Util.upperCaseObject(OpenLayers.Util.getParameters(url));for(var key in allParams){if(key.toUpperCase()in urlParams){delete allParams[key];}}
paramsString=OpenLayers.Util.getParameterString(allParams);var requestString=url;if(paramsString!=""){var lastServerChar=url.charAt(url.length-1);if((lastServerChar=="&")||(lastServerChar=="?")){requestString+=paramsString;}else{if(url.indexOf('?')==-1){requestString+='?'+paramsString;}else{requestString+='&'+paramsString;}}}
return requestString;},CLASS_NAME:"OpenLayers.Layer.HTTPRequest"});OpenLayers.Layer.Grid=OpenLayers.Class(OpenLayers.Layer.HTTPRequest,{tileSize:null,grid:null,singleTile:false,ratio:1.5,buffer:2,numLoadingTiles:0,initialize:function(name,url,params,options){OpenLayers.Layer.HTTPRequest.prototype.initialize.apply(this,arguments);this.events.addEventType("tileloaded");this.grid=[];},destroy:function(){this.clearGrid();this.grid=null;this.tileSize=null;OpenLayers.Layer.HTTPRequest.prototype.destroy.apply(this,arguments);},clearGrid:function(){if(this.grid){for(var iRow=0,len=this.grid.length;iRow<len;iRow++){var row=this.grid[iRow];for(var iCol=0,clen=row.length;iCol<clen;iCol++){var tile=row[iCol];this.removeTileMonitoringHooks(tile);tile.destroy();}}
this.grid=[];}},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.Grid(this.name,this.url,this.params,this.options);}
obj=OpenLayers.Layer.HTTPRequest.prototype.clone.apply(this,[obj]);if(this.tileSize!=null){obj.tileSize=this.tileSize.clone();}
obj.grid=[];return obj;},moveTo:function(bounds,zoomChanged,dragging){OpenLayers.Layer.HTTPRequest.prototype.moveTo.apply(this,arguments);bounds=bounds||this.map.getExtent();if(bounds!=null){var forceReTile=!this.grid.length||zoomChanged;var tilesBounds=this.getTilesBounds();if(this.singleTile){if(forceReTile||(!dragging&&!tilesBounds.containsBounds(bounds))){this.initSingleTile(bounds);}}else{if(forceReTile||!tilesBounds.containsBounds(bounds,true)){this.initGriddedTiles(bounds);}else{this.moveGriddedTiles(bounds);}}}},setTileSize:function(size){if(this.singleTile){size=this.map.getSize().clone();size.h=parseInt(size.h*this.ratio);size.w=parseInt(size.w*this.ratio);}
OpenLayers.Layer.HTTPRequest.prototype.setTileSize.apply(this,[size]);},getGridBounds:function(){var msg="The getGridBounds() function is deprecated. It will be "+"removed in 3.0. Please use getTilesBounds() instead.";OpenLayers.Console.warn(msg);return this.getTilesBounds();},getTilesBounds:function(){var bounds=null;if(this.grid.length){var bottom=this.grid.length-1;var bottomLeftTile=this.grid[bottom][0];var right=this.grid[0].length-1;var topRightTile=this.grid[0][right];bounds=new OpenLayers.Bounds(bottomLeftTile.bounds.left,bottomLeftTile.bounds.bottom,topRightTile.bounds.right,topRightTile.bounds.top);}
return bounds;},initSingleTile:function(bounds){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 ul=new OpenLayers.LonLat(tileBounds.left,tileBounds.top);var px=this.map.getLayerPxFromLonLat(ul);if(!this.grid.length){this.grid[0]=[];}
var tile=this.grid[0][0];if(!tile){tile=this.addTile(tileBounds,px);this.addTileMonitoringHooks(tile);tile.draw();this.grid[0][0]=tile;}else{tile.moveTo(tileBounds,px);}
this.removeExcessTiles(1,1);},calculateGridLayout:function(bounds,extent,resolution){var tilelon=resolution*this.tileSize.w;var tilelat=resolution*this.tileSize.h;var offsetlon=bounds.left-extent.left;var tilecol=Math.floor(offsetlon/tilelon)-this.buffer;var tilecolremain=offsetlon/tilelon-tilecol;var tileoffsetx=-tilecolremain*this.tileSize.w;var tileoffsetlon=extent.left+tilecol*tilelon;var offsetlat=bounds.top-(extent.bottom+tilelat);var tilerow=Math.ceil(offsetlat/tilelat)+this.buffer;var tilerowremain=tilerow-offsetlat/tilelat;var tileoffsety=-tilerowremain*this.tileSize.h;var tileoffsetlat=extent.bottom+tilerow*tilelat;return{tilelon:tilelon,tilelat:tilelat,tileoffsetlon:tileoffsetlon,tileoffsetlat:tileoffsetlat,tileoffsetx:tileoffsetx,tileoffsety:tileoffsety};},initGriddedTiles:function(bounds){var viewSize=this.map.getSize();var minRows=Math.ceil(viewSize.h/this.tileSize.h)+
Math.max(1,2*this.buffer);var minCols=Math.ceil(viewSize.w/this.tileSize.w)+
Math.max(1,2*this.buffer);var extent=this.maxExtent;var resolution=this.map.getResolution();var tileLayout=this.calculateGridLayout(bounds,extent,resolution);var tileoffsetx=Math.round(tileLayout.tileoffsetx);var tileoffsety=Math.round(tileLayout.tileoffsety);var tileoffsetlon=tileLayout.tileoffsetlon;var tileoffsetlat=tileLayout.tileoffsetlat;var tilelon=tileLayout.tilelon;var tilelat=tileLayout.tilelat;this.origin=new OpenLayers.Pixel(tileoffsetx,tileoffsety);var startX=tileoffsetx;var startLon=tileoffsetlon;var rowidx=0;var layerContainerDivLeft=parseInt(this.map.layerContainerDiv.style.left);var layerContainerDivTop=parseInt(this.map.layerContainerDiv.style.top);do{var row=this.grid[rowidx++];if(!row){row=[];this.grid.push(row);}
tileoffsetlon=startLon;tileoffsetx=startX;var colidx=0;do{var tileBounds=new OpenLayers.Bounds(tileoffsetlon,tileoffsetlat,tileoffsetlon+tilelon,tileoffsetlat+tilelat);var x=tileoffsetx;x-=layerContainerDivLeft;var y=tileoffsety;y-=layerContainerDivTop;var px=new OpenLayers.Pixel(x,y);var tile=row[colidx++];if(!tile){tile=this.addTile(tileBounds,px);this.addTileMonitoringHooks(tile);row.push(tile);}else{tile.moveTo(tileBounds,px,false);}
tileoffsetlon+=tilelon;tileoffsetx+=this.tileSize.w;}while((tileoffsetlon<=bounds.right+tilelon*this.buffer)||colidx<minCols);tileoffsetlat-=tilelat;tileoffsety+=this.tileSize.h;}while((tileoffsetlat>=bounds.bottom-tilelat*this.buffer)||rowidx<minRows);this.removeExcessTiles(rowidx,colidx);this.spiralTileLoad();},spiralTileLoad:function(){var tileQueue=[];var directions=["right","down","left","up"];var iRow=0;var iCell=-1;var direction=OpenLayers.Util.indexOf(directions,"right");var directionsTried=0;while(directionsTried<directions.length){var testRow=iRow;var testCell=iCell;switch(directions[direction]){case"right":testCell++;break;case"down":testRow++;break;case"left":testCell--;break;case"up":testRow--;break;}
var tile=null;if((testRow<this.grid.length)&&(testRow>=0)&&(testCell<this.grid[0].length)&&(testCell>=0)){tile=this.grid[testRow][testCell];}
if((tile!=null)&&(!tile.queued)){tileQueue.unshift(tile);tile.queued=true;directionsTried=0;iRow=testRow;iCell=testCell;}else{direction=(direction+1)%4;directionsTried++;}}
for(var i=0,len=tileQueue.length;i<len;i++){var tile=tileQueue[i];tile.draw();tile.queued=false;}},addTile:function(bounds,position){},addTileMonitoringHooks:function(tile){tile.onLoadStart=function(){if(this.numLoadingTiles==0){this.events.triggerEvent("loadstart");}
this.numLoadingTiles++;};tile.events.register("loadstart",this,tile.onLoadStart);tile.onLoadEnd=function(){this.numLoadingTiles--;this.events.triggerEvent("tileloaded");if(this.numLoadingTiles==0){this.events.triggerEvent("loadend");}};tile.events.register("loadend",this,tile.onLoadEnd);tile.events.register("unload",this,tile.onLoadEnd);},removeTileMonitoringHooks:function(tile){tile.unload();tile.events.un({"loadstart":tile.onLoadStart,"loadend":tile.onLoadEnd,"unload":tile.onLoadEnd,scope:this});},moveGriddedTiles:function(bounds){var buffer=this.buffer||1;while(true){var tlLayer=this.grid[0][0].position;var tlViewPort=this.map.getViewPortPxFromLayerPx(tlLayer);if(tlViewPort.x>-this.tileSize.w*(buffer-1)){this.shiftColumn(true);}else if(tlViewPort.x<-this.tileSize.w*buffer){this.shiftColumn(false);}else if(tlViewPort.y>-this.tileSize.h*(buffer-1)){this.shiftRow(true);}else if(tlViewPort.y<-this.tileSize.h*buffer){this.shiftRow(false);}else{break;}};},shiftRow:function(prepend){var modelRowIndex=(prepend)?0:(this.grid.length-1);var grid=this.grid;var modelRow=grid[modelRowIndex];var resolution=this.map.getResolution();var deltaY=(prepend)?-this.tileSize.h:this.tileSize.h;var deltaLat=resolution*-deltaY;var row=(prepend)?grid.pop():grid.shift();for(var i=0,len=modelRow.length;i<len;i++){var modelTile=modelRow[i];var bounds=modelTile.bounds.clone();var position=modelTile.position.clone();bounds.bottom=bounds.bottom+deltaLat;bounds.top=bounds.top+deltaLat;position.y=position.y+deltaY;row[i].moveTo(bounds,position);}
if(prepend){grid.unshift(row);}else{grid.push(row);}},shiftColumn:function(prepend){var deltaX=(prepend)?-this.tileSize.w:this.tileSize.w;var resolution=this.map.getResolution();var deltaLon=resolution*deltaX;for(var i=0,len=this.grid.length;i<len;i++){var row=this.grid[i];var modelTileIndex=(prepend)?0:(row.length-1);var modelTile=row[modelTileIndex];var bounds=modelTile.bounds.clone();var position=modelTile.position.clone();bounds.left=bounds.left+deltaLon;bounds.right=bounds.right+deltaLon;position.x=position.x+deltaX;var tile=prepend?this.grid[i].pop():this.grid[i].shift();tile.moveTo(bounds,position);if(prepend){row.unshift(tile);}else{row.push(tile);}}},removeExcessTiles:function(rows,columns){while(this.grid.length>rows){var row=this.grid.pop();for(var i=0,l=row.length;i<l;i++){var tile=row[i];this.removeTileMonitoringHooks(tile);tile.destroy();}}
while(this.grid[0].length>columns){for(var i=0,l=this.grid.length;i<l;i++){var row=this.grid[i];var tile=row.pop();this.removeTileMonitoringHooks(tile);tile.destroy();}}},onMapResize:function(){if(this.singleTile){this.clearGrid();this.setTileSize();}},getTileBounds:function(viewPortPx){var maxExtent=this.maxExtent;var resolution=this.getResolution();var tileMapWidth=resolution*this.tileSize.w;var tileMapHeight=resolution*this.tileSize.h;var mapPoint=this.getLonLatFromViewPortPx(viewPortPx);var tileLeft=maxExtent.left+(tileMapWidth*Math.floor((mapPoint.lon-
maxExtent.left)/tileMapWidth));var tileBottom=maxExtent.bottom+(tileMapHeight*Math.floor((mapPoint.lat-
maxExtent.bottom)/tileMapHeight));return new OpenLayers.Bounds(tileLeft,tileBottom,tileLeft+tileMapWidth,tileBottom+tileMapHeight);},CLASS_NAME:"OpenLayers.Layer.Grid"});OpenLayers.Layer.WMS=OpenLayers.Class(OpenLayers.Layer.Grid,{DEFAULT_PARAMS:{service:"WMS",version:"1.1.1",request:"GetMap",styles:"",exceptions:"application/vnd.ogc.se_inimage",format:"image/jpeg"},reproject:false,isBaseLayer:true,encodeBBOX:false,noMagic:false,initialize:function(name,url,params,options){var newArguments=[];params=OpenLayers.Util.upperCaseObject(params);newArguments.push(name,url,params,options);OpenLayers.Layer.Grid.prototype.initialize.apply(this,newArguments);OpenLayers.Util.applyDefaults(this.params,OpenLayers.Util.upperCaseObject(this.DEFAULT_PARAMS));if(!this.noMagic&&this.params.TRANSPARENT&&this.params.TRANSPARENT.toString().toLowerCase()=="true"){if((options==null)||(!options.isBaseLayer)){this.isBaseLayer=false;}
if(this.params.FORMAT=="image/jpeg"){this.params.FORMAT=OpenLayers.Util.alphaHack()?"image/gif":"image/png";}}},destroy:function(){OpenLayers.Layer.Grid.prototype.destroy.apply(this,arguments);},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.WMS(this.name,this.url,this.params,this.options);}
obj=OpenLayers.Layer.Grid.prototype.clone.apply(this,[obj]);return obj;},getURL:function(bounds){bounds=this.adjustBounds(bounds);var imageSize=this.getImageSize();var newParams={'BBOX':this.encodeBBOX?bounds.toBBOX():bounds.toArray(),'WIDTH':imageSize.w,'HEIGHT':imageSize.h};var requestString=this.getFullRequestString(newParams);return requestString;},addTile:function(bounds,position){return new OpenLayers.Tile.Image(this,position,bounds,null,this.tileSize);},mergeNewParams:function(newParams){var upperParams=OpenLayers.Util.upperCaseObject(newParams);var newArguments=[upperParams];return OpenLayers.Layer.Grid.prototype.mergeNewParams.apply(this,newArguments);},getFullRequestString:function(newParams,altUrl){var projectionCode=this.map.getProjection();this.params.SRS=(projectionCode=="none")?null:projectionCode;return OpenLayers.Layer.Grid.prototype.getFullRequestString.apply(this,arguments);},CLASS_NAME:"OpenLayers.Layer.WMS"});OpenLayers.Layer.WMS.Untiled=OpenLayers.Class(OpenLayers.Layer.WMS,{singleTile:true,initialize:function(name,url,params,options){OpenLayers.Layer.WMS.prototype.initialize.apply(this,arguments);var msg="The OpenLayers.Layer.WMS.Untiled class is deprecated and "+"will be removed in 3.0. Instead, you should use the "+"normal OpenLayers.Layer.WMS class, passing it the option "+"'singleTile' as true.";OpenLayers.Console.warn(msg);},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.WMS.Untiled(this.name,this.url,this.params,this.options);}
obj=OpenLayers.Layer.WMS.prototype.clone.apply(this,[obj]);return obj;},CLASS_NAME:"OpenLayers.Layer.WMS.Untiled"});OpenLayers.Layer.TileCache=OpenLayers.Class(OpenLayers.Layer.Grid,{isBaseLayer:true,format:'image/png',serverResolutions:null,initialize:function(name,url,layername,options){this.layername=layername;OpenLayers.Layer.Grid.prototype.initialize.apply(this,[name,url,{},options]);this.extension=this.format.split('/')[1].toLowerCase();this.extension=(this.extension=='jpg')?'jpeg':this.extension;},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.TileCache(this.name,this.url,this.layername,this.options);}
obj=OpenLayers.Layer.Grid.prototype.clone.apply(this,[obj]);return obj;},getURL:function(bounds){var res=this.map.getResolution();var bbox=this.maxExtent;var size=this.tileSize;var tileX=Math.round((bounds.left-bbox.left)/(res*size.w));var tileY=Math.round((bounds.bottom-bbox.bottom)/(res*size.h));var tileZ=this.serverResolutions!=null?OpenLayers.Util.indexOf(this.serverResolutions,res):this.map.getZoom();function zeroPad(number,length){number=String(number);var zeros=[];for(var i=0;i<length;++i){zeros.push('0');}
return zeros.join('').substring(0,length-number.length)+number;}
var components=[this.layername,zeroPad(tileZ,2),zeroPad(parseInt(tileX/1000000),3),zeroPad((parseInt(tileX/1000)%1000),3),zeroPad((parseInt(tileX)%1000),3),zeroPad(parseInt(tileY/1000000),3),zeroPad((parseInt(tileY/1000)%1000),3),zeroPad((parseInt(tileY)%1000),3)+'.'+this.extension];var path=components.join('/');var url=this.url;if(url instanceof Array){url=this.selectUrl(path,url);}
url=(url.charAt(url.length-1)=='/')?url:url+'/';return url+path;},addTile:function(bounds,position){var url=this.getURL(bounds);return new OpenLayers.Tile.Image(this,position,bounds,url,this.tileSize);},CLASS_NAME:"OpenLayers.Layer.TileCache"});OpenLayers.Popup.Anchored=OpenLayers.Class(OpenLayers.Popup,{relativePosition:null,keepInMap:true,anchor:null,initialize:function(id,lonlat,contentSize,contentHTML,anchor,closeBox,closeBoxCallback){var newArguments=[id,lonlat,contentSize,contentHTML,closeBox,closeBoxCallback];OpenLayers.Popup.prototype.initialize.apply(this,newArguments);this.anchor=(anchor!=null)?anchor:{size:new OpenLayers.Size(0,0),offset:new OpenLayers.Pixel(0,0)};},destroy:function(){this.anchor=null;this.relativePosition=null;OpenLayers.Popup.prototype.destroy.apply(this,arguments);},show:function(){this.updatePosition();OpenLayers.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);OpenLayers.Popup.prototype.moveTo.apply(this,newArguments);if(this.relativePosition!=oldRelativePosition){this.updateRelativePosition();}},setSize:function(contentSize){OpenLayers.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 OpenLayers.Bounds.oppositeQuadrant(quadrant);},updateRelativePosition:function(){},calculateNewPx:function(px){var newPx=px.offset(this.anchor.offset);var size=this.size||this.contentSize;var top=(this.relativePosition.charAt(0)=='t');newPx.y+=(top)?-size.h:this.anchor.size.h;var left=(this.relativePosition.charAt(1)=='l');newPx.x+=(left)?-size.w:this.anchor.size.w;return newPx;},CLASS_NAME:"OpenLayers.Popup.Anchored"});OpenLayers.Popup.AnchoredBubble=OpenLayers.Class(OpenLayers.Popup.Anchored,{rounded:false,initialize:function(id,lonlat,contentSize,contentHTML,anchor,closeBox,closeBoxCallback){this.padding=new OpenLayers.Bounds(0,OpenLayers.Popup.AnchoredBubble.CORNER_SIZE,0,OpenLayers.Popup.AnchoredBubble.CORNER_SIZE);OpenLayers.Popup.Anchored.prototype.initialize.apply(this,arguments);},draw:function(px){OpenLayers.Popup.Anchored.prototype.draw.apply(this,arguments);this.setContentHTML();this.setBackgroundColor();this.setOpacity();return this.div;},updateRelativePosition:function(){this.setRicoCorners();},setSize:function(contentSize){OpenLayers.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){OpenLayers.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=OpenLayers.Bounds.oppositeQuadrant(this.relativePosition);OpenLayers.Util.removeItem(corners,corner);return corners.join(" ");},CLASS_NAME:"OpenLayers.Popup.AnchoredBubble"});OpenLayers.Popup.AnchoredBubble.CORNER_SIZE=5;OpenLayers.Popup.Framed=OpenLayers.Class(OpenLayers.Popup.Anchored,{imageSrc:null,imageSize:null,isAlphaImage:false,positionBlocks:null,blocks:null,fixedRelativePosition:false,initialize:function(id,lonlat,contentSize,contentHTML,anchor,closeBox,closeBoxCallback){OpenLayers.Popup.Anchored.prototype.initialize.apply(this,arguments);if(this.fixedRelativePosition){this.updateRelativePosition();this.calculateRelativePosition=function(px){return this.relativePosition;};}
this.contentDiv.style.position="absolute";this.contentDiv.style.zIndex=1;if(closeBox){this.closeDiv.style.zIndex=1;}
this.groupDiv.style.position="absolute";this.groupDiv.style.top="0px";this.groupDiv.style.left="0px";this.groupDiv.style.height="100%";this.groupDiv.style.width="100%";},destroy:function(){this.imageSrc=null;this.imageSize=null;this.isAlphaImage=null;this.fixedRelativePosition=false;this.positionBlocks=null;for(var i=0;i<this.blocks.length;i++){var block=this.blocks[i];if(block.image){block.div.removeChild(block.image);}
block.image=null;if(block.div){this.groupDiv.removeChild(block.div);}
block.div=null;}
this.blocks=null;OpenLayers.Popup.Anchored.prototype.destroy.apply(this,arguments);},setBackgroundColor:function(color){},setBorder:function(){},setOpacity:function(opacity){},setSize:function(contentSize){OpenLayers.Popup.Anchored.prototype.setSize.apply(this,arguments);this.updateBlocks();},updateRelativePosition:function(){this.padding=this.positionBlocks[this.relativePosition].padding;if(this.closeDiv){var contentDivPadding=this.getContentDivPadding();this.closeDiv.style.right=contentDivPadding.right+
this.padding.right+"px";this.closeDiv.style.top=contentDivPadding.top+
this.padding.top+"px";}
this.updateBlocks();},calculateNewPx:function(px){var newPx=OpenLayers.Popup.Anchored.prototype.calculateNewPx.apply(this,arguments);newPx=newPx.offset(this.positionBlocks[this.relativePosition].offset);return newPx;},createBlocks:function(){this.blocks=[];var firstPosition=null;for(var key in this.positionBlocks){firstPosition=key;break;}
var position=this.positionBlocks[firstPosition];for(var i=0;i<position.blocks.length;i++){var block={};this.blocks.push(block);var divId=this.id+'_FrameDecorationDiv_'+i;block.div=OpenLayers.Util.createDiv(divId,null,null,null,"absolute",null,"hidden",null);var imgId=this.id+'_FrameDecorationImg_'+i;var imageCreator=(this.isAlphaImage)?OpenLayers.Util.createAlphaImageDiv:OpenLayers.Util.createImage;block.image=imageCreator(imgId,null,this.imageSize,this.imageSrc,"absolute",null,null,null);block.div.appendChild(block.image);this.groupDiv.appendChild(block.div);}},updateBlocks:function(){if(!this.blocks){this.createBlocks();}
if(this.size&&this.relativePosition){var position=this.positionBlocks[this.relativePosition];for(var i=0;i<position.blocks.length;i++){var positionBlock=position.blocks[i];var block=this.blocks[i];var l=positionBlock.anchor.left;var b=positionBlock.anchor.bottom;var r=positionBlock.anchor.right;var t=positionBlock.anchor.top;var w=(isNaN(positionBlock.size.w))?this.size.w-(r+l):positionBlock.size.w;var h=(isNaN(positionBlock.size.h))?this.size.h-(b+t):positionBlock.size.h;block.div.style.width=(w<0?0:w)+'px';block.div.style.height=(h<0?0:h)+'px';block.div.style.left=(l!=null)?l+'px':'';block.div.style.bottom=(b!=null)?b+'px':'';block.div.style.right=(r!=null)?r+'px':'';block.div.style.top=(t!=null)?t+'px':'';block.image.style.left=positionBlock.position.x+'px';block.image.style.top=positionBlock.position.y+'px';}
this.contentDiv.style.left=this.padding.left+"px";this.contentDiv.style.top=this.padding.top+"px";}},CLASS_NAME:"OpenLayers.Popup.Framed"});OpenLayers.Popup.FramedCloud=OpenLayers.Class(OpenLayers.Popup.Framed,{contentDisplayClass:"olFramedCloudPopupContent",autoSize:true,panMapIfOutOfView:true,imageSize:new OpenLayers.Size(676,736),isAlphaImage:false,fixedRelativePosition:false,positionBlocks:{"tl":{'offset':new OpenLayers.Pixel(44,0),'padding':new OpenLayers.Bounds(8,40,8,9),'blocks':[{size:new OpenLayers.Size('auto','auto'),anchor:new OpenLayers.Bounds(0,51,22,0),position:new OpenLayers.Pixel(0,0)},{size:new OpenLayers.Size(22,'auto'),anchor:new OpenLayers.Bounds(null,50,0,0),position:new OpenLayers.Pixel(-638,0)},{size:new OpenLayers.Size('auto',19),anchor:new OpenLayers.Bounds(0,32,22,null),position:new OpenLayers.Pixel(0,-631)},{size:new OpenLayers.Size(22,18),anchor:new OpenLayers.Bounds(null,32,0,null),position:new OpenLayers.Pixel(-638,-632)},{size:new OpenLayers.Size(81,35),anchor:new OpenLayers.Bounds(null,0,0,null),position:new OpenLayers.Pixel(0,-688)}]},"tr":{'offset':new OpenLayers.Pixel(-45,0),'padding':new OpenLayers.Bounds(8,40,8,9),'blocks':[{size:new OpenLayers.Size('auto','auto'),anchor:new OpenLayers.Bounds(0,51,22,0),position:new OpenLayers.Pixel(0,0)},{size:new OpenLayers.Size(22,'auto'),anchor:new OpenLayers.Bounds(null,50,0,0),position:new OpenLayers.Pixel(-638,0)},{size:new OpenLayers.Size('auto',19),anchor:new OpenLayers.Bounds(0,32,22,null),position:new OpenLayers.Pixel(0,-631)},{size:new OpenLayers.Size(22,19),anchor:new OpenLayers.Bounds(null,32,0,null),position:new OpenLayers.Pixel(-638,-631)},{size:new OpenLayers.Size(81,35),anchor:new OpenLayers.Bounds(0,0,null,null),position:new OpenLayers.Pixel(-215,-687)}]},"bl":{'offset':new OpenLayers.Pixel(45,0),'padding':new OpenLayers.Bounds(8,9,8,40),'blocks':[{size:new OpenLayers.Size('auto','auto'),anchor:new OpenLayers.Bounds(0,21,22,32),position:new OpenLayers.Pixel(0,0)},{size:new OpenLayers.Size(22,'auto'),anchor:new OpenLayers.Bounds(null,21,0,32),position:new OpenLayers.Pixel(-638,0)},{size:new OpenLayers.Size('auto',21),anchor:new OpenLayers.Bounds(0,0,22,null),position:new OpenLayers.Pixel(0,-629)},{size:new OpenLayers.Size(22,21),anchor:new OpenLayers.Bounds(null,0,0,null),position:new OpenLayers.Pixel(-638,-629)},{size:new OpenLayers.Size(81,33),anchor:new OpenLayers.Bounds(null,null,0,0),position:new OpenLayers.Pixel(-101,-674)}]},"br":{'offset':new OpenLayers.Pixel(-44,0),'padding':new OpenLayers.Bounds(8,9,8,40),'blocks':[{size:new OpenLayers.Size('auto','auto'),anchor:new OpenLayers.Bounds(0,21,22,32),position:new OpenLayers.Pixel(0,0)},{size:new OpenLayers.Size(22,'auto'),anchor:new OpenLayers.Bounds(null,21,0,32),position:new OpenLayers.Pixel(-638,0)},{size:new OpenLayers.Size('auto',21),anchor:new OpenLayers.Bounds(0,0,22,null),position:new OpenLayers.Pixel(0,-629)},{size:new OpenLayers.Size(22,21),anchor:new OpenLayers.Bounds(null,0,0,null),position:new OpenLayers.Pixel(-638,-629)},{size:new OpenLayers.Size(81,33),anchor:new OpenLayers.Bounds(0,null,null,0),position:new OpenLayers.Pixel(-311,-674)}]}},minSize:new OpenLayers.Size(105,10),maxSize:new OpenLayers.Size(600,660),initialize:function(id,lonlat,contentSize,contentHTML,anchor,closeBox,closeBoxCallback){this.imageSrc=OpenLayers.Util.getImagesLocation()+'cloud-popup-relative.png';OpenLayers.Popup.Framed.prototype.initialize.apply(this,arguments);this.contentDiv.className=this.contentDisplayClass;},destroy:function(){OpenLayers.Popup.Framed.prototype.destroy.apply(this,arguments);},CLASS_NAME:"OpenLayers.Popup.FramedCloud"});OpenLayers.Feature=OpenLayers.Class({layer:null,id:null,lonlat:null,data:null,marker:null,popupClass:OpenLayers.Popup.AnchoredBubble,popup:null,initialize:function(layer,lonlat,data){this.layer=layer;this.lonlat=lonlat;this.data=(data!=null)?data:{};this.id=OpenLayers.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 OpenLayers.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:"OpenLayers.Feature"});OpenLayers.State={UNKNOWN:'Unknown',INSERT:'Insert',UPDATE:'Update',DELETE:'Delete'};OpenLayers.Feature.Vector=OpenLayers.Class(OpenLayers.Feature,{fid:null,geometry:null,attributes:null,bounds:null,state:null,style:null,renderIntent:"default",initialize:function(geometry,attributes,style){OpenLayers.Feature.prototype.initialize.apply(this,[null,null,attributes]);this.lonlat=null;this.geometry=geometry?geometry:null;this.state=null;this.attributes={};if(attributes){this.attributes=OpenLayers.Util.extend(this.attributes,attributes);}
this.style=style?style:null;},destroy:function(){if(this.layer){this.layer.removeFeatures(this);this.layer=null;}
this.geometry=null;OpenLayers.Feature.prototype.destroy.apply(this,arguments);},clone:function(){return new OpenLayers.Feature.Vector(this.geometry?this.geometry.clone():null,this.attributes,this.style);},onScreen:function(boundsOnly){var onScreen=false;if(this.layer&&this.layer.map){var screenBounds=this.layer.map.getExtent();if(boundsOnly){var featureBounds=this.geometry.getBounds();onScreen=screenBounds.intersectsBounds(featureBounds);}else{var screenPoly=screenBounds.toGeometry();onScreen=screenPoly.intersects(this.geometry);}}
return onScreen;},createMarker:function(){return null;},destroyMarker:function(){},createPopup:function(){return null;},atPoint:function(lonlat,toleranceLon,toleranceLat){var atPoint=false;if(this.geometry){atPoint=this.geometry.atPoint(lonlat,toleranceLon,toleranceLat);}
return atPoint;},destroyPopup:function(){},move:function(location){if(!this.layer||!this.geometry.move){return;}
var pixel;if(location.CLASS_NAME=="OpenLayers.LonLat"){pixel=this.layer.getViewPortPxFromLonLat(location);}else{pixel=location;}
var lastPixel=this.layer.getViewPortPxFromLonLat(this.geometry.getBounds().getCenterLonLat());var res=this.layer.map.getResolution();this.geometry.move(res*(pixel.x-lastPixel.x),res*(lastPixel.y-pixel.y));this.layer.drawFeature(this);return lastPixel;},toState:function(state){if(state==OpenLayers.State.UPDATE){switch(this.state){case OpenLayers.State.UNKNOWN:case OpenLayers.State.DELETE:this.state=state;break;case OpenLayers.State.UPDATE:case OpenLayers.State.INSERT:break;}}else if(state==OpenLayers.State.INSERT){switch(this.state){case OpenLayers.State.UNKNOWN:break;default:this.state=state;break;}}else if(state==OpenLayers.State.DELETE){switch(this.state){case OpenLayers.State.INSERT:break;case OpenLayers.State.DELETE:break;case OpenLayers.State.UNKNOWN:case OpenLayers.State.UPDATE:this.state=state;break;}}else if(state==OpenLayers.State.UNKNOWN){this.state=state;}},CLASS_NAME:"OpenLayers.Feature.Vector"});OpenLayers.Feature.Vector.style={'default':{fillColor:"#ee9900",fillOpacity:0.4,hoverFillColor:"white",hoverFillOpacity:0.8,strokeColor:"#ee9900",strokeOpacity:1,strokeWidth:1,strokeLinecap:"round",strokeDashstyle:"solid",hoverStrokeColor:"red",hoverStrokeOpacity:1,hoverStrokeWidth:0.2,pointRadius:6,hoverPointRadius:1,hoverPointUnit:"%",pointerEvents:"visiblePainted",cursor:"inherit"},'select':{fillColor:"blue",fillOpacity:0.4,hoverFillColor:"white",hoverFillOpacity:0.8,strokeColor:"blue",strokeOpacity:1,strokeWidth:2,strokeLinecap:"round",strokeDashstyle:"solid",hoverStrokeColor:"red",hoverStrokeOpacity:1,hoverStrokeWidth:0.2,pointRadius:6,hoverPointRadius:1,hoverPointUnit:"%",pointerEvents:"visiblePainted",cursor:"pointer"},'temporary':{fillColor:"#66cccc",fillOpacity:0.2,hoverFillColor:"white",hoverFillOpacity:0.8,strokeColor:"#66cccc",strokeOpacity:1,strokeLinecap:"round",strokeWidth:2,strokeDashstyle:"solid",hoverStrokeColor:"red",hoverStrokeOpacity:1,hoverStrokeWidth:0.2,pointRadius:6,hoverPointRadius:1,hoverPointUnit:"%",pointerEvents:"visiblePainted",cursor:"inherit"},'delete':{display:"none"}};OpenLayers.Handler=OpenLayers.Class({id:null,control:null,map:null,keyMask:null,active:false,evt:null,initialize:function(control,callbacks,options){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+"_");},setMap:function(map){this.map=map;},checkModifiers:function(evt){if(this.keyMask==null){return true;}
var keyModifiers=(evt.shiftKey?OpenLayers.Handler.MOD_SHIFT:0)|(evt.ctrlKey?OpenLayers.Handler.MOD_CTRL:0)|(evt.altKey?OpenLayers.Handler.MOD_ALT:0);return(keyModifiers==this.keyMask);},activate:function(){if(this.active){return false;}
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;},deactivate:function(){if(!this.active){return false;}
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;},callback:function(name,args){if(name&&this.callbacks[name]){this.callbacks[name].apply(this.control,args);}},register:function(name,method){this.map.events.registerPriority(name,this,method);this.map.events.registerPriority(name,this,this.setEvent);},unregister:function(name,method){this.map.events.unregister(name,this,method);this.map.events.unregister(name,this,this.setEvent);},setEvent:function(evt){this.evt=evt;return true;},destroy:function(){this.deactivate();this.control=this.map=null;},CLASS_NAME:"OpenLayers.Handler"});OpenLayers.Handler.MOD_NONE=0;OpenLayers.Handler.MOD_SHIFT=1;OpenLayers.Handler.MOD_CTRL=2;OpenLayers.Handler.MOD_ALT=4;OpenLayers.Handler.Click=OpenLayers.Class(OpenLayers.Handler,{delay:300,single:true,'double':false,pixelTolerance:0,stopSingle:false,stopDouble:false,timerId:null,down:null,rightclickTimerId:null,initialize:function(control,callbacks,options){OpenLayers.Handler.prototype.initialize.apply(this,arguments);if(this.pixelTolerance!=null){this.mousedown=function(evt){this.down=evt.xy;return true;};}},mousedown:null,mouseup:function(evt){var propagate=true;if(this.checkModifiers(evt)&&this.control.handleRightClicks&&OpenLayers.Event.isRightClick(evt)){propagate=this.rightclick(evt);}
return propagate;},rightclick:function(evt){if(this.passesTolerance(evt)){if(this.rightclickTimerId!=null){this.clearTimer();this.callback('dblrightclick',[evt]);return!this.stopDouble;}else{var clickEvent=this['double']?OpenLayers.Util.extend({},evt):this.callback('rightclick',[evt]);var delayedRightCall=OpenLayers.Function.bind(this.delayedRightCall,this,clickEvent);this.rightclickTimerId=window.setTimeout(delayedRightCall,this.delay);}}
return!this.stopSingle;},delayedRightCall:function(evt){this.rightclickTimerId=null;if(evt){this.callback('rightclick',[evt]);}
return!this.stopSingle;},dblclick:function(evt){if(this.passesTolerance(evt)){if(this["double"]){this.callback('dblclick',[evt]);}
this.clearTimer();}
return!this.stopDouble;},click:function(evt){if(this.passesTolerance(evt)){if(this.timerId!=null){this.clearTimer();}else{var clickEvent=this.single?OpenLayers.Util.extend({},evt):null;this.timerId=window.setTimeout(OpenLayers.Function.bind(this.delayedCall,this,clickEvent),this.delay);}}
return!this.stopSingle;},passesTolerance:function(evt){var passes=true;if(this.pixelTolerance!=null&&this.down){var dpx=Math.sqrt(Math.pow(this.down.x-evt.xy.x,2)+
Math.pow(this.down.y-evt.xy.y,2));if(dpx>this.pixelTolerance){passes=false;}}
return passes;},clearTimer:function(){if(this.timerId!=null){window.clearTimeout(this.timerId);this.timerId=null;}
if(this.rightclickTimerId!=null){window.clearTimeout(this.rightclickTimerId);this.rightclickTimerId=null;}},delayedCall:function(evt){this.timerId=null;if(evt){this.callback('click',[evt]);}},deactivate:function(){var deactivated=false;if(OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){this.clearTimer();this.down=null;deactivated=true;}
return deactivated;},CLASS_NAME:"OpenLayers.Handler.Click"});OpenLayers.Handler.Hover=OpenLayers.Class(OpenLayers.Handler,{delay:500,pixelTolerance:null,stopMove:false,px:null,timerId:null,initialize:function(control,callbacks,options){OpenLayers.Handler.prototype.initialize.apply(this,arguments);},mousemove:function(evt){if(this.passesTolerance(evt.xy)){this.clearTimer();this.callback('move',[evt]);this.px=evt.xy;evt=OpenLayers.Util.extend({},evt);this.timerId=window.setTimeout(OpenLayers.Function.bind(this.delayedCall,this,evt),this.delay);}
return!this.stopMove;},mouseout:function(evt){if(OpenLayers.Util.mouseLeft(evt,this.map.div)){this.clearTimer();this.callback('move',[evt]);}
return true;},passesTolerance:function(px){var passes=true;if(this.pixelTolerance&&this.px){var dpx=Math.sqrt(Math.pow(this.px.x-px.x,2)+
Math.pow(this.px.y-px.y,2));if(dpx<this.pixelTolerance){passes=false;}}
return passes;},clearTimer:function(){if(this.timerId!=null){window.clearTimeout(this.timerId);this.timerId=null;}},delayedCall:function(evt){this.callback('pause',[evt]);},deactivate:function(){var deactivated=false;if(OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){this.clearTimer();deactivated=true;}
return deactivated;},CLASS_NAME:"OpenLayers.Handler.Hover"});OpenLayers.Handler.Point=OpenLayers.Class(OpenLayers.Handler,{point:null,layer:null,multi:false,drawing:false,mouseDown:false,lastDown:null,lastUp:null,persist:false,layerOptions:null,initialize:function(control,callbacks,options){if(!(options&&options.layerOptions&&options.layerOptions.styleMap)){this.style=OpenLayers.Util.extend(OpenLayers.Feature.Vector.style['default'],{});}
OpenLayers.Handler.prototype.initialize.apply(this,arguments);},activate:function(){if(!OpenLayers.Handler.prototype.activate.apply(this,arguments)){return false;}
var options=OpenLayers.Util.extend({displayInLayerSwitcher:false,calculateInRange:function(){return true;}},this.layerOptions);this.layer=new OpenLayers.Layer.Vector(this.CLASS_NAME,options);this.map.addLayer(this.layer);return true;},createFeature:function(pixel){var lonlat=this.map.getLonLatFromPixel(pixel);this.point=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonlat.lon,lonlat.lat));this.callback("create",[this.point.geometry,this.point]);this.point.geometry.clearBounds();this.layer.addFeatures([this.point],{silent:true});},deactivate:function(){if(!OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){return false;}
if(this.drawing){this.cancel();}
this.destroyFeature();if(this.layer.map!=null){this.layer.destroy(false);}
this.layer=null;return true;},destroyFeature:function(){if(this.layer){this.layer.destroyFeatures();}
this.point=null;},finalize:function(cancel){var key=cancel?"cancel":"done";this.drawing=false;this.mouseDown=false;this.lastDown=null;this.lastUp=null;this.callback(key,[this.geometryClone()]);if(cancel||!this.persist){this.destroyFeature();}},cancel:function(){this.finalize(true);},click:function(evt){OpenLayers.Event.stop(evt);return false;},dblclick:function(evt){OpenLayers.Event.stop(evt);return false;},modifyFeature:function(pixel){var lonlat=this.map.getLonLatFromPixel(pixel);this.point.geometry.x=lonlat.lon;this.point.geometry.y=lonlat.lat;this.callback("modify",[this.point.geometry,this.point]);this.point.geometry.clearBounds();this.drawFeature();},drawFeature:function(){this.layer.drawFeature(this.point,this.style);},getGeometry:function(){var geometry=this.point&&this.point.geometry;if(geometry&&this.multi){geometry=new OpenLayers.Geometry.MultiPoint([geometry]);}
return geometry;},geometryClone:function(){var geom=this.getGeometry();return geom&&geom.clone();},mousedown:function(evt){if(!this.checkModifiers(evt)){return true;}
if(this.lastDown&&this.lastDown.equals(evt.xy)){return true;}
this.drawing=true;if(this.lastDown==null){if(this.persist){this.destroyFeature();}
this.createFeature(evt.xy);}else{this.modifyFeature(evt.xy);}
this.lastDown=evt.xy;return false;},mousemove:function(evt){if(this.drawing){this.modifyFeature(evt.xy);}
return true;},mouseup:function(evt){if(this.drawing){this.finalize();return false;}else{return true;}},CLASS_NAME:"OpenLayers.Handler.Point"});OpenLayers.Handler.Path=OpenLayers.Class(OpenLayers.Handler.Point,{line:null,freehand:false,freehandToggle:'shiftKey',initialize:function(control,callbacks,options){OpenLayers.Handler.Point.prototype.initialize.apply(this,arguments);},createFeature:function(pixel){var lonlat=this.control.map.getLonLatFromPixel(pixel);this.point=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonlat.lon,lonlat.lat));this.line=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString([this.point.geometry]));this.callback("create",[this.point.geometry,this.getSketch()]);this.point.geometry.clearBounds();this.layer.addFeatures([this.line,this.point],{silent:true});},destroyFeature:function(){OpenLayers.Handler.Point.prototype.destroyFeature.apply(this);this.line=null;},removePoint:function(){if(this.point){this.layer.removeFeatures([this.point]);}},addPoint:function(pixel){this.layer.removeFeatures([this.point]);var lonlat=this.control.map.getLonLatFromPixel(pixel);this.point=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonlat.lon,lonlat.lat));this.line.geometry.addComponent(this.point.geometry,this.line.geometry.components.length);this.callback("point",[this.point.geometry,this.getGeometry()]);this.callback("modify",[this.point.geometry,this.getSketch()]);this.drawFeature();},freehandMode:function(evt){return(this.freehandToggle&&evt[this.freehandToggle])?!this.freehand:this.freehand;},modifyFeature:function(pixel){var lonlat=this.control.map.getLonLatFromPixel(pixel);this.point.geometry.x=lonlat.lon;this.point.geometry.y=lonlat.lat;this.callback("modify",[this.point.geometry,this.getSketch()]);this.point.geometry.clearBounds();this.drawFeature();},drawFeature:function(){this.layer.drawFeature(this.line,this.style);this.layer.drawFeature(this.point,this.style);},getSketch:function(){return this.line;},getGeometry:function(){var geometry=this.line&&this.line.geometry;if(geometry&&this.multi){geometry=new OpenLayers.Geometry.MultiLineString([geometry]);}
return geometry;},mousedown:function(evt){if(this.lastDown&&this.lastDown.equals(evt.xy)){return false;}
if(this.lastDown==null){if(this.persist){this.destroyFeature();}
this.createFeature(evt.xy);}else if((this.lastUp==null)||!this.lastUp.equals(evt.xy)){this.addPoint(evt.xy);}
this.mouseDown=true;this.lastDown=evt.xy;this.drawing=true;return false;},mousemove:function(evt){if(this.drawing){if(this.mouseDown&&this.freehandMode(evt)){this.addPoint(evt.xy);}else{this.modifyFeature(evt.xy);}}
return true;},mouseup:function(evt){this.mouseDown=false;if(this.drawing){if(this.freehandMode(evt)){this.removePoint();this.finalize();}else{if(this.lastUp==null){this.addPoint(evt.xy);}
this.lastUp=evt.xy;}
return false;}
return true;},dblclick:function(evt){if(!this.freehandMode(evt)){var index=this.line.geometry.components.length-1;this.line.geometry.removeComponent(this.line.geometry.components[index]);this.removePoint();this.finalize();}
return false;},CLASS_NAME:"OpenLayers.Handler.Path"});OpenLayers.Handler.Polygon=OpenLayers.Class(OpenLayers.Handler.Path,{polygon:null,initialize:function(control,callbacks,options){OpenLayers.Handler.Path.prototype.initialize.apply(this,arguments);},createFeature:function(pixel){var lonlat=this.control.map.getLonLatFromPixel(pixel);this.point=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonlat.lon,lonlat.lat));this.line=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LinearRing([this.point.geometry]));this.polygon=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([this.line.geometry]));this.callback("create",[this.point.geometry,this.getSketch()]);this.point.geometry.clearBounds();this.layer.addFeatures([this.polygon,this.point],{silent:true});},destroyFeature:function(){OpenLayers.Handler.Path.prototype.destroyFeature.apply(this);this.polygon=null;},drawFeature:function(){this.layer.drawFeature(this.polygon,this.style);this.layer.drawFeature(this.point,this.style);},getSketch:function(){return this.polygon;},getGeometry:function(){var geometry=this.polygon&&this.polygon.geometry;if(geometry&&this.multi){geometry=new OpenLayers.Geometry.MultiPolygon([geometry]);}
return geometry;},dblclick:function(evt){if(!this.freehandMode(evt)){var index=this.line.geometry.components.length-2;this.line.geometry.removeComponent(this.line.geometry.components[index]);this.removePoint();this.finalize();}
return false;},CLASS_NAME:"OpenLayers.Handler.Polygon"});OpenLayers.Handler.Feature=OpenLayers.Class(OpenLayers.Handler,{EVENTMAP:{'click':{'in':'click','out':'clickout'},'mousemove':{'in':'over','out':'out'},'dblclick':{'in':'dblclick','out':null},'mousedown':{'in':null,'out':null},'mouseup':{'in':null,'out':null}},feature:null,lastFeature:null,down:null,up:null,clickTolerance:4,geometryTypes:null,stopClick:true,stopDown:true,stopUp:false,initialize:function(control,layer,callbacks,options){OpenLayers.Handler.prototype.initialize.apply(this,[control,callbacks,options]);this.layer=layer;},mousedown:function(evt){this.down=evt.xy;return this.handle(evt)?!this.stopDown:true;},mouseup:function(evt){this.up=evt.xy;return this.handle(evt)?!this.stopUp:true;},click:function(evt){return this.handle(evt)?!this.stopClick:true;},mousemove:function(evt){if(!this.callbacks['over']&&!this.callbacks['out']){return true;}
this.handle(evt);return true;},dblclick:function(evt){return!this.handle(evt);},geometryTypeMatches:function(feature){return this.geometryTypes==null||OpenLayers.Util.indexOf(this.geometryTypes,feature.geometry.CLASS_NAME)>-1;},handle:function(evt){if(this.feature&&!this.feature.layer){this.feature=null;}
var type=evt.type;var handled=false;var previouslyIn=!!(this.feature);var click=(type=="click"||type=="dblclick");this.feature=this.layer.getFeatureFromEvent(evt);if(this.feature&&!this.feature.layer){this.feature=null;}
if(this.lastFeature&&!this.lastFeature.layer){this.lastFeature=null;}
if(this.feature){var inNew=(this.feature!=this.lastFeature);if(this.geometryTypeMatches(this.feature)){if(previouslyIn&&inNew){if(this.lastFeature){this.triggerCallback(type,'out',[this.lastFeature]);}
this.triggerCallback(type,'in',[this.feature]);}else if(!previouslyIn||click){this.triggerCallback(type,'in',[this.feature]);}
this.lastFeature=this.feature;handled=true;}else{if(this.lastFeature&&(previouslyIn&&inNew||click)){this.triggerCallback(type,'out',[this.lastFeature]);}
this.feature=null;}}else{if(this.lastFeature&&(previouslyIn||click)){this.triggerCallback(type,'out',[this.lastFeature]);}}
return handled;},triggerCallback:function(type,mode,args){var key=this.EVENTMAP[type][mode];if(key){if(type=='click'&&this.up&&this.down){var dpx=Math.sqrt(Math.pow(this.up.x-this.down.x,2)+
Math.pow(this.up.y-this.down.y,2));if(dpx<=this.clickTolerance){this.callback(key,args);}}else{this.callback(key,args);}}},activate:function(){var activated=false;if(OpenLayers.Handler.prototype.activate.apply(this,arguments)){this.moveLayerToTop();this.map.events.on({"removelayer":this.handleMapEvents,"changelayer":this.handleMapEvents,scope:this});activated=true;}
return activated;},deactivate:function(){var deactivated=false;if(OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){this.moveLayerBack();this.feature=null;this.lastFeature=null;this.down=null;this.up=null;this.map.events.un({"removelayer":this.handleMapEvents,"changelayer":this.handleMapEvents,scope:this});deactivated=true;}
return deactivated;},handleMapEvents:function(evt){if(!evt.property||evt.property=="order"){this.moveLayerToTop();}},moveLayerToTop:function(){var index=Math.max(this.map.Z_INDEX_BASE['Feature']-1,this.layer.getZIndex())+1;this.layer.setZIndex(index);},moveLayerBack:function(){var index=this.layer.getZIndex()-1;if(index>=this.map.Z_INDEX_BASE['Feature']){this.layer.setZIndex(index);}else{this.map.setLayerZIndex(this.layer,this.map.getLayerIndex(this.layer));}},CLASS_NAME:"OpenLayers.Handler.Feature"});OpenLayers.Handler.Drag=OpenLayers.Class(OpenLayers.Handler,{started:false,stopDown:true,dragging:false,last:null,start:null,oldOnselectstart:null,interval:0,timeoutId:null,initialize:function(control,callbacks,options){OpenLayers.Handler.prototype.initialize.apply(this,arguments);},down:function(evt){},move:function(evt){},up:function(evt){},out:function(evt){},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;OpenLayers.Element.addClass(this.map.viewPortDiv,"olDragDown");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;},mousemove:function(evt){if(this.started&&!this.timeoutId&&(evt.xy.x!=this.last.x||evt.xy.y!=this.last.y)){if(this.interval>0){this.timeoutId=setTimeout(OpenLayers.Function.bind(this.removeTimeout,this),this.interval);}
this.dragging=true;this.move(evt);this.callback("move",[evt.xy]);if(!this.oldOnselectstart){this.oldOnselectstart=document.onselectstart;document.onselectstart=function(){return false;};}
this.last=this.evt.xy;}
return true;},removeTimeout:function(){this.timeoutId=null;},mouseup:function(evt){if(this.started){var dragged=(this.start!=this.last);this.started=false;this.dragging=false;OpenLayers.Element.removeClass(this.map.viewPortDiv,"olDragDown");this.up(evt);this.callback("up",[evt.xy]);if(dragged){this.callback("done",[evt.xy]);}
document.onselectstart=this.oldOnselectstart;}
return true;},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;OpenLayers.Element.removeClass(this.map.viewPortDiv,"olDragDown");this.out(evt);this.callback("out",[]);if(dragged){this.callback("done",[evt.xy]);}
if(document.onselectstart){document.onselectstart=this.oldOnselectstart;}}
return true;},click:function(evt){return(this.start==this.last);},activate:function(){var activated=false;if(OpenLayers.Handler.prototype.activate.apply(this,arguments)){this.dragging=false;activated=true;}
return activated;},deactivate:function(){var deactivated=false;if(OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){this.started=false;this.dragging=false;this.start=null;this.last=null;deactivated=true;OpenLayers.Element.removeClass(this.map.viewPortDiv,"olDragDown");}
return deactivated;},CLASS_NAME:"OpenLayers.Handler.Drag"});OpenLayers.Handler.RegularPolygon=OpenLayers.Class(OpenLayers.Handler.Drag,{sides:4,radius:null,snapAngle:null,snapToggle:'shiftKey',persist:false,irregular:false,angle:null,fixedRadius:false,feature:null,layer:null,origin:null,initialize:function(control,callbacks,options){this.style=OpenLayers.Util.extend(OpenLayers.Feature.Vector.style['default'],{});OpenLayers.Handler.prototype.initialize.apply(this,[control,callbacks,options]);this.options=(options)?options:new Object();},setOptions:function(newOptions){OpenLayers.Util.extend(this.options,newOptions);OpenLayers.Util.extend(this,newOptions);},activate:function(){var activated=false;if(OpenLayers.Handler.prototype.activate.apply(this,arguments)){var options={displayInLayerSwitcher:false,calculateInRange:function(){return true;}};this.layer=new OpenLayers.Layer.Vector(this.CLASS_NAME,options);this.map.addLayer(this.layer);activated=true;}
return activated;},deactivate:function(){var deactivated=false;if(OpenLayers.Handler.Drag.prototype.deactivate.apply(this,arguments)){if(this.dragging){this.cancel();}
if(this.layer.map!=null){this.layer.destroy(false);if(this.feature){this.feature.destroy();}}
this.layer=null;this.feature=null;deactivated=true;}
return deactivated;},down:function(evt){this.fixedRadius=!!(this.radius);var maploc=this.map.getLonLatFromPixel(evt.xy);this.origin=new OpenLayers.Geometry.Point(maploc.lon,maploc.lat);if(!this.fixedRadius||this.irregular){this.radius=this.map.getResolution();}
if(this.persist){this.clear();}
this.feature=new OpenLayers.Feature.Vector();this.createGeometry();this.callback("create",[this.origin,this.feature]);this.layer.addFeatures([this.feature],{silent:true});this.layer.drawFeature(this.feature,this.style);},move:function(evt){var maploc=this.map.getLonLatFromPixel(evt.xy);var point=new OpenLayers.Geometry.Point(maploc.lon,maploc.lat);if(this.irregular){var ry=Math.sqrt(2)*Math.abs(point.y-this.origin.y)/2;this.radius=Math.max(this.map.getResolution()/2,ry);}else if(this.fixedRadius){this.origin=point;}else{this.calculateAngle(point,evt);this.radius=Math.max(this.map.getResolution()/2,point.distanceTo(this.origin));}
this.modifyGeometry();if(this.irregular){var dx=point.x-this.origin.x;var dy=point.y-this.origin.y;var ratio;if(dy==0){ratio=dx/(this.radius*Math.sqrt(2));}else{ratio=dx/dy;}
this.feature.geometry.resize(1,this.origin,ratio);this.feature.geometry.move(dx/2,dy/2);}
this.layer.drawFeature(this.feature,this.style);},up:function(evt){this.finalize();if(this.start==this.last){this.callback("done",[evt.xy]);}},out:function(evt){this.finalize();},createGeometry:function(){this.angle=Math.PI*((1/this.sides)-(1/2));if(this.snapAngle){this.angle+=this.snapAngle*(Math.PI/180);}
this.feature.geometry=OpenLayers.Geometry.Polygon.createRegularPolygon(this.origin,this.radius,this.sides,this.snapAngle);},modifyGeometry:function(){var angle,dx,dy,point;var ring=this.feature.geometry.components[0];if(ring.components.length!=(this.sides+1)){this.createGeometry();ring=this.feature.geometry.components[0];}
for(var i=0;i<this.sides;++i){point=ring.components[i];angle=this.angle+(i*2*Math.PI/this.sides);point.x=this.origin.x+(this.radius*Math.cos(angle));point.y=this.origin.y+(this.radius*Math.sin(angle));point.clearBounds();}},calculateAngle:function(point,evt){var alpha=Math.atan2(point.y-this.origin.y,point.x-this.origin.x);if(this.snapAngle&&(this.snapToggle&&!evt[this.snapToggle])){var snapAngleRad=(Math.PI/180)*this.snapAngle;this.angle=Math.round(alpha/snapAngleRad)*snapAngleRad;}else{this.angle=alpha;}},cancel:function(){this.callback("cancel",null);this.finalize();},finalize:function(){this.origin=null;this.radius=this.options.radius;},clear:function(){this.layer.renderer.clear();this.layer.destroyFeatures();},callback:function(name,args){if(this.callbacks[name]){this.callbacks[name].apply(this.control,[this.feature.geometry.clone()]);}
if(!this.persist&&(name=="done"||name=="cancel")){this.clear();}},CLASS_NAME:"OpenLayers.Handler.RegularPolygon"});OpenLayers.Handler.Box=OpenLayers.Class(OpenLayers.Handler,{dragHandler:null,boxDivClassName:'olHandlerBoxZoomBox',boxCharacteristics:null,initialize:function(control,callbacks,options){OpenLayers.Handler.prototype.initialize.apply(this,arguments);var callbacks={"down":this.startBox,"move":this.moveBox,"out":this.removeBox,"up":this.endBox};this.dragHandler=new OpenLayers.Handler.Drag(this,callbacks,{keyMask:this.keyMask});},setMap:function(map){OpenLayers.Handler.prototype.setMap.apply(this,arguments);if(this.dragHandler){this.dragHandler.setMap(map);}},startBox:function(xy){this.zoomBox=OpenLayers.Util.createDiv('zoomBox',this.dragHandler.start);this.zoomBox.className=this.boxDivClassName;this.zoomBox.style.zIndex=this.map.Z_INDEX_BASE["Popup"]-1;this.map.viewPortDiv.appendChild(this.zoomBox);OpenLayers.Element.addClass(this.map.viewPortDiv,"olDrawBox");},moveBox:function(xy){var startX=this.dragHandler.start.x;var startY=this.dragHandler.start.y;var deltaX=Math.abs(startX-xy.x);var deltaY=Math.abs(startY-xy.y);this.zoomBox.style.width=Math.max(1,deltaX)+"px";this.zoomBox.style.height=Math.max(1,deltaY)+"px";this.zoomBox.style.left=xy.x<startX?xy.x+"px":startX+"px";this.zoomBox.style.top=xy.y<startY?xy.y+"px":startY+"px";var box=this.getBoxCharacteristics();if(box.newBoxModel){if(xy.x>startX){this.zoomBox.style.width=Math.max(1,deltaX-box.xOffset)+"px";}
if(xy.y>startY){this.zoomBox.style.height=Math.max(1,deltaY-box.yOffset)+"px";}}},endBox:function(end){var result;if(Math.abs(this.dragHandler.start.x-end.x)>5||Math.abs(this.dragHandler.start.y-end.y)>5){var start=this.dragHandler.start;var top=Math.min(start.y,end.y);var bottom=Math.max(start.y,end.y);var left=Math.min(start.x,end.x);var right=Math.max(start.x,end.x);result=new OpenLayers.Bounds(left,bottom,right,top);}else{result=this.dragHandler.start.clone();}
this.removeBox();this.callback("done",[result]);},removeBox:function(){this.map.viewPortDiv.removeChild(this.zoomBox);this.zoomBox=null;this.boxCharacteristics=null;OpenLayers.Element.removeClass(this.map.viewPortDiv,"olDrawBox");},activate:function(){if(OpenLayers.Handler.prototype.activate.apply(this,arguments)){this.dragHandler.activate();return true;}else{return false;}},deactivate:function(){if(OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){this.dragHandler.deactivate();return true;}else{return false;}},getBoxCharacteristics:function(){if(!this.boxCharacteristics){var xOffset=parseInt(OpenLayers.Element.getStyle(this.zoomBox,"border-left-width"))+parseInt(OpenLayers.Element.getStyle(this.zoomBox,"border-right-width"))+1;var yOffset=parseInt(OpenLayers.Element.getStyle(this.zoomBox,"border-top-width"))+parseInt(OpenLayers.Element.getStyle(this.zoomBox,"border-bottom-width"))+1;var newBoxModel=OpenLayers.Util.getBrowserName()=="msie"?document.compatMode!="BackCompat":true;this.boxCharacteristics={xOffset:xOffset,yOffset:yOffset,newBoxModel:newBoxModel};}
return this.boxCharacteristics;},CLASS_NAME:"OpenLayers.Handler.Box"});OpenLayers.Handler.MouseWheel=OpenLayers.Class(OpenLayers.Handler,{wheelListener:null,mousePosition:null,initialize:function(control,callbacks,options){OpenLayers.Handler.prototype.initialize.apply(this,arguments);this.wheelListener=OpenLayers.Function.bindAsEventListener(this.onWheelEvent,this);},destroy:function(){OpenLayers.Handler.prototype.destroy.apply(this,arguments);this.wheelListener=null;},onWheelEvent:function(e){if(!this.map||!this.checkModifiers(e)){return;}
var overScrollableDiv=false;var overLayerDiv=false;var overMapDiv=false;var elem=OpenLayers.Event.element(e);while((elem!=null)&&!overMapDiv&&!overScrollableDiv){if(!overScrollableDiv){try{if(elem.currentStyle){overflow=elem.currentStyle["overflow"];}else{var style=document.defaultView.getComputedStyle(elem,null);var overflow=style.getPropertyValue("overflow");}
overScrollableDiv=(overflow&&(overflow=="auto")||(overflow=="scroll"));}catch(err){}}
if(!overLayerDiv){for(var i=0,len=this.map.layers.length;i<len;i++){if(elem==this.map.layers[i].div||elem==this.map.layers[i].pane){overLayerDiv=true;break;}}}
overMapDiv=(elem==this.map.div);elem=elem.parentNode;}
if(!overScrollableDiv&&overMapDiv){if(overLayerDiv){this.wheelZoom(e);}
OpenLayers.Event.stop(e);}},wheelZoom:function(e){var delta=0;if(!e){e=window.event;}
if(e.wheelDelta){delta=e.wheelDelta/120;if(window.opera&&window.opera.version()<9.2){delta=-delta;}}else if(e.detail){delta=-e.detail/3;}
if(delta){if(this.mousePosition){e.xy=this.mousePosition;}
if(!e.xy){e.xy=this.map.getPixelFromLonLat(this.map.getCenter());}
if(delta<0){this.callback("down",[e,delta]);}else{this.callback("up",[e,delta]);}}},mousemove:function(evt){this.mousePosition=evt.xy;},activate:function(evt){if(OpenLayers.Handler.prototype.activate.apply(this,arguments)){var wheelListener=this.wheelListener;OpenLayers.Event.observe(window,"DOMMouseScroll",wheelListener);OpenLayers.Event.observe(window,"mousewheel",wheelListener);OpenLayers.Event.observe(document,"mousewheel",wheelListener);return true;}else{return false;}},deactivate:function(evt){if(OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){var wheelListener=this.wheelListener;OpenLayers.Event.stopObserving(window,"DOMMouseScroll",wheelListener);OpenLayers.Event.stopObserving(window,"mousewheel",wheelListener);OpenLayers.Event.stopObserving(document,"mousewheel",wheelListener);return true;}else{return false;}},CLASS_NAME:"OpenLayers.Handler.MouseWheel"});OpenLayers.Handler.Keyboard=OpenLayers.Class(OpenLayers.Handler,{KEY_EVENTS:["keydown","keyup"],eventListener:null,initialize:function(control,callbacks,options){OpenLayers.Handler.prototype.initialize.apply(this,arguments);this.eventListener=OpenLayers.Function.bindAsEventListener(this.handleKeyEvent,this);},destroy:function(){this.deactivate();this.eventListener=null;OpenLayers.Handler.prototype.destroy.apply(this,arguments);},activate:function(){if(OpenLayers.Handler.prototype.activate.apply(this,arguments)){for(var i=0,len=this.KEY_EVENTS.length;i<len;i++){OpenLayers.Event.observe(document,this.KEY_EVENTS[i],this.eventListener);}
return true;}else{return false;}},deactivate:function(){var deactivated=false;if(OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){for(var i=0,len=this.KEY_EVENTS.length;i<len;i++){OpenLayers.Event.stopObserving(document,this.KEY_EVENTS[i],this.eventListener);}
deactivated=true;}
return deactivated;},handleKeyEvent:function(evt){if(this.checkModifiers(evt)){this.callback(evt.type,[evt]);}},CLASS_NAME:"OpenLayers.Handler.Keyboard"});OpenLayers.Control=OpenLayers.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("OpenLayers.","ol").replace(/\./g,"");OpenLayers.Util.extend(this,options);this.events=new OpenLayers.Events(this,null,this.EVENT_TYPES);if(this.eventListeners instanceof Object){this.events.on(this.eventListeners);}
if(this.id==null){this.id=OpenLayers.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=OpenLayers.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;if(this.map){OpenLayers.Element.addClass(this.map.viewPortDiv,this.displayClass.replace(/ /g,"")+"Active");}
this.events.triggerEvent("activate");return true;},deactivate:function(){if(this.active){if(this.handler){this.handler.deactivate();}
this.active=false;if(this.map){OpenLayers.Element.removeClass(this.map.viewPortDiv,this.displayClass.replace(/ /g,"")+"Active");}
this.events.triggerEvent("deactivate");return true;}
return false;},CLASS_NAME:"OpenLayers.Control"});OpenLayers.Control.TYPE_BUTTON=1;OpenLayers.Control.TYPE_TOGGLE=2;OpenLayers.Control.TYPE_TOOL=3;OpenLayers.Control.ZoomBox=OpenLayers.Class(OpenLayers.Control,{type:OpenLayers.Control.TYPE_TOOL,out:false,alwaysZoom:false,draw:function(){this.handler=new OpenLayers.Handler.Box(this,{done:this.zoomBox},{keyMask:this.keyMask});},zoomBox:function(position){if(position instanceof OpenLayers.Bounds){if(!this.out){var minXY=this.map.getLonLatFromPixel(new OpenLayers.Pixel(position.left,position.bottom));var maxXY=this.map.getLonLatFromPixel(new OpenLayers.Pixel(position.right,position.top));var bounds=new OpenLayers.Bounds(minXY.lon,minXY.lat,maxXY.lon,maxXY.lat);}else{var pixWidth=Math.abs(position.right-position.left);var pixHeight=Math.abs(position.top-position.bottom);var zoomFactor=Math.min((this.map.size.h/pixHeight),(this.map.size.w/pixWidth));var extent=this.map.getExtent();var center=this.map.getLonLatFromPixel(position.getCenterPixel());var xmin=center.lon-(extent.getWidth()/2)*zoomFactor;var xmax=center.lon+(extent.getWidth()/2)*zoomFactor;var ymin=center.lat-(extent.getHeight()/2)*zoomFactor;var ymax=center.lat+(extent.getHeight()/2)*zoomFactor;var bounds=new OpenLayers.Bounds(xmin,ymin,xmax,ymax);}
var lastZoom=this.map.getZoom();this.map.zoomToExtent(bounds);if(lastZoom==this.map.getZoom()&&this.alwaysZoom==true){this.map.zoomTo(lastZoom+(this.out?-1:1));}}else{if(!this.out){this.map.setCenter(this.map.getLonLatFromPixel(position),this.map.getZoom()+1);}else{this.map.setCenter(this.map.getLonLatFromPixel(position),this.map.getZoom()-1);}}},CLASS_NAME:"OpenLayers.Control.ZoomBox"});OpenLayers.Control.DragPan=OpenLayers.Class(OpenLayers.Control,{type:OpenLayers.Control.TYPE_TOOL,panned:false,interval:25,draw:function(){this.handler=new OpenLayers.Handler.Drag(this,{"move":this.panMap,"done":this.panMapDone},{interval:this.interval});},panMap:function(xy){this.panned=true;this.map.pan(this.handler.last.x-xy.x,this.handler.last.y-xy.y,{dragging:this.handler.dragging,animate:false});},panMapDone:function(xy){if(this.panned){this.panMap(xy);this.panned=false;}},CLASS_NAME:"OpenLayers.Control.DragPan"});OpenLayers.Control.Navigation=OpenLayers.Class(OpenLayers.Control,{dragPan:null,dragPanOptions:null,zoomBox:null,zoomWheelEnabled:true,handleRightClicks:false,zoomBoxKeyMask:OpenLayers.Handler.MOD_SHIFT,initialize:function(options){this.handlers={};OpenLayers.Control.prototype.initialize.apply(this,arguments);},destroy:function(){this.deactivate();if(this.dragPan){this.dragPan.destroy();}
this.dragPan=null;if(this.zoomBox){this.zoomBox.destroy();}
this.zoomBox=null;OpenLayers.Control.prototype.destroy.apply(this,arguments);},activate:function(){this.dragPan.activate();if(this.zoomWheelEnabled){this.handlers.wheel.activate();}
this.handlers.click.activate();this.zoomBox.activate();return OpenLayers.Control.prototype.activate.apply(this,arguments);},deactivate:function(){this.zoomBox.deactivate();this.dragPan.deactivate();this.handlers.click.deactivate();this.handlers.wheel.deactivate();return OpenLayers.Control.prototype.deactivate.apply(this,arguments);},draw:function(){if(this.handleRightClicks){this.map.viewPortDiv.oncontextmenu=function(){return false;};}
var clickCallbacks={'dblclick':this.defaultDblClick,'dblrightclick':this.defaultDblRightClick};var clickOptions={'double':true,'stopDouble':true};this.handlers.click=new OpenLayers.Handler.Click(this,clickCallbacks,clickOptions);this.dragPan=new OpenLayers.Control.DragPan(OpenLayers.Util.extend({map:this.map},this.dragPanOptions));this.zoomBox=new OpenLayers.Control.ZoomBox({map:this.map,keyMask:this.zoomBoxKeyMask});this.dragPan.draw();this.zoomBox.draw();this.handlers.wheel=new OpenLayers.Handler.MouseWheel(this,{"up":this.wheelUp,"down":this.wheelDown});this.activate();},defaultDblClick:function(evt){var newCenter=this.map.getLonLatFromViewPortPx(evt.xy);this.map.setCenter(newCenter,this.map.zoom+1);},defaultDblRightClick:function(evt){var newCenter=this.map.getLonLatFromViewPortPx(evt.xy);this.map.setCenter(newCenter,this.map.zoom-1);},wheelChange:function(evt,deltaZ){var newZoom=this.map.getZoom()+deltaZ;if(!this.map.isValidZoomLevel(newZoom)){return;}
var size=this.map.getSize();var deltaX=size.w/2-evt.xy.x;var deltaY=evt.xy.y-size.h/2;var newRes=this.map.baseLayer.getResolutionForZoom(newZoom);var zoomPoint=this.map.getLonLatFromPixel(evt.xy);var newCenter=new OpenLayers.LonLat(zoomPoint.lon+deltaX*newRes,zoomPoint.lat+deltaY*newRes);this.map.setCenter(newCenter,newZoom);},wheelUp:function(evt){this.wheelChange(evt,1);},wheelDown:function(evt){this.wheelChange(evt,-1);},disableZoomWheel:function(){this.zoomWheelEnabled=false;this.handlers.wheel.deactivate();},enableZoomWheel:function(){this.zoomWheelEnabled=true;if(this.active){this.handlers.wheel.activate();}},CLASS_NAME:"OpenLayers.Control.Navigation"});OpenLayers.Control.KeyboardDefaults=OpenLayers.Class(OpenLayers.Control,{slideFactor:75,initialize:function(){OpenLayers.Control.prototype.initialize.apply(this,arguments);},destroy:function(){if(this.handler){this.handler.destroy();}
this.handler=null;OpenLayers.Control.prototype.destroy.apply(this,arguments);},draw:function(){this.handler=new OpenLayers.Handler.Keyboard(this,{"keydown":this.defaultKeyPress});this.activate();},defaultKeyPress:function(evt){switch(evt.keyCode){case OpenLayers.Event.KEY_LEFT:this.map.pan(-this.slideFactor,0);break;case OpenLayers.Event.KEY_RIGHT:this.map.pan(this.slideFactor,0);break;case OpenLayers.Event.KEY_UP:this.map.pan(0,-this.slideFactor);break;case OpenLayers.Event.KEY_DOWN:this.map.pan(0,this.slideFactor);break;case 33:var size=this.map.getSize();this.map.pan(0,-0.75*size.h);break;case 34:var size=this.map.getSize();this.map.pan(0,0.75*size.h);break;case 35:var size=this.map.getSize();this.map.pan(0.75*size.w,0);break;case 36:var size=this.map.getSize();this.map.pan(-0.75*size.w,0);break;case 43:case 61:case 187:case 107:this.map.zoomIn();break;case 45:case 109:case 189:case 95:this.map.zoomOut();break;}},CLASS_NAME:"OpenLayers.Control.KeyboardDefaults"});OpenLayers.Geometry=OpenLayers.Class({id:null,parent:null,bounds:null,initialize:function(){this.id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_");},destroy:function(){this.id=null;this.bounds=null;},clone:function(){return new OpenLayers.Geometry();},setBounds:function(bounds){if(bounds){this.bounds=bounds.clone();}},clearBounds:function(){this.bounds=null;if(this.parent){this.parent.clearBounds();}},extendBounds:function(newBounds){var bounds=this.getBounds();if(!bounds){this.setBounds(newBounds);}else{this.bounds.extend(newBounds);}},getBounds:function(){if(this.bounds==null){this.calculateBounds();}
return this.bounds;},calculateBounds:function(){},distanceTo:function(geometry,options){},getVertices:function(nodes){},atPoint:function(lonlat,toleranceLon,toleranceLat){var atPoint=false;var bounds=this.getBounds();if((bounds!=null)&&(lonlat!=null)){var dX=(toleranceLon!=null)?toleranceLon:0;var dY=(toleranceLat!=null)?toleranceLat:0;var toleranceBounds=new OpenLayers.Bounds(this.bounds.left-dX,this.bounds.bottom-dY,this.bounds.right+dX,this.bounds.top+dY);atPoint=toleranceBounds.containsLonLat(lonlat);}
return atPoint;},getLength:function(){return 0.0;},getArea:function(){return 0.0;},getCentroid:function(){return null;},toString:function(){return OpenLayers.Format.WKT.prototype.write(new OpenLayers.Feature.Vector(this));},CLASS_NAME:"OpenLayers.Geometry"});OpenLayers.Geometry.fromWKT=function(wkt){var format=arguments.callee.format;if(!format){format=new OpenLayers.Format.WKT();arguments.callee.format=format;}
var geom;var result=format.read(wkt);if(result instanceof OpenLayers.Feature.Vector){geom=result.geometry;}else if(result instanceof Array){var len=result.length;var components=new Array(len);for(var i=0;i<len;++i){components[i]=result[i].geometry;}
geom=new OpenLayers.Geometry.Collection(components);}
return geom;};OpenLayers.Geometry.segmentsIntersect=function(seg1,seg2,options){var point=options&&options.point;var tolerance=options&&options.tolerance;var intersection=false;var x11_21=seg1.x1-seg2.x1;var y11_21=seg1.y1-seg2.y1;var x12_11=seg1.x2-seg1.x1;var y12_11=seg1.y2-seg1.y1;var y22_21=seg2.y2-seg2.y1;var x22_21=seg2.x2-seg2.x1;var d=(y22_21*x12_11)-(x22_21*y12_11);var n1=(x22_21*y11_21)-(y22_21*x11_21);var n2=(x12_11*y11_21)-(y12_11*x11_21);if(d==0){if(n1==0&&n2==0){intersection=true;}}else{var along1=n1/d;var along2=n2/d;if(along1>=0&&along1<=1&&along2>=0&&along2<=1){if(!point){intersection=true;}else{var x=seg1.x1+(along1*x12_11);var y=seg1.y1+(along1*y12_11);intersection=new OpenLayers.Geometry.Point(x,y);}}}
if(tolerance){var dist;if(intersection){if(point){var segs=[seg1,seg2];var seg,x,y;outer:for(var i=0;i<2;++i){seg=segs[i];for(var j=1;j<3;++j){x=seg["x"+j];y=seg["y"+j];dist=Math.sqrt(Math.pow(x-intersection.x,2)+
Math.pow(y-intersection.y,2));if(dist<tolerance){intersection.x=x;intersection.y=y;break outer;}}}}}else{var segs=[seg1,seg2];var source,target,x,y,p,result;outer:for(var i=0;i<2;++i){source=segs[i];target=segs[(i+1)%2];for(var j=1;j<3;++j){p={x:source["x"+j],y:source["y"+j]};result=OpenLayers.Geometry.distanceToSegment(p,target);if(result.distance<tolerance){if(point){intersection=new OpenLayers.Geometry.Point(p.x,p.y);}else{intersection=true;}
break outer;}}}}}
return intersection;};OpenLayers.Geometry.distanceToSegment=function(point,segment){var x0=point.x;var y0=point.y;var x1=segment.x1;var y1=segment.y1;var x2=segment.x2;var y2=segment.y2;var dx=x2-x1;var dy=y2-y1;var along=((dx*(x0-x1))+(dy*(y0-y1)))/(Math.pow(dx,2)+Math.pow(dy,2));var x,y;if(along<=0.0){x=x1;y=y1;}else if(along>=1.0){x=x2;y=y2;}else{x=x1+along*dx;y=y1+along*dy;}
return{distance:Math.sqrt(Math.pow(x-x0,2)+Math.pow(y-y0,2)),x:x,y:y};};OpenLayers.Geometry.Collection=OpenLayers.Class(OpenLayers.Geometry,{components:null,componentTypes:null,initialize:function(components){OpenLayers.Geometry.prototype.initialize.apply(this,arguments);this.components=[];if(components!=null){this.addComponents(components);}},destroy:function(){this.components.length=0;this.components=null;},clone:function(){var geometry=eval("new "+this.CLASS_NAME+"()");for(var i=0,len=this.components.length;i<len;i++){geometry.addComponent(this.components[i].clone());}
OpenLayers.Util.applyDefaults(geometry,this);return geometry;},getComponentsString:function(){var strings=[];for(var i=0,len=this.components.length;i<len;i++){strings.push(this.components[i].toShortString());}
return strings.join(",");},calculateBounds:function(){this.bounds=null;if(this.components&&this.components.length>0){this.setBounds(this.components[0].getBounds());for(var i=1,len=this.components.length;i<len;i++){this.extendBounds(this.components[i].getBounds());}}},addComponents:function(components){if(!(components instanceof Array)){components=[components];}
for(var i=0,len=components.length;i<len;i++){this.addComponent(components[i]);}},addComponent:function(component,index){var added=false;if(component){if(this.componentTypes==null||(OpenLayers.Util.indexOf(this.componentTypes,component.CLASS_NAME)>-1)){if(index!=null&&(index<this.components.length)){var components1=this.components.slice(0,index);var components2=this.components.slice(index,this.components.length);components1.push(component);this.components=components1.concat(components2);}else{this.components.push(component);}
component.parent=this;this.clearBounds();added=true;}}
return added;},removeComponents:function(components){if(!(components instanceof Array)){components=[components];}
for(var i=components.length-1;i>=0;--i){this.removeComponent(components[i]);}},removeComponent:function(component){OpenLayers.Util.removeItem(this.components,component);this.clearBounds();},getLength:function(){var length=0.0;for(var i=0,len=this.components.length;i<len;i++){length+=this.components[i].getLength();}
return length;},getArea:function(){var area=0.0;for(var i=0,len=this.components.length;i<len;i++){area+=this.components[i].getArea();}
return area;},getGeodesicArea:function(projection){var area=0.0;for(var i=0,len=this.components.length;i<len;i++){area+=this.components[i].getGeodesicArea(projection);}
return area;},getCentroid:function(){return this.components.length&&this.components[0].getCentroid();},getGeodesicLength:function(projection){var length=0.0;for(var i=0,len=this.components.length;i<len;i++){length+=this.components[i].getGeodesicLength(projection);}
return length;},move:function(x,y){for(var i=0,len=this.components.length;i<len;i++){this.components[i].move(x,y);}},rotate:function(angle,origin){for(var i=0,len=this.components.length;i<len;++i){this.components[i].rotate(angle,origin);}},resize:function(scale,origin,ratio){for(var i=0;i<this.components.length;++i){this.components[i].resize(scale,origin,ratio);}
return this;},distanceTo:function(geometry,options){var edge=!(options&&options.edge===false);var details=edge&&options&&options.details;var result,best;var min=Number.POSITIVE_INFINITY;for(var i=0,len=this.components.length;i<len;++i){result=this.components[i].distanceTo(geometry,options);distance=details?result.distance:result;if(distance<min){min=distance;best=result;if(min==0){break;}}}
return best;},equals:function(geometry){var equivalent=true;if(!geometry||!geometry.CLASS_NAME||(this.CLASS_NAME!=geometry.CLASS_NAME)){equivalent=false;}else if(!(geometry.components instanceof Array)||(geometry.components.length!=this.components.length)){equivalent=false;}else{for(var i=0,len=this.components.length;i<len;++i){if(!this.components[i].equals(geometry.components[i])){equivalent=false;break;}}}
return equivalent;},transform:function(source,dest){if(source&&dest){for(var i=0,len=this.components.length;i<len;i++){var component=this.components[i];component.transform(source,dest);}
this.bounds=null;}
return this;},intersects:function(geometry){var intersect=false;for(var i=0,len=this.components.length;i<len;++i){intersect=geometry.intersects(this.components[i]);if(intersect){break;}}
return intersect;},getVertices:function(nodes){var vertices=[];for(var i=0,len=this.components.length;i<len;++i){Array.prototype.push.apply(vertices,this.components[i].getVertices(nodes));}
return vertices;},CLASS_NAME:"OpenLayers.Geometry.Collection"});OpenLayers.Geometry.Point=OpenLayers.Class(OpenLayers.Geometry,{x:null,y:null,initialize:function(x,y){OpenLayers.Geometry.prototype.initialize.apply(this,arguments);this.x=parseFloat(x);this.y=parseFloat(y);},clone:function(obj){if(obj==null){obj=new OpenLayers.Geometry.Point(this.x,this.y);}
OpenLayers.Util.applyDefaults(obj,this);return obj;},calculateBounds:function(){this.bounds=new OpenLayers.Bounds(this.x,this.y,this.x,this.y);},distanceTo:function(geometry,options){var edge=!(options&&options.edge===false);var details=edge&&options&&options.details;var distance,x0,y0,x1,y1,result;if(geometry instanceof OpenLayers.Geometry.Point){x0=this.x;y0=this.y;x1=geometry.x;y1=geometry.y;distance=Math.sqrt(Math.pow(x0-x1,2)+Math.pow(y0-y1,2));result=!details?distance:{x0:x0,y0:y0,x1:x1,y1:y1,distance:distance};}else{result=geometry.distanceTo(this,options);if(details){result={x0:result.x1,y0:result.y1,x1:result.x0,y1:result.y0,distance:result.distance};}}
return result;},equals:function(geom){var equals=false;if(geom!=null){equals=((this.x==geom.x&&this.y==geom.y)||(isNaN(this.x)&&isNaN(this.y)&&isNaN(geom.x)&&isNaN(geom.y)));}
return equals;},toShortString:function(){return(this.x+", "+this.y);},move:function(x,y){this.x=this.x+x;this.y=this.y+y;this.clearBounds();},rotate:function(angle,origin){angle*=Math.PI/180;var radius=this.distanceTo(origin);var theta=angle+Math.atan2(this.y-origin.y,this.x-origin.x);this.x=origin.x+(radius*Math.cos(theta));this.y=origin.y+(radius*Math.sin(theta));this.clearBounds();},getCentroid:function(){return new OpenLayers.Geometry.Point(this.x,this.y);},resize:function(scale,origin,ratio){ratio=(ratio==undefined)?1:ratio;this.x=origin.x+(scale*ratio*(this.x-origin.x));this.y=origin.y+(scale*(this.y-origin.y));this.clearBounds();return this;},intersects:function(geometry){var intersect=false;if(geometry.CLASS_NAME=="OpenLayers.Geometry.Point"){intersect=this.equals(geometry);}else{intersect=geometry.intersects(this);}
return intersect;},transform:function(source,dest){if((source&&dest)){OpenLayers.Projection.transform(this,source,dest);this.bounds=null;}
return this;},getVertices:function(nodes){return[this];},CLASS_NAME:"OpenLayers.Geometry.Point"});OpenLayers.Geometry.MultiPoint=OpenLayers.Class(OpenLayers.Geometry.Collection,{componentTypes:["OpenLayers.Geometry.Point"],initialize:function(components){OpenLayers.Geometry.Collection.prototype.initialize.apply(this,arguments);},addPoint:function(point,index){this.addComponent(point,index);},removePoint:function(point){this.removeComponent(point);},CLASS_NAME:"OpenLayers.Geometry.MultiPoint"});OpenLayers.Geometry.Curve=OpenLayers.Class(OpenLayers.Geometry.MultiPoint,{componentTypes:["OpenLayers.Geometry.Point"],initialize:function(points){OpenLayers.Geometry.MultiPoint.prototype.initialize.apply(this,arguments);},getLength:function(){var length=0.0;if(this.components&&(this.components.length>1)){for(var i=1,len=this.components.length;i<len;i++){length+=this.components[i-1].distanceTo(this.components[i]);}}
return length;},getGeodesicLength:function(projection){var geom=this;if(projection){var gg=new OpenLayers.Projection("EPSG:4326");if(!gg.equals(projection)){geom=this.clone().transform(projection,gg);}}
var length=0.0;if(geom.components&&(geom.components.length>1)){var p1,p2;for(var i=1,len=geom.components.length;i<len;i++){p1=geom.components[i-1];p2=geom.components[i];length+=OpenLayers.Util.distVincenty({lon:p1.x,lat:p1.y},{lon:p2.x,lat:p2.y});}}
return length*1000;},CLASS_NAME:"OpenLayers.Geometry.Curve"});OpenLayers.Geometry.LineString=OpenLayers.Class(OpenLayers.Geometry.Curve,{initialize:function(points){OpenLayers.Geometry.Curve.prototype.initialize.apply(this,arguments);},removeComponent:function(point){if(this.components&&(this.components.length>2)){OpenLayers.Geometry.Collection.prototype.removeComponent.apply(this,arguments);}},intersects:function(geometry){var intersect=false;var type=geometry.CLASS_NAME;if(type=="OpenLayers.Geometry.LineString"||type=="OpenLayers.Geometry.LinearRing"||type=="OpenLayers.Geometry.Point"){var segs1=this.getSortedSegments();var segs2;if(type=="OpenLayers.Geometry.Point"){segs2=[{x1:geometry.x,y1:geometry.y,x2:geometry.x,y2:geometry.y}];}else{segs2=geometry.getSortedSegments();}
var seg1,seg1x1,seg1x2,seg1y1,seg1y2,seg2,seg2y1,seg2y2;outer:for(var i=0,len=segs1.length;i<len;++i){seg1=segs1[i];seg1x1=seg1.x1;seg1x2=seg1.x2;seg1y1=seg1.y1;seg1y2=seg1.y2;inner:for(var j=0,jlen=segs2.length;j<jlen;++j){seg2=segs2[j];if(seg2.x1>seg1x2){break;}
if(seg2.x2<seg1x1){continue;}
seg2y1=seg2.y1;seg2y2=seg2.y2;if(Math.min(seg2y1,seg2y2)>Math.max(seg1y1,seg1y2)){continue;}
if(Math.max(seg2y1,seg2y2)<Math.min(seg1y1,seg1y2)){continue;}
if(OpenLayers.Geometry.segmentsIntersect(seg1,seg2)){intersect=true;break outer;}}}}else{intersect=geometry.intersects(this);}
return intersect;},getSortedSegments:function(){var numSeg=this.components.length-1;var segments=new Array(numSeg);for(var i=0;i<numSeg;++i){point1=this.components[i];point2=this.components[i+1];if(point1.x<point2.x){segments[i]={x1:point1.x,y1:point1.y,x2:point2.x,y2:point2.y};}else{segments[i]={x1:point2.x,y1:point2.y,x2:point1.x,y2:point1.y};}}
function byX1(seg1,seg2){return seg1.x1-seg2.x1;}
return segments.sort(byX1);},splitWithSegment:function(seg,options){var edge=!(options&&options.edge===false);var tolerance=options&&options.tolerance;var lines=[];var verts=this.getVertices();var points=[];var intersections=[];var split=false;var vert1,vert2,point;var node,vertex,target;var interOptions={point:true,tolerance:tolerance};var result=null;for(var i=0,stop=verts.length-2;i<=stop;++i){vert1=verts[i];points.push(vert1.clone());vert2=verts[i+1];target={x1:vert1.x,y1:vert1.y,x2:vert2.x,y2:vert2.y};point=OpenLayers.Geometry.segmentsIntersect(seg,target,interOptions);if(point instanceof OpenLayers.Geometry.Point){if((point.x===seg.x1&&point.y===seg.y1)||(point.x===seg.x2&&point.y===seg.y2)||point.equals(vert1)||point.equals(vert2)){vertex=true;}else{vertex=false;}
if(vertex||edge){if(!point.equals(intersections[intersections.length-1])){intersections.push(point.clone());}
if(i===0){if(point.equals(vert1)){continue;}}
if(point.equals(vert2)){continue;}
split=true;if(!point.equals(vert1)){points.push(point);}
lines.push(new OpenLayers.Geometry.LineString(points));points=[point.clone()];}}}
if(split){points.push(vert2.clone());lines.push(new OpenLayers.Geometry.LineString(points));}
if(intersections.length>0){var xDir=seg.x1<seg.x2?1:-1;var yDir=seg.y1<seg.y2?1:-1;result={lines:lines,points:intersections.sort(function(p1,p2){return(xDir*p1.x-xDir*p2.x)||(yDir*p1.y-yDir*p2.y);})};}
return result;},split:function(target,options){var results=null;var mutual=options&&options.mutual;var sourceSplit,targetSplit,sourceParts,targetParts;if(target instanceof OpenLayers.Geometry.LineString){var verts=this.getVertices();var vert1,vert2,seg,splits,lines,point;var points=[];sourceParts=[];for(var i=0,stop=verts.length-2;i<=stop;++i){vert1=verts[i];vert2=verts[i+1];seg={x1:vert1.x,y1:vert1.y,x2:vert2.x,y2:vert2.y};targetParts=targetParts||[target];if(mutual){points.push(vert1.clone());}
for(var j=0;j<targetParts.length;++j){splits=targetParts[j].splitWithSegment(seg,options);if(splits){lines=splits.lines;if(lines.length>0){lines.unshift(j,1);Array.prototype.splice.apply(targetParts,lines);j+=lines.length-2;}
if(mutual){for(var k=0,len=splits.points.length;k<len;++k){point=splits.points[k];if(!point.equals(vert1)){points.push(point);sourceParts.push(new OpenLayers.Geometry.LineString(points));if(point.equals(vert2)){points=[];}else{points=[point.clone()];}}}}}}}
if(mutual&&sourceParts.length>0&&points.length>0){points.push(vert2.clone());sourceParts.push(new OpenLayers.Geometry.LineString(points));}}else{results=target.splitWith(this,options);}
if(targetParts&&targetParts.length>1){targetSplit=true;}else{targetParts=[];}
if(sourceParts&&sourceParts.length>1){sourceSplit=true;}else{sourceParts=[];}
if(targetSplit||sourceSplit){if(mutual){results=[sourceParts,targetParts];}else{results=targetParts;}}
return results;},splitWith:function(geometry,options){return geometry.split(this,options);},getVertices:function(nodes){var vertices;if(nodes===true){vertices=[this.components[0],this.components[this.components.length-1]];}else if(nodes===false){vertices=this.components.slice(1,this.components.length-1);}else{vertices=this.components.slice();}
return vertices;},distanceTo:function(geometry,options){var edge=!(options&&options.edge===false);var details=edge&&options&&options.details;var result,best={};var min=Number.POSITIVE_INFINITY;if(geometry instanceof OpenLayers.Geometry.Point){var segs=this.getSortedSegments();var x=geometry.x;var y=geometry.y;var seg;for(var i=0,len=segs.length;i<len;++i){seg=segs[i];result=OpenLayers.Geometry.distanceToSegment(geometry,seg);if(result.distance<min){min=result.distance;best=result;if(min===0){break;}}else{if(seg.x2>x&&((y>seg.y1&&y<seg.y2)||(y<seg.y1&&y>seg.y2))){break;}}}
if(details){best={distance:best.distance,x0:best.x,y0:best.y,x1:x,y1:y};}else{best=best.distance;}}else if(geometry instanceof OpenLayers.Geometry.LineString){var segs0=this.getSortedSegments();var segs1=geometry.getSortedSegments();var seg0,seg1,intersection,x0,y0;var len1=segs1.length;var interOptions={point:true};outer:for(var i=0,len=segs0.length;i<len;++i){seg0=segs0[i];x0=seg0.x1;y0=seg0.y1;for(var j=0;j<len1;++j){seg1=segs1[j];intersection=OpenLayers.Geometry.segmentsIntersect(seg0,seg1,interOptions);if(intersection){min=0;best={distance:0,x0:intersection.x,y0:intersection.y,x1:intersection.x,y1:intersection.y};break outer;}else{result=OpenLayers.Geometry.distanceToSegment({x:x0,y:y0},seg1);if(result.distance<min){min=result.distance;best={distance:min,x0:x0,y0:y0,x1:result.x,y1:result.y};}}}}
if(!details){best=best.distance;}
if(min!==0){if(seg0){result=geometry.distanceTo(new OpenLayers.Geometry.Point(seg0.x2,seg0.y2),options);var dist=details?result.distance:result;if(dist<min){if(details){best={distance:min,x0:result.x1,y0:result.y1,x1:result.x0,y1:result.y0};}else{best=dist;}}}}}else{best=geometry.distanceTo(this,options);if(details){best={distance:best.distance,x0:best.x1,y0:best.y1,x1:best.x0,y1:best.y0};}}
return best;},CLASS_NAME:"OpenLayers.Geometry.LineString"});OpenLayers.Geometry.LinearRing=OpenLayers.Class(OpenLayers.Geometry.LineString,{componentTypes:["OpenLayers.Geometry.Point"],initialize:function(points){OpenLayers.Geometry.LineString.prototype.initialize.apply(this,arguments);},addComponent:function(point,index){var added=false;var lastPoint=this.components.pop();if(index!=null||!point.equals(lastPoint)){added=OpenLayers.Geometry.Collection.prototype.addComponent.apply(this,arguments);}
var firstPoint=this.components[0];OpenLayers.Geometry.Collection.prototype.addComponent.apply(this,[firstPoint]);return added;},removeComponent:function(point){if(this.components.length>4){this.components.pop();OpenLayers.Geometry.Collection.prototype.removeComponent.apply(this,arguments);var firstPoint=this.components[0];OpenLayers.Geometry.Collection.prototype.addComponent.apply(this,[firstPoint]);}},move:function(x,y){for(var i=0,len=this.components.length;i<len-1;i++){this.components[i].move(x,y);}},rotate:function(angle,origin){for(var i=0,len=this.components.length;i<len-1;++i){this.components[i].rotate(angle,origin);}},resize:function(scale,origin,ratio){for(var i=0,len=this.components.length;i<len-1;++i){this.components[i].resize(scale,origin,ratio);}
return this;},transform:function(source,dest){if(source&&dest){for(var i=0,len=this.components.length;i<len-1;i++){var component=this.components[i];component.transform(source,dest);}
this.bounds=null;}
return this;},getCentroid:function(){if(this.components&&(this.components.length>2)){var sumX=0.0;var sumY=0.0;for(var i=0;i<this.components.length-1;i++){var b=this.components[i];var c=this.components[i+1];sumX+=(b.x+c.x)*(b.x*c.y-c.x*b.y);sumY+=(b.y+c.y)*(b.x*c.y-c.x*b.y);}
var area=-1*this.getArea();var x=sumX/(6*area);var y=sumY/(6*area);}
return new OpenLayers.Geometry.Point(x,y);},getArea:function(){var area=0.0;if(this.components&&(this.components.length>2)){var sum=0.0;for(var i=0,len=this.components.length;i<len-1;i++){var b=this.components[i];var c=this.components[i+1];sum+=(b.x+c.x)*(c.y-b.y);}
area=-sum/2.0;}
return area;},getGeodesicArea:function(projection){var ring=this;if(projection){var gg=new OpenLayers.Projection("EPSG:4326");if(!gg.equals(projection)){ring=this.clone().transform(projection,gg);}}
var area=0.0;var len=ring.components&&ring.components.length;if(len>2){var p1,p2;for(var i=0;i<len-1;i++){p1=ring.components[i];p2=ring.components[i+1];area+=OpenLayers.Util.rad(p2.x-p1.x)*(2+Math.sin(OpenLayers.Util.rad(p1.y))+
Math.sin(OpenLayers.Util.rad(p2.y)));}
area=area*6378137.0*6378137.0/2.0;}
return area;},containsPoint:function(point){var approx=OpenLayers.Number.limitSigDigs;var digs=14;var px=approx(point.x,digs);var py=approx(point.y,digs);function getX(y,x1,y1,x2,y2){return(((x1-x2)*y)+((x2*y1)-(x1*y2)))/(y1-y2);}
var numSeg=this.components.length-1;var start,end,x1,y1,x2,y2,cx,cy;var crosses=0;for(var i=0;i<numSeg;++i){start=this.components[i];x1=approx(start.x,digs);y1=approx(start.y,digs);end=this.components[i+1];x2=approx(end.x,digs);y2=approx(end.y,digs);if(y1==y2){if(py==y1){if(x1<=x2&&(px>=x1&&px<=x2)||x1>=x2&&(px<=x1&&px>=x2)){crosses=-1;break;}}
continue;}
cx=approx(getX(py,x1,y1,x2,y2),digs);if(cx==px){if(y1<y2&&(py>=y1&&py<=y2)||y1>y2&&(py<=y1&&py>=y2)){crosses=-1;break;}}
if(cx<=px){continue;}
if(x1!=x2&&(cx<Math.min(x1,x2)||cx>Math.max(x1,x2))){continue;}
if(y1<y2&&(py>=y1&&py<y2)||y1>y2&&(py<y1&&py>=y2)){++crosses;}}
var contained=(crosses==-1)?1:!!(crosses&1);return contained;},intersects:function(geometry){var intersect=false;if(geometry.CLASS_NAME=="OpenLayers.Geometry.Point"){intersect=this.containsPoint(geometry);}else if(geometry.CLASS_NAME=="OpenLayers.Geometry.LineString"){intersect=geometry.intersects(this);}else if(geometry.CLASS_NAME=="OpenLayers.Geometry.LinearRing"){intersect=OpenLayers.Geometry.LineString.prototype.intersects.apply(this,[geometry]);}else{for(var i=0,len=geometry.components.length;i<len;++i){intersect=geometry.components[i].intersects(this);if(intersect){break;}}}
return intersect;},getVertices:function(nodes){return(nodes===true)?[]:this.components.slice(0,this.components.length-1);},CLASS_NAME:"OpenLayers.Geometry.LinearRing"});OpenLayers.Geometry.Polygon=OpenLayers.Class(OpenLayers.Geometry.Collection,{componentTypes:["OpenLayers.Geometry.LinearRing"],initialize:function(components){OpenLayers.Geometry.Collection.prototype.initialize.apply(this,arguments);},getArea:function(){var area=0.0;if(this.components&&(this.components.length>0)){area+=Math.abs(this.components[0].getArea());for(var i=1,len=this.components.length;i<len;i++){area-=Math.abs(this.components[i].getArea());}}
return area;},getGeodesicArea:function(projection){var area=0.0;if(this.components&&(this.components.length>0)){area+=Math.abs(this.components[0].getGeodesicArea(projection));for(var i=1,len=this.components.length;i<len;i++){area-=Math.abs(this.components[i].getGeodesicArea(projection));}}
return area;},containsPoint:function(point){var numRings=this.components.length;var contained=false;if(numRings>0){contained=this.components[0].containsPoint(point);if(contained!==1){if(contained&&numRings>1){var hole;for(var i=1;i<numRings;++i){hole=this.components[i].containsPoint(point);if(hole){if(hole===1){contained=1;}else{contained=false;}
break;}}}}}
return contained;},intersects:function(geometry){var intersect=false;var i,len;if(geometry.CLASS_NAME=="OpenLayers.Geometry.Point"){intersect=this.containsPoint(geometry);}else if(geometry.CLASS_NAME=="OpenLayers.Geometry.LineString"||geometry.CLASS_NAME=="OpenLayers.Geometry.LinearRing"){for(i=0,len=this.components.length;i<len;++i){intersect=geometry.intersects(this.components[i]);if(intersect){break;}}
if(!intersect){for(i=0,len=geometry.components.length;i<len;++i){intersect=this.containsPoint(geometry.components[i]);if(intersect){break;}}}}else{for(i=0,len=geometry.components.length;i<len;++i){intersect=this.intersects(geometry.components[i]);if(intersect){break;}}}
if(!intersect&&geometry.CLASS_NAME=="OpenLayers.Geometry.Polygon"){var ring=this.components[0];for(i=0,len=ring.components.length;i<len;++i){intersect=geometry.containsPoint(ring.components[i]);if(intersect){break;}}}
return intersect;},distanceTo:function(geometry,options){var edge=!(options&&options.edge===false);var result;if(!edge&&this.intersects(geometry)){result=0;}else{result=OpenLayers.Geometry.Collection.prototype.distanceTo.apply(this,[geometry,options]);}
return result;},CLASS_NAME:"OpenLayers.Geometry.Polygon"});OpenLayers.Geometry.Polygon.createRegularPolygon=function(origin,radius,sides,rotation){var angle=Math.PI*((1/sides)-(1/2));if(rotation){angle+=(rotation/180)*Math.PI;}
var rotatedAngle,x,y;var points=[];for(var i=0;i<sides;++i){rotatedAngle=angle+(i*2*Math.PI/sides);x=origin.x+(radius*Math.cos(rotatedAngle));y=origin.y+(radius*Math.sin(rotatedAngle));points.push(new OpenLayers.Geometry.Point(x,y));}
var ring=new OpenLayers.Geometry.LinearRing(points);return new OpenLayers.Geometry.Polygon([ring]);};OpenLayers.Renderer=OpenLayers.Class({container:null,root:null,extent:null,locked:false,size:null,resolution:null,map:null,initialize:function(containerID,options){this.container=OpenLayers.Util.getElement(containerID);},destroy:function(){this.container=null;this.extent=null;this.size=null;this.resolution=null;this.map=null;},supported:function(){return false;},setExtent:function(extent,resolutionChanged){this.extent=extent.clone();if(resolutionChanged){this.resolution=null;}},setSize:function(size){this.size=size.clone();this.resolution=null;},getResolution:function(){this.resolution=this.resolution||this.map.getResolution();return this.resolution;},drawFeature:function(feature,style){if(style==null){style=feature.style;}
if(feature.geometry){var bounds=feature.geometry.getBounds();if(bounds){if(!bounds.intersectsBounds(this.extent)){style={display:"none"};}
var rendered=this.drawGeometry(feature.geometry,style,feature.id);if(style.display!="none"&&style.label&&rendered!==false){this.drawText(feature.id,style,feature.geometry.getCentroid());}else{this.removeText(feature.id);}
return rendered;}}},drawGeometry:function(geometry,style,featureId){},drawText:function(featureId,style,location){},removeText:function(featureId){},clear:function(){},getFeatureIdFromEvent:function(evt){},eraseFeatures:function(features){if(!(features instanceof Array)){features=[features];}
for(var i=0,len=features.length;i<len;++i){this.eraseGeometry(features[i].geometry);this.removeText(features[i].id);}},eraseGeometry:function(geometry){},moveRoot:function(renderer){},getRenderLayerId:function(){return this.container.id;},CLASS_NAME:"OpenLayers.Renderer"});OpenLayers.ElementsIndexer=OpenLayers.Class({maxZIndex:null,order:null,indices:null,compare:null,initialize:function(yOrdering){this.compare=yOrdering?OpenLayers.ElementsIndexer.IndexingMethods.Z_ORDER_Y_ORDER:OpenLayers.ElementsIndexer.IndexingMethods.Z_ORDER_DRAWING_ORDER;this.order=[];this.indices={};this.maxZIndex=0;},insert:function(newNode){if(this.exists(newNode)){this.remove(newNode);}
var nodeId=newNode.id;this.determineZIndex(newNode);var leftIndex=-1;var rightIndex=this.order.length;var middle;while(rightIndex-leftIndex>1){middle=parseInt((leftIndex+rightIndex)/2);var placement=this.compare(this,newNode,OpenLayers.Util.getElement(this.order[middle]));if(placement>0){leftIndex=middle;}else{rightIndex=middle;}}
this.order.splice(rightIndex,0,nodeId);this.indices[nodeId]=this.getZIndex(newNode);return this.getNextElement(rightIndex);},remove:function(node){var nodeId=node.id;var arrayIndex=OpenLayers.Util.indexOf(this.order,nodeId);if(arrayIndex>=0){this.order.splice(arrayIndex,1);delete this.indices[nodeId];if(this.order.length>0){var lastId=this.order[this.order.length-1];this.maxZIndex=this.indices[lastId];}else{this.maxZIndex=0;}}},clear:function(){this.order=[];this.indices={};this.maxZIndex=0;},exists:function(node){return(this.indices[node.id]!=null);},getZIndex:function(node){return node._style.graphicZIndex;},determineZIndex:function(node){var zIndex=node._style.graphicZIndex;if(zIndex==null){zIndex=this.maxZIndex;node._style.graphicZIndex=zIndex;}else if(zIndex>this.maxZIndex){this.maxZIndex=zIndex;}},getNextElement:function(index){var nextIndex=index+1;if(nextIndex<this.order.length){var nextElement=OpenLayers.Util.getElement(this.order[nextIndex]);if(nextElement==undefined){nextElement=this.getNextElement(nextIndex);}
return nextElement;}else{return null;}},CLASS_NAME:"OpenLayers.ElementsIndexer"});OpenLayers.ElementsIndexer.IndexingMethods={Z_ORDER:function(indexer,newNode,nextNode){var newZIndex=indexer.getZIndex(newNode);var returnVal=0;if(nextNode){var nextZIndex=indexer.getZIndex(nextNode);returnVal=newZIndex-nextZIndex;}
return returnVal;},Z_ORDER_DRAWING_ORDER:function(indexer,newNode,nextNode){var returnVal=OpenLayers.ElementsIndexer.IndexingMethods.Z_ORDER(indexer,newNode,nextNode);if(nextNode&&returnVal==0){returnVal=1;}
return returnVal;},Z_ORDER_Y_ORDER:function(indexer,newNode,nextNode){var returnVal=OpenLayers.ElementsIndexer.IndexingMethods.Z_ORDER(indexer,newNode,nextNode);if(nextNode&&returnVal==0){var newLat=newNode._geometry.getBounds().bottom;var nextLat=nextNode._geometry.getBounds().bottom;var result=nextLat-newLat;returnVal=(result==0)?1:result;}
return returnVal;}};OpenLayers.Renderer.Elements=OpenLayers.Class(OpenLayers.Renderer,{rendererRoot:null,root:null,vectorRoot:null,textRoot:null,xmlns:null,indexer:null,BACKGROUND_ID_SUFFIX:"_background",LABEL_ID_SUFFIX:"_label",minimumSymbolizer:{strokeLinecap:"round",strokeOpacity:1,strokeDashstyle:"solid",fillOpacity:1,pointRadius:0},initialize:function(containerID,options){OpenLayers.Renderer.prototype.initialize.apply(this,arguments);this.rendererRoot=this.createRenderRoot();this.root=this.createRoot("_root");this.vectorRoot=this.createRoot("_vroot");this.textRoot=this.createRoot("_troot");this.root.appendChild(this.vectorRoot);this.root.appendChild(this.textRoot);this.rendererRoot.appendChild(this.root);this.container.appendChild(this.rendererRoot);if(options&&(options.zIndexing||options.yOrdering)){this.indexer=new OpenLayers.ElementsIndexer(options.yOrdering);}},destroy:function(){this.clear();this.rendererRoot=null;this.root=null;this.xmlns=null;OpenLayers.Renderer.prototype.destroy.apply(this,arguments);},clear:function(){if(this.vectorRoot){while(this.vectorRoot.childNodes.length>0){this.vectorRoot.removeChild(this.vectorRoot.firstChild);}}
if(this.textRoot){while(this.textRoot.childNodes.length>0){this.textRoot.removeChild(this.textRoot.firstChild);}}
if(this.indexer){this.indexer.clear();}},getNodeType:function(geometry,style){},drawGeometry:function(geometry,style,featureId){var className=geometry.CLASS_NAME;var rendered=true;if((className=="OpenLayers.Geometry.Collection")||(className=="OpenLayers.Geometry.MultiPoint")||(className=="OpenLayers.Geometry.MultiLineString")||(className=="OpenLayers.Geometry.MultiPolygon")){for(var i=0,len=geometry.components.length;i<len;i++){rendered=this.drawGeometry(geometry.components[i],style,featureId)&&rendered;}
return rendered;};rendered=false;if(style.display!="none"){if(style.backgroundGraphic){this.redrawBackgroundNode(geometry.id,geometry,style,featureId);}
rendered=this.redrawNode(geometry.id,geometry,style,featureId);}
if(rendered==false){var node=document.getElementById(geometry.id);if(node){if(node._style.backgroundGraphic){node.parentNode.removeChild(document.getElementById(geometry.id+this.BACKGROUND_ID_SUFFIX));}
node.parentNode.removeChild(node);}}
return rendered;},redrawNode:function(id,geometry,style,featureId){var node=this.nodeFactory(id,this.getNodeType(geometry,style));node._featureId=featureId;node._geometry=geometry;node._geometryClass=geometry.CLASS_NAME;node._style=style;var drawResult=this.drawGeometryNode(node,geometry,style);if(drawResult===false){return false;}
node=drawResult.node;if(this.indexer){var insert=this.indexer.insert(node);if(insert){this.vectorRoot.insertBefore(node,insert);}else{this.vectorRoot.appendChild(node);}}else{if(node.parentNode!==this.vectorRoot){this.vectorRoot.appendChild(node);}}
this.postDraw(node);return drawResult.complete;},redrawBackgroundNode:function(id,geometry,style,featureId){var backgroundStyle=OpenLayers.Util.extend({},style);backgroundStyle.externalGraphic=backgroundStyle.backgroundGraphic;backgroundStyle.graphicXOffset=backgroundStyle.backgroundXOffset;backgroundStyle.graphicYOffset=backgroundStyle.backgroundYOffset;backgroundStyle.graphicZIndex=backgroundStyle.backgroundGraphicZIndex;backgroundStyle.graphicWidth=backgroundStyle.backgroundWidth||backgroundStyle.graphicWidth;backgroundStyle.graphicHeight=backgroundStyle.backgroundHeight||backgroundStyle.graphicHeight;backgroundStyle.backgroundGraphic=null;backgroundStyle.backgroundXOffset=null;backgroundStyle.backgroundYOffset=null;backgroundStyle.backgroundGraphicZIndex=null;return this.redrawNode(id+this.BACKGROUND_ID_SUFFIX,geometry,backgroundStyle,null);},drawGeometryNode:function(node,geometry,style){style=style||node._style;OpenLayers.Util.applyDefaults(style,this.minimumSymbolizer);var options={'isFilled':style.fill===undefined?true:style.fill,'isStroked':style.stroke===undefined?!!style.strokeWidth:style.stroke};var drawn;switch(geometry.CLASS_NAME){case"OpenLayers.Geometry.Point":if(style.graphic===false){options.isFilled=false;options.isStroked=false;}
drawn=this.drawPoint(node,geometry);break;case"OpenLayers.Geometry.LineString":options.isFilled=false;drawn=this.drawLineString(node,geometry);break;case"OpenLayers.Geometry.LinearRing":drawn=this.drawLinearRing(node,geometry);break;case"OpenLayers.Geometry.Polygon":drawn=this.drawPolygon(node,geometry);break;case"OpenLayers.Geometry.Surface":drawn=this.drawSurface(node,geometry);break;case"OpenLayers.Geometry.Rectangle":drawn=this.drawRectangle(node,geometry);break;default:break;}
node._style=style;node._options=options;if(drawn!=false){return{node:this.setStyle(node,style,options,geometry),complete:drawn};}else{return false;}},postDraw:function(node){},drawPoint:function(node,geometry){},drawLineString:function(node,geometry){},drawLinearRing:function(node,geometry){},drawPolygon:function(node,geometry){},drawRectangle:function(node,geometry){},drawCircle:function(node,geometry){},drawSurface:function(node,geometry){},removeText:function(featureId){var label=document.getElementById(featureId+this.LABEL_ID_SUFFIX);if(label){this.textRoot.removeChild(label);}},getFeatureIdFromEvent:function(evt){var target=evt.target;var useElement=target&&target.correspondingUseElement;var node=useElement?useElement:(target||evt.srcElement);var featureId=node._featureId;return featureId;},eraseGeometry:function(geometry){if((geometry.CLASS_NAME=="OpenLayers.Geometry.MultiPoint")||(geometry.CLASS_NAME=="OpenLayers.Geometry.MultiLineString")||(geometry.CLASS_NAME=="OpenLayers.Geometry.MultiPolygon")||(geometry.CLASS_NAME=="OpenLayers.Geometry.Collection")){for(var i=0,len=geometry.components.length;i<len;i++){this.eraseGeometry(geometry.components[i]);}}else{var element=OpenLayers.Util.getElement(geometry.id);if(element&&element.parentNode){if(element.geometry){element.geometry.destroy();element.geometry=null;}
element.parentNode.removeChild(element);if(this.indexer){this.indexer.remove(element);}
if(element._style.backgroundGraphic){var backgroundId=geometry.id+this.BACKGROUND_ID_SUFFIX;var bElem=OpenLayers.Util.getElement(backgroundId);if(bElem&&bElem.parentNode){bElem.parentNode.removeChild(bElem);}}}}},nodeFactory:function(id,type){var node=OpenLayers.Util.getElement(id);if(node){if(!this.nodeTypeCompare(node,type)){node.parentNode.removeChild(node);node=this.nodeFactory(id,type);}}else{node=this.createNode(type,id);}
return node;},nodeTypeCompare:function(node,type){},createNode:function(type,id){},moveRoot:function(renderer){var root=this.root;if(renderer.root.parentNode==this.rendererRoot){root=renderer.root;}
root.parentNode.removeChild(root);renderer.rendererRoot.appendChild(root);},getRenderLayerId:function(){return this.root.parentNode.parentNode.id;},isComplexSymbol:function(graphicName){return(graphicName!="circle")&&!!graphicName;},CLASS_NAME:"OpenLayers.Renderer.Elements"});OpenLayers.Renderer.symbol={"star":[350,75,379,161,469,161,397,215,423,301,350,250,277,301,303,215,231,161,321,161,350,75],"cross":[4,0,6,0,6,4,10,4,10,6,6,6,6,10,4,10,4,6,0,6,0,4,4,4,4,0],"x":[0,0,25,0,50,35,75,0,100,0,65,50,100,100,75,100,50,65,25,100,0,100,35,50,0,0],"square":[0,0,0,1,1,1,1,0,0,0],"triangle":[0,10,10,10,5,0,0,10]};OpenLayers.Renderer.SVG=OpenLayers.Class(OpenLayers.Renderer.Elements,{xmlns:"http://www.w3.org/2000/svg",xlinkns:"http://www.w3.org/1999/xlink",MAX_PIXEL:15000,translationParameters:null,symbolSize:{},isGecko:null,initialize:function(containerID){if(!this.supported()){return;}
OpenLayers.Renderer.Elements.prototype.initialize.apply(this,arguments);this.translationParameters={x:0,y:0};this.isGecko=(navigator.userAgent.toLowerCase().indexOf("gecko/")!=-1);},destroy:function(){OpenLayers.Renderer.Elements.prototype.destroy.apply(this,arguments);},supported:function(){var svgFeature="http://www.w3.org/TR/SVG11/feature#";return(document.implementation&&(document.implementation.hasFeature("org.w3c.svg","1.0")||document.implementation.hasFeature(svgFeature+"SVG","1.1")||document.implementation.hasFeature(svgFeature+"BasicStructure","1.1")));},inValidRange:function(x,y,xyOnly){var left=x+(xyOnly?0:this.translationParameters.x);var top=y+(xyOnly?0:this.translationParameters.y);return(left>=-this.MAX_PIXEL&&left<=this.MAX_PIXEL&&top>=-this.MAX_PIXEL&&top<=this.MAX_PIXEL);},setExtent:function(extent,resolutionChanged){OpenLayers.Renderer.Elements.prototype.setExtent.apply(this,arguments);var resolution=this.getResolution();var left=-extent.left/resolution;var top=extent.top/resolution;if(resolutionChanged){this.left=left;this.top=top;var extentString="0 0 "+this.size.w+" "+this.size.h;this.rendererRoot.setAttributeNS(null,"viewBox",extentString);this.translate(0,0);return true;}else{var inRange=this.translate(left-this.left,top-this.top);if(!inRange){this.setExtent(extent,true);}
return inRange;}},translate:function(x,y){if(!this.inValidRange(x,y,true)){return false;}else{var transformString="";if(x||y){transformString="translate("+x+","+y+")";}
this.root.setAttributeNS(null,"transform",transformString);this.translationParameters={x:x,y:y};return true;}},setSize:function(size){OpenLayers.Renderer.prototype.setSize.apply(this,arguments);this.rendererRoot.setAttributeNS(null,"width",this.size.w);this.rendererRoot.setAttributeNS(null,"height",this.size.h);},getNodeType:function(geometry,style){var nodeType=null;switch(geometry.CLASS_NAME){case"OpenLayers.Geometry.Point":if(style.externalGraphic){nodeType="image";}else if(this.isComplexSymbol(style.graphicName)){nodeType="use";}else{nodeType="circle";}
break;case"OpenLayers.Geometry.Rectangle":nodeType="rect";break;case"OpenLayers.Geometry.LineString":nodeType="polyline";break;case"OpenLayers.Geometry.LinearRing":nodeType="polygon";break;case"OpenLayers.Geometry.Polygon":case"OpenLayers.Geometry.Curve":case"OpenLayers.Geometry.Surface":nodeType="path";break;default:break;}
return nodeType;},setStyle:function(node,style,options){style=style||node._style;options=options||node._options;var r=parseFloat(node.getAttributeNS(null,"r"));var widthFactor=1;var pos;if(node._geometryClass=="OpenLayers.Geometry.Point"&&r){node.style.visibility="";if(style.graphic===false){node.style.visibility="hidden";}else if(style.externalGraphic){pos=this.getPosition(node);if(style.graphicTitle){node.setAttributeNS(null,"title",style.graphicTitle);}
if(style.graphicWidth&&style.graphicHeight){node.setAttributeNS(null,"preserveAspectRatio","none");}
var width=style.graphicWidth||style.graphicHeight;var height=style.graphicHeight||style.graphicWidth;width=width?width:style.pointRadius*2;height=height?height:style.pointRadius*2;var xOffset=(style.graphicXOffset!=undefined)?style.graphicXOffset:-(0.5*width);var yOffset=(style.graphicYOffset!=undefined)?style.graphicYOffset:-(0.5*height);var opacity=style.graphicOpacity||style.fillOpacity;node.setAttributeNS(null,"x",(pos.x+xOffset).toFixed());node.setAttributeNS(null,"y",(pos.y+yOffset).toFixed());node.setAttributeNS(null,"width",width);node.setAttributeNS(null,"height",height);node.setAttributeNS(this.xlinkns,"href",style.externalGraphic);node.setAttributeNS(null,"style","opacity: "+opacity);}else if(this.isComplexSymbol(style.graphicName)){var offset=style.pointRadius*3;var size=offset*2;var id=this.importSymbol(style.graphicName);var href="#"+id;pos=this.getPosition(node);widthFactor=this.symbolSize[id]/size;var parent=node.parentNode;var nextSibling=node.nextSibling;if(parent){parent.removeChild(node);}
node.setAttributeNS(this.xlinkns,"href",href);node.setAttributeNS(null,"width",size);node.setAttributeNS(null,"height",size);node.setAttributeNS(null,"x",pos.x-offset);node.setAttributeNS(null,"y",pos.y-offset);if(nextSibling){parent.insertBefore(node,nextSibling);}else if(parent){parent.appendChild(node);}}else{node.setAttributeNS(null,"r",style.pointRadius);}
if(typeof style.rotation!="undefined"&&pos){var rotation=OpenLayers.String.format("rotate(${0} ${1} ${2})",[style.rotation,pos.x,pos.y]);node.setAttributeNS(null,"transform",rotation);}}
if(options.isFilled){node.setAttributeNS(null,"fill",style.fillColor);node.setAttributeNS(null,"fill-opacity",style.fillOpacity);}else{node.setAttributeNS(null,"fill","none");}
if(options.isStroked){node.setAttributeNS(null,"stroke",style.strokeColor);node.setAttributeNS(null,"stroke-opacity",style.strokeOpacity);node.setAttributeNS(null,"stroke-width",style.strokeWidth*widthFactor);node.setAttributeNS(null,"stroke-linecap",style.strokeLinecap);node.setAttributeNS(null,"stroke-linejoin","round");node.setAttributeNS(null,"stroke-dasharray",this.dashStyle(style,widthFactor));}else{node.setAttributeNS(null,"stroke","none");}
if(style.pointerEvents){node.setAttributeNS(null,"pointer-events",style.pointerEvents);}
if(style.cursor!=null){node.setAttributeNS(null,"cursor",style.cursor);}
return node;},dashStyle:function(style,widthFactor){var w=style.strokeWidth*widthFactor;switch(style.strokeDashstyle){case'solid':return'none';case'dot':return[1,4*w].join();case'dash':return[4*w,4*w].join();case'dashdot':return[4*w,4*w,1,4*w].join();case'longdash':return[8*w,4*w].join();case'longdashdot':return[8*w,4*w,1,4*w].join();default:return style.strokeDashstyle.replace(/ /g,",");}},createNode:function(type,id){var node=document.createElementNS(this.xmlns,type);if(id){node.setAttributeNS(null,"id",id);}
return node;},nodeTypeCompare:function(node,type){return(type==node.nodeName);},createRenderRoot:function(){return this.nodeFactory(this.container.id+"_svgRoot","svg");},createRoot:function(suffix){return this.nodeFactory(this.container.id+suffix,"g");},createDefs:function(){var defs=this.nodeFactory(this.container.id+"_defs","defs");this.rendererRoot.appendChild(defs);return defs;},drawPoint:function(node,geometry){return this.drawCircle(node,geometry,1);},drawCircle:function(node,geometry,radius){var resolution=this.getResolution();var x=(geometry.x/resolution+this.left);var y=(this.top-geometry.y/resolution);if(this.inValidRange(x,y)){node.setAttributeNS(null,"cx",x);node.setAttributeNS(null,"cy",y);node.setAttributeNS(null,"r",radius);return node;}else{return false;}},drawLineString:function(node,geometry){var componentsResult=this.getComponentsString(geometry.components);if(componentsResult.path){node.setAttributeNS(null,"points",componentsResult.path);return(componentsResult.complete?node:null);}else{return false;}},drawLinearRing:function(node,geometry){var componentsResult=this.getComponentsString(geometry.components);if(componentsResult.path){node.setAttributeNS(null,"points",componentsResult.path);return(componentsResult.complete?node:null);}else{return false;}},drawPolygon:function(node,geometry){var d="";var draw=true;var complete=true;var linearRingResult,path;for(var j=0,len=geometry.components.length;j<len;j++){d+=" M";linearRingResult=this.getComponentsString(geometry.components[j].components," ");path=linearRingResult.path;if(path){d+=" "+path;complete=linearRingResult.complete&&complete;}else{draw=false;}}
d+=" z";if(draw){node.setAttributeNS(null,"d",d);node.setAttributeNS(null,"fill-rule","evenodd");return complete?node:null;}else{return false;}},drawRectangle:function(node,geometry){var resolution=this.getResolution();var x=(geometry.x/resolution+this.left);var y=(this.top-geometry.y/resolution);if(this.inValidRange(x,y)){node.setAttributeNS(null,"x",x);node.setAttributeNS(null,"y",y);node.setAttributeNS(null,"width",geometry.width/resolution);node.setAttributeNS(null,"height",geometry.height/resolution);return node;}else{return false;}},drawSurface:function(node,geometry){var d=null;var draw=true;for(var i=0,len=geometry.components.length;i<len;i++){if((i%3)==0&&(i/3)==0){var component=this.getShortString(geometry.components[i]);if(!component){draw=false;}
d="M "+component;}else if((i%3)==1){var component=this.getShortString(geometry.components[i]);if(!component){draw=false;}
d+=" C "+component;}else{var component=this.getShortString(geometry.components[i]);if(!component){draw=false;}
d+=" "+component;}}
d+=" Z";if(draw){node.setAttributeNS(null,"d",d);return node;}else{return false;}},drawText:function(featureId,style,location){var resolution=this.getResolution();var x=(location.x/resolution+this.left);var y=(location.y/resolution-this.top);var label=this.nodeFactory(featureId+this.LABEL_ID_SUFFIX,"text");var tspan=this.nodeFactory(featureId+this.LABEL_ID_SUFFIX+"_tspan","tspan");label.setAttributeNS(null,"x",x);label.setAttributeNS(null,"y",-y);label.setAttributeNS(null,"pointer-events","none");if(style.fontColor){label.setAttributeNS(null,"fill",style.fontColor);}
if(style.fontFamily){label.setAttributeNS(null,"font-family",style.fontFamily);}
if(style.fontSize){label.setAttributeNS(null,"font-size",style.fontSize);}
if(style.fontWeight){label.setAttributeNS(null,"font-weight",style.fontWeight);}
var align=style.labelAlign||"cm";label.setAttributeNS(null,"text-anchor",OpenLayers.Renderer.SVG.LABEL_ALIGN[align[0]]||"middle");if(this.isGecko){label.setAttributeNS(null,"dominant-baseline",OpenLayers.Renderer.SVG.LABEL_ALIGN[align[1]]||"central");}else{tspan.setAttributeNS(null,"baseline-shift",OpenLayers.Renderer.SVG.LABEL_VSHIFT[align[1]]||"-35%");}
tspan.textContent=style.label;if(!label.parentNode){label.appendChild(tspan);this.textRoot.appendChild(label);}},getComponentsString:function(components,separator){var renderCmp=[];var complete=true;var len=components.length;var strings=[];var str,component,j;for(var i=0;i<len;i++){component=components[i];renderCmp.push(component);str=this.getShortString(component);if(str){strings.push(str);}else{if(i>0){if(this.getShortString(components[i-1])){strings.push(this.clipLine(components[i],components[i-1]));}}
if(i<len-1){if(this.getShortString(components[i+1])){strings.push(this.clipLine(components[i],components[i+1]));}}
complete=false;}}
return{path:strings.join(separator||","),complete:complete};},clipLine:function(badComponent,goodComponent){if(goodComponent.equals(badComponent)){return"";}
var resolution=this.getResolution();var maxX=this.MAX_PIXEL-this.translationParameters.x;var maxY=this.MAX_PIXEL-this.translationParameters.y;var x1=goodComponent.x/resolution+this.left;var y1=this.top-goodComponent.y/resolution;var x2=badComponent.x/resolution+this.left;var y2=this.top-badComponent.y/resolution;var k;if(x2<-maxX||x2>maxX){k=(y2-y1)/(x2-x1);x2=x2<0?-maxX:maxX;y2=y1+(x2-x1)*k;}
if(y2<-maxY||y2>maxY){k=(x2-x1)/(y2-y1);y2=y2<0?-maxY:maxY;x2=x1+(y2-y1)*k;}
return x2+","+y2;},getShortString:function(point){var resolution=this.getResolution();var x=(point.x/resolution+this.left);var y=(this.top-point.y/resolution);if(this.inValidRange(x,y)){return x+","+y;}else{return false;}},getPosition:function(node){return({x:parseFloat(node.getAttributeNS(null,"cx")),y:parseFloat(node.getAttributeNS(null,"cy"))});},importSymbol:function(graphicName){if(!this.defs){this.defs=this.createDefs();}
var id=this.container.id+"-"+graphicName;if(document.getElementById(id)!=null){return id;}
var symbol=OpenLayers.Renderer.symbol[graphicName];if(!symbol){throw new Error(graphicName+' is not a valid symbol name');return;}
var symbolNode=this.nodeFactory(id,"symbol");var node=this.nodeFactory(null,"polygon");symbolNode.appendChild(node);var symbolExtent=new OpenLayers.Bounds(Number.MAX_VALUE,Number.MAX_VALUE,0,0);var points="";var x,y;for(var i=0;i<symbol.length;i=i+2){x=symbol[i];y=symbol[i+1];symbolExtent.left=Math.min(symbolExtent.left,x);symbolExtent.bottom=Math.min(symbolExtent.bottom,y);symbolExtent.right=Math.max(symbolExtent.right,x);symbolExtent.top=Math.max(symbolExtent.top,y);points+=" "+x+","+y;}
node.setAttributeNS(null,"points",points);var width=symbolExtent.getWidth();var height=symbolExtent.getHeight();var viewBox=[symbolExtent.left-width,symbolExtent.bottom-height,width*3,height*3];symbolNode.setAttributeNS(null,"viewBox",viewBox.join(" "));this.symbolSize[id]=Math.max(width,height)*3;this.defs.appendChild(symbolNode);return symbolNode.id;},CLASS_NAME:"OpenLayers.Renderer.SVG"});OpenLayers.Renderer.SVG.LABEL_ALIGN={"l":"start","r":"end","b":"bottom","t":"hanging"};OpenLayers.Renderer.SVG.LABEL_VSHIFT={"t":"-70%","b":"0"};OpenLayers.Renderer.Canvas=OpenLayers.Class(OpenLayers.Renderer,{canvas:null,features:null,geometryMap:null,initialize:function(containerID){OpenLayers.Renderer.prototype.initialize.apply(this,arguments);this.root=document.createElement("canvas");this.container.appendChild(this.root);this.canvas=this.root.getContext("2d");this.features={};this.geometryMap={};},eraseGeometry:function(geometry){this.eraseFeatures(this.features[this.geometryMap[geometry.id]][0]);},supported:function(){var canvas=document.createElement("canvas");return!!canvas.getContext;},setExtent:function(extent){this.extent=extent.clone();this.resolution=null;this.redraw();},setSize:function(size){this.size=size.clone();this.root.style.width=size.w+"px";this.root.style.height=size.h+"px";this.root.width=size.w;this.root.height=size.h;this.resolution=null;},drawFeature:function(feature,style){if(style==null){style=feature.style;}
style=OpenLayers.Util.extend({'fillColor':'#000000','strokeColor':'#000000','strokeWidth':2,'fillOpacity':1,'strokeOpacity':1},style);this.features[feature.id]=[feature,style];if(feature.geometry){this.geometryMap[feature.geometry.id]=feature.id;}
this.redraw();},drawGeometry:function(geometry,style){var className=geometry.CLASS_NAME;if((className=="OpenLayers.Geometry.Collection")||(className=="OpenLayers.Geometry.MultiPoint")||(className=="OpenLayers.Geometry.MultiLineString")||(className=="OpenLayers.Geometry.MultiPolygon")){for(var i=0;i<geometry.components.length;i++){this.drawGeometry(geometry.components[i],style);}
return;};switch(geometry.CLASS_NAME){case"OpenLayers.Geometry.Point":this.drawPoint(geometry,style);break;case"OpenLayers.Geometry.LineString":this.drawLineString(geometry,style);break;case"OpenLayers.Geometry.LinearRing":this.drawLinearRing(geometry,style);break;case"OpenLayers.Geometry.Polygon":this.drawPolygon(geometry,style);break;default:break;}},drawExternalGraphic:function(pt,style){var img=new Image();img.src=style.externalGraphic;if(style.graphicTitle){img.title=style.graphicTitle;}
var width=style.graphicWidth||style.graphicHeight;var height=style.graphicHeight||style.graphicWidth;width=width?width:style.pointRadius*2;height=height?height:style.pointRadius*2;var xOffset=(style.graphicXOffset!=undefined)?style.graphicXOffset:-(0.5*width);var yOffset=(style.graphicYOffset!=undefined)?style.graphicYOffset:-(0.5*height);var opacity=style.graphicOpacity||style.fillOpacity;var context={img:img,x:(pt[0]+xOffset),y:(pt[1]+yOffset),width:width,height:height,canvas:this.canvas};img.onload=OpenLayers.Function.bind(function(){this.canvas.drawImage(this.img,this.x,this.y,this.width,this.height);},context);},setCanvasStyle:function(type,style){if(type=="fill"){this.canvas.globalAlpha=style['fillOpacity'];this.canvas.fillStyle=style['fillColor'];}else if(type=="stroke"){this.canvas.globalAlpha=style['strokeOpacity'];this.canvas.strokeStyle=style['strokeColor'];this.canvas.lineWidth=style['strokeWidth'];}else{this.canvas.globalAlpha=0;this.canvas.lineWidth=1;}},drawPoint:function(geometry,style){if(style.graphic!==false){var pt=this.getLocalXY(geometry);if(style.externalGraphic){this.drawExternalGraphic(pt,style);}else{if(style.fill!==false){this.setCanvasStyle("fill",style);this.canvas.beginPath();this.canvas.arc(pt[0],pt[1],6,0,Math.PI*2,true);this.canvas.fill();}
if(style.stroke!==false){this.setCanvasStyle("stroke",style);this.canvas.beginPath();this.canvas.arc(pt[0],pt[1],6,0,Math.PI*2,true);this.canvas.stroke();this.setCanvasStyle("reset");}}}},drawLineString:function(geometry,style){if(style.stroke!==false){this.setCanvasStyle("stroke",style);this.canvas.beginPath();var start=this.getLocalXY(geometry.components[0]);this.canvas.moveTo(start[0],start[1]);for(var i=1;i<geometry.components.length;i++){var pt=this.getLocalXY(geometry.components[i]);this.canvas.lineTo(pt[0],pt[1]);}
this.canvas.stroke();}
this.setCanvasStyle("reset");},drawLinearRing:function(geometry,style){if(style.fill!==false){this.setCanvasStyle("fill",style);this.canvas.beginPath();var start=this.getLocalXY(geometry.components[0]);this.canvas.moveTo(start[0],start[1]);for(var i=1;i<geometry.components.length-1;i++){var pt=this.getLocalXY(geometry.components[i]);this.canvas.lineTo(pt[0],pt[1]);}
this.canvas.fill();}
if(style.stroke!==false){var oldWidth=this.canvas.lineWidth;this.setCanvasStyle("stroke",style);this.canvas.beginPath();var start=this.getLocalXY(geometry.components[0]);this.canvas.moveTo(start[0],start[1]);for(var i=1;i<geometry.components.length;i++){var pt=this.getLocalXY(geometry.components[i]);this.canvas.lineTo(pt[0],pt[1]);}
this.canvas.stroke();}
this.setCanvasStyle("reset");},drawPolygon:function(geometry,style){this.drawLinearRing(geometry.components[0],style);for(var i=1;i<geometry.components.length;i++){this.drawLinearRing(geometry.components[i],{fillOpacity:0,strokeWidth:0,strokeOpacity:0,strokeColor:'#000000',fillColor:'#000000'});}},drawText:function(location,style){style=OpenLayers.Util.extend({fontColor:"#000000",labelAlign:"cm"},style);var pt=this.getLocalXY(location);this.setCanvasStyle("reset");this.canvas.fillStyle=style.fontColor;this.canvas.globalAlpha=1;var fontStyle=style.fontWeight+" "+style.fontSize+" "+style.fontFamily;if(this.canvas.fillText){var labelAlign=OpenLayers.Renderer.Canvas.LABEL_ALIGN[style.labelAlign[0]]||"middle";this.canvas.font=fontStyle;this.canvas.textAlign=labelAlign;this.canvas.fillText(style.label,pt[0],pt[1]);}else if(this.canvas.mozDrawText){this.canvas.mozTextStyle=fontStyle;var len=this.canvas.mozMeasureText(style.label);switch(style.labelAlign[0]){case"l":break;case"r":pt[0]-=len;break;case"c":default:pt[0]-=len/2;}
this.canvas.translate(pt[0],pt[1]);this.canvas.mozDrawText(style.label);this.canvas.translate(-1*pt[0],-1*pt[1]);}
this.setCanvasStyle("reset");},getLocalXY:function(point){var resolution=this.getResolution();var extent=this.extent;var x=(point.x/resolution+(-extent.left/resolution));var y=((extent.top/resolution)-point.y/resolution);return[x,y];},clear:function(){this.canvas.clearRect(0,0,this.root.width,this.root.height);},getFeatureIdFromEvent:function(evt){var loc=this.map.getLonLatFromPixel(evt.xy);var resolution=this.getResolution();var bounds=new OpenLayers.Bounds(loc.lon-resolution*5,loc.lat-resolution*5,loc.lon+resolution*5,loc.lat+resolution*5);var geom=bounds.toGeometry();for(var feat in this.features){if(!this.features.hasOwnProperty(feat)){continue;}
if(this.features[feat][0].geometry.intersects(geom)){return feat;}}
return null;},eraseFeatures:function(features){if(!(features instanceof Array)){features=[features];}
for(var i=0;i<features.length;++i){delete this.features[features[i].id];}
this.redraw();},redraw:function(){if(!this.locked){this.clear();var labelMap=[];var feature,style;for(var id in this.features){if(!this.features.hasOwnProperty(id)){continue;}
feature=this.features[id][0];style=this.features[id][1];if(!feature.geometry){continue;}
this.drawGeometry(feature.geometry,style);if(style.label){labelMap.push([feature,style]);}}
var item;for(var i=0;len=labelMap.length,i<len;++i){item=labelMap[i];this.drawText(item[0].geometry.getCentroid(),item[1]);}}},CLASS_NAME:"OpenLayers.Renderer.Canvas"});OpenLayers.Renderer.Canvas.LABEL_ALIGN={"l":"left","r":"right"};OpenLayers.Renderer.VML=OpenLayers.Class(OpenLayers.Renderer.Elements,{xmlns:"urn:schemas-microsoft-com:vml",symbolCache:{},offset:null,initialize:function(containerID){if(!this.supported()){return;}
if(!document.namespaces.olv){document.namespaces.add("olv",this.xmlns);var style=document.createStyleSheet();var shapes=['shape','rect','oval','fill','stroke','imagedata','group','textbox'];for(var i=0,len=shapes.length;i<len;i++){style.addRule('olv\\:'+shapes[i],"behavior: url(#default#VML); "+"position: absolute; display: inline-block;");}}
OpenLayers.Renderer.Elements.prototype.initialize.apply(this,arguments);this.offset={x:0,y:0};},destroy:function(){OpenLayers.Renderer.Elements.prototype.destroy.apply(this,arguments);},supported:function(){return!!(document.namespaces);},setExtent:function(extent,resolutionChanged){OpenLayers.Renderer.Elements.prototype.setExtent.apply(this,arguments);var resolution=this.getResolution();var left=extent.left/resolution;var top=extent.top/resolution-this.size.h;if(resolutionChanged){this.offset={x:left,y:top};left=0;top=0;}else{left=left-this.offset.x;top=top-this.offset.y;}
var org=left+" "+top;this.root.coordorigin=org;var roots=[this.root,this.vectorRoot,this.textRoot];var root;for(var i=0,len=roots.length;i<len;++i){root=roots[i];var size=this.size.w+" "+this.size.h;root.coordsize=size;}
this.root.style.flip="y";return true;},setSize:function(size){OpenLayers.Renderer.prototype.setSize.apply(this,arguments);var roots=[this.rendererRoot,this.root,this.vectorRoot,this.textRoot];var w=this.size.w+"px";var h=this.size.h+"px";var root;for(var i=0,len=roots.length;i<len;++i){root=roots[i];root.style.width=w;root.style.height=h;}},getNodeType:function(geometry,style){var nodeType=null;switch(geometry.CLASS_NAME){case"OpenLayers.Geometry.Point":if(style.externalGraphic){nodeType="olv:rect";}else if(this.isComplexSymbol(style.graphicName)){nodeType="olv:shape";}else{nodeType="olv:oval";}
break;case"OpenLayers.Geometry.Rectangle":nodeType="olv:rect";break;case"OpenLayers.Geometry.LineString":case"OpenLayers.Geometry.LinearRing":case"OpenLayers.Geometry.Polygon":case"OpenLayers.Geometry.Curve":case"OpenLayers.Geometry.Surface":nodeType="olv:shape";break;default:break;}
return nodeType;},setStyle:function(node,style,options,geometry){style=style||node._style;options=options||node._options;var widthFactor=1;if(node._geometryClass=="OpenLayers.Geometry.Point"){if(style.externalGraphic){if(style.graphicTitle){node.title=style.graphicTitle;}
var width=style.graphicWidth||style.graphicHeight;var height=style.graphicHeight||style.graphicWidth;width=width?width:style.pointRadius*2;height=height?height:style.pointRadius*2;var resolution=this.getResolution();var xOffset=(style.graphicXOffset!=undefined)?style.graphicXOffset:-(0.5*width);var yOffset=(style.graphicYOffset!=undefined)?style.graphicYOffset:-(0.5*height);node.style.left=((geometry.x/resolution-this.offset.x)+xOffset).toFixed();node.style.top=((geometry.y/resolution-this.offset.y)-(yOffset+height)).toFixed();node.style.width=width+"px";node.style.height=height+"px";node.style.flip="y";style.fillColor="none";options.isStroked=false;}else if(this.isComplexSymbol(style.graphicName)){var cache=this.importSymbol(style.graphicName);node.path=cache.path;node.coordorigin=cache.left+","+cache.bottom;var size=cache.size;node.coordsize=size+","+size;this.drawCircle(node,geometry,style.pointRadius);node.style.flip="y";}else{this.drawCircle(node,geometry,style.pointRadius);}}
if(options.isFilled){node.fillcolor=style.fillColor;}else{node.filled="false";}
var fills=node.getElementsByTagName("fill");var fill=(fills.length==0)?null:fills[0];if(!options.isFilled){if(fill){node.removeChild(fill);}}else{if(!fill){fill=this.createNode('olv:fill',node.id+"_fill");}
fill.opacity=style.fillOpacity;if(node._geometryClass=="OpenLayers.Geometry.Point"&&style.externalGraphic){if(style.graphicOpacity){fill.opacity=style.graphicOpacity;}
fill.src=style.externalGraphic;fill.type="frame";if(!(style.graphicWidth&&style.graphicHeight)){fill.aspect="atmost";}}
if(fill.parentNode!=node){node.appendChild(fill);}}
if(typeof style.rotation!="undefined"){if(style.externalGraphic){this.graphicRotate(node,xOffset,yOffset);fill.opacity=0;}else{node.style.rotation=style.rotation;}}
if(options.isStroked){node.strokecolor=style.strokeColor;node.strokeweight=style.strokeWidth+"px";}else{node.stroked=false;}
var strokes=node.getElementsByTagName("stroke");var stroke=(strokes.length==0)?null:strokes[0];if(!options.isStroked){if(stroke){node.removeChild(stroke);}}else{if(!stroke){stroke=this.createNode('olv:stroke',node.id+"_stroke");node.appendChild(stroke);}
stroke.opacity=style.strokeOpacity;stroke.endcap=!style.strokeLinecap||style.strokeLinecap=='butt'?'flat':style.strokeLinecap;stroke.dashstyle=this.dashStyle(style);}
if(style.cursor!="inherit"&&style.cursor!=null){node.style.cursor=style.cursor;}
return node;},graphicRotate:function(node,xOffset,yOffset){var style=style||node._style;var options=node._options;var aspectRatio,size;if(!(style.graphicWidth&&style.graphicHeight)){var img=new Image();img.onreadystatechange=OpenLayers.Function.bind(function(){if(img.readyState=="complete"||img.readyState=="interactive"){aspectRatio=img.width/img.height;size=Math.max(style.pointRadius*2,style.graphicWidth||0,style.graphicHeight||0);xOffset=xOffset*aspectRatio;style.graphicWidth=size*aspectRatio;style.graphicHeight=size;this.graphicRotate(node,xOffset,yOffset);}},this);img.src=style.externalGraphic;return;}else{size=Math.max(style.graphicWidth,style.graphicHeight);aspectRatio=style.graphicWidth/style.graphicHeight;}
var width=Math.round(style.graphicWidth||size*aspectRatio);var height=Math.round(style.graphicHeight||size);node.style.width=width+"px";node.style.height=height+"px";var image=document.getElementById(node.id+"_image");if(!image){image=this.createNode("olv:imagedata",node.id+"_image");node.appendChild(image);}
image.style.width=width+"px";image.style.height=height+"px";image.src=style.externalGraphic;image.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader("+"src='', sizingMethod='scale')";var rotation=style.rotation*Math.PI/180;var sintheta=Math.sin(rotation);var costheta=Math.cos(rotation);var filter="progid:DXImageTransform.Microsoft.Matrix(M11="+costheta+",M12="+(-sintheta)+",M21="+sintheta+",M22="+costheta+",SizingMethod='auto expand')\n";var opacity=style.graphicOpacity||style.fillOpacity;if(opacity&&opacity!=1){filter+="progid:DXImageTransform.Microsoft.BasicImage(opacity="+
opacity+")\n";}
node.style.filter=filter;var centerPoint=new OpenLayers.Geometry.Point(-xOffset,-yOffset);var imgBox=new OpenLayers.Bounds(0,0,width,height).toGeometry();imgBox.rotate(style.rotation,centerPoint);var imgBounds=imgBox.getBounds();node.style.left=Math.round(parseInt(node.style.left)+imgBounds.left)+"px";node.style.top=Math.round(parseInt(node.style.top)-imgBounds.bottom)+"px";},postDraw:function(node){var fillColor=node._style.fillColor;var strokeColor=node._style.strokeColor;if(fillColor=="none"&&node.fillcolor!=fillColor){node.fillcolor=fillColor;}
if(strokeColor=="none"&&node.strokecolor!=strokeColor){node.strokecolor=strokeColor;}},setNodeDimension:function(node,geometry){var bbox=geometry.getBounds();if(bbox){var resolution=this.getResolution();var scaledBox=new OpenLayers.Bounds((bbox.left/resolution-this.offset.x).toFixed(),(bbox.bottom/resolution-this.offset.y).toFixed(),(bbox.right/resolution-this.offset.x).toFixed(),(bbox.top/resolution-this.offset.y).toFixed());node.style.left=scaledBox.left+"px";node.style.top=scaledBox.top+"px";node.style.width=scaledBox.getWidth()+"px";node.style.height=scaledBox.getHeight()+"px";node.coordorigin=scaledBox.left+" "+scaledBox.top;node.coordsize=scaledBox.getWidth()+" "+scaledBox.getHeight();}},dashStyle:function(style){var dash=style.strokeDashstyle;switch(dash){case'solid':case'dot':case'dash':case'dashdot':case'longdash':case'longdashdot':return dash;default:var parts=dash.split(/[ ,]/);if(parts.length==2){if(1*parts[0]>=2*parts[1]){return"longdash";}
return(parts[0]==1||parts[1]==1)?"dot":"dash";}else if(parts.length==4){return(1*parts[0]>=2*parts[1])?"longdashdot":"dashdot";}
return"solid";}},createNode:function(type,id){var node=document.createElement(type);if(id){node.id=id;}
node.unselectable='on';node.onselectstart=function(){return(false);};return node;},nodeTypeCompare:function(node,type){var subType=type;var splitIndex=subType.indexOf(":");if(splitIndex!=-1){subType=subType.substr(splitIndex+1);}
var nodeName=node.nodeName;splitIndex=nodeName.indexOf(":");if(splitIndex!=-1){nodeName=nodeName.substr(splitIndex+1);}
return(subType==nodeName);},createRenderRoot:function(){return this.nodeFactory(this.container.id+"_vmlRoot","div");},createRoot:function(suffix){return this.nodeFactory(this.container.id+suffix,"olv:group");},drawPoint:function(node,geometry){return this.drawCircle(node,geometry,1);},drawCircle:function(node,geometry,radius){if(!isNaN(geometry.x)&&!isNaN(geometry.y)){var resolution=this.getResolution();node.style.left=((geometry.x/resolution-this.offset.x).toFixed()-radius)+"px";node.style.top=((geometry.y/resolution-this.offset.y).toFixed()-radius)+"px";var diameter=radius*2;node.style.width=diameter+"px";node.style.height=diameter+"px";return node;}
return false;},drawLineString:function(node,geometry){return this.drawLine(node,geometry,false);},drawLinearRing:function(node,geometry){return this.drawLine(node,geometry,true);},drawLine:function(node,geometry,closeLine){this.setNodeDimension(node,geometry);var resolution=this.getResolution();var numComponents=geometry.components.length;var parts=new Array(numComponents);var comp,x,y;for(var i=0;i<numComponents;i++){comp=geometry.components[i];x=(comp.x/resolution-this.offset.x);y=(comp.y/resolution-this.offset.y);parts[i]=" "+x.toFixed()+","+y.toFixed()+" l ";}
var end=(closeLine)?" x e":" e";node.path="m"+parts.join("")+end;return node;},drawPolygon:function(node,geometry){this.setNodeDimension(node,geometry);var resolution=this.getResolution();var path=[];var linearRing,i,j,len,ilen,comp,x,y;for(j=0,len=geometry.components.length;j<len;j++){linearRing=geometry.components[j];path.push("m");for(i=0,ilen=linearRing.components.length;i<ilen;i++){comp=linearRing.components[i];x=comp.x/resolution-this.offset.x;y=comp.y/resolution-this.offset.y;path.push(" "+x.toFixed()+","+y.toFixed());if(i==0){path.push(" l");}}
path.push(" x ");}
path.push("e");node.path=path.join("");return node;},drawRectangle:function(node,geometry){var resolution=this.getResolution();node.style.left=(geometry.x/resolution-this.offset.x)+"px";node.style.top=(geometry.y/resolution-this.offset.y)+"px";node.style.width=geometry.width/resolution+"px";node.style.height=geometry.height/resolution+"px";return node;},drawText:function(featureId,style,location){var label=this.nodeFactory(featureId+this.LABEL_ID_SUFFIX,"olv:rect");var textbox=this.nodeFactory(featureId+this.LABEL_ID_SUFFIX+"_textbox","olv:textbox");var resolution=this.getResolution();label.style.left=(location.x/resolution-this.offset.x).toFixed()+"px";label.style.top=(location.y/resolution-this.offset.y).toFixed()+"px";label.style.flip="y";textbox.innerText=style.label;if(style.fillColor){textbox.style.color=style.fontColor;}
if(style.fontFamily){textbox.style.fontFamily=style.fontFamily;}
if(style.fontSize){textbox.style.fontSize=style.fontSize;}
if(style.fontWeight){textbox.style.fontWeight=style.fontWeight;}
textbox.style.whiteSpace="nowrap";textbox.inset="1px,0px,0px,0px";if(!label.parentNode){label.appendChild(textbox);this.textRoot.appendChild(label);}
var align=style.labelAlign||"cm";var xshift=textbox.clientWidth*(OpenLayers.Renderer.VML.LABEL_SHIFT[align.substr(0,1)]);var yshift=textbox.clientHeight*(OpenLayers.Renderer.VML.LABEL_SHIFT[align.substr(1,1)]);label.style.left=parseInt(label.style.left)-xshift-1+"px";label.style.top=parseInt(label.style.top)+yshift+"px";},drawSurface:function(node,geometry){this.setNodeDimension(node,geometry);var resolution=this.getResolution();var path=[];var comp,x,y;for(var i=0,len=geometry.components.length;i<len;i++){comp=geometry.components[i];x=comp.x/resolution-this.offset.x;y=comp.y/resolution-this.offset.y;if((i%3)==0&&(i/3)==0){path.push("m");}else if((i%3)==1){path.push(" c");}
path.push(" "+x+","+y);}
path.push(" x e");node.path=path.join("");return node;},moveRoot:function(renderer){var layer=this.map.getLayer(renderer.container.id);if(layer instanceof OpenLayers.Layer.Vector.RootContainer){layer=this.map.getLayer(this.container.id);}
layer&&layer.renderer.clear();OpenLayers.Renderer.Elements.prototype.moveRoot.apply(this,arguments);layer&&layer.redraw();},importSymbol:function(graphicName){var id=this.container.id+"-"+graphicName;var cache=this.symbolCache[id];if(cache){return cache;}
var symbol=OpenLayers.Renderer.symbol[graphicName];if(!symbol){throw new Error(graphicName+' is not a valid symbol name');return;}
var symbolExtent=new OpenLayers.Bounds(Number.MAX_VALUE,Number.MAX_VALUE,0,0);var pathitems=["m"];for(var i=0;i<symbol.length;i=i+2){x=symbol[i];y=symbol[i+1];symbolExtent.left=Math.min(symbolExtent.left,x);symbolExtent.bottom=Math.min(symbolExtent.bottom,y);symbolExtent.right=Math.max(symbolExtent.right,x);symbolExtent.top=Math.max(symbolExtent.top,y);pathitems.push(x);pathitems.push(y);if(i==0){pathitems.push("l");}}
pathitems.push("x e");var path=pathitems.join(" ");var diff=(symbolExtent.getWidth()-symbolExtent.getHeight())/2;if(diff>0){symbolExtent.bottom=symbolExtent.bottom-diff;symbolExtent.top=symbolExtent.top+diff;}else{symbolExtent.left=symbolExtent.left-diff;symbolExtent.right=symbolExtent.right+diff;}
cache={path:path,size:symbolExtent.getWidth(),left:symbolExtent.left,bottom:symbolExtent.bottom};this.symbolCache[id]=cache;return cache;},CLASS_NAME:"OpenLayers.Renderer.VML"});OpenLayers.Renderer.VML.LABEL_SHIFT={"l":0,"c":.5,"r":1,"t":0,"m":.5,"b":1};OpenLayers.Layer.Vector=OpenLayers.Class(OpenLayers.Layer,{EVENT_TYPES:["beforefeatureadded","beforefeaturesadded","featureadded","featuresadded","beforefeatureremoved","featureremoved","featuresremoved","beforefeatureselected","featureselected","featureunselected","beforefeaturemodified","featuremodified","afterfeaturemodified","vertexmodified","sketchstarted","sketchmodified","sketchcomplete","refresh"],isBaseLayer:false,isFixed:false,isVector:true,features:null,selectedFeatures:null,unrenderedFeatures:null,reportError:true,style:null,styleMap:null,strategies:null,protocol:null,renderers:['SVG','VML','Canvas'],renderer:null,rendererOptions:null,geometryType:null,drawn:false,initialize:function(name,options){this.EVENT_TYPES=OpenLayers.Layer.Vector.prototype.EVENT_TYPES.concat(OpenLayers.Layer.prototype.EVENT_TYPES);OpenLayers.Layer.prototype.initialize.apply(this,arguments);if(!this.renderer||!this.renderer.supported()){this.assignRenderer();}
if(!this.renderer||!this.renderer.supported()){this.renderer=null;this.displayError();}
if(!this.styleMap){this.styleMap=new OpenLayers.StyleMap();}
this.features=[];this.selectedFeatures=[];this.unrenderedFeatures={};if(this.strategies){for(var i=0,len=this.strategies.length;i<len;i++){this.strategies[i].setLayer(this);}}},destroy:function(){if(this.strategies){var strategy,i,len;for(i=0,len=this.strategies.length;i<len;i++){strategy=this.strategies[i];if(strategy.autoDestroy){strategy.destroy();}}
this.strategies=null;}
if(this.protocol){if(this.protocol.autoDestroy){this.protocol.destroy();}
this.protocol=null;}
this.destroyFeatures();this.features=null;this.selectedFeatures=null;this.unrenderedFeatures=null;if(this.renderer){this.renderer.destroy();}
this.renderer=null;this.geometryType=null;this.drawn=null;OpenLayers.Layer.prototype.destroy.apply(this,arguments);},refresh:function(obj){if(this.calculateInRange()&&this.visibility){this.events.triggerEvent("refresh",obj);}},assignRenderer:function(){for(var i=0,len=this.renderers.length;i<len;i++){var rendererClass=OpenLayers.Renderer[this.renderers[i]];if(rendererClass&&rendererClass.prototype.supported()){this.renderer=new rendererClass(this.div,this.rendererOptions);break;}}},displayError:function(){if(this.reportError){OpenLayers.Console.userError(OpenLayers.i18n("browserNotSupported",{'renderers':this.renderers.join("\n")}));}},setMap:function(map){OpenLayers.Layer.prototype.setMap.apply(this,arguments);if(!this.renderer){this.map.removeLayer(this);}else{this.renderer.map=this.map;this.renderer.setSize(this.map.getSize());}},afterAdd:function(){if(this.strategies){var strategy,i,len;for(i=0,len=this.strategies.length;i<len;i++){strategy=this.strategies[i];if(strategy.autoActivate){strategy.activate();}}}},removeMap:function(map){if(this.strategies){var strategy,i,len;for(i=0,len=this.strategies.length;i<len;i++){strategy=this.strategies[i];if(strategy.autoActivate){strategy.deactivate();}}}},onMapResize:function(){OpenLayers.Layer.prototype.onMapResize.apply(this,arguments);this.renderer.setSize(this.map.getSize());},moveTo:function(bounds,zoomChanged,dragging){OpenLayers.Layer.prototype.moveTo.apply(this,arguments);var coordSysUnchanged=true;if(!dragging){this.renderer.root.style.visibility="hidden";this.div.style.left=-parseInt(this.map.layerContainerDiv.style.left)+"px";this.div.style.top=-parseInt(this.map.layerContainerDiv.style.top)+"px";var extent=this.map.getExtent();coordSysUnchanged=this.renderer.setExtent(extent,zoomChanged);this.renderer.root.style.visibility="visible";if(navigator.userAgent.toLowerCase().indexOf("gecko")!=-1){this.div.scrollLeft=this.div.scrollLeft;}
if(!zoomChanged&&coordSysUnchanged){for(var i in this.unrenderedFeatures){var feature=this.unrenderedFeatures[i];this.drawFeature(feature);}}}
if(!this.drawn||zoomChanged||!coordSysUnchanged){this.drawn=true;var feature;for(var i=0,len=this.features.length;i<len;i++){this.renderer.locked=(i!==(len-1));feature=this.features[i];this.drawFeature(feature);}}},display:function(display){OpenLayers.Layer.prototype.display.apply(this,arguments);var currentDisplay=this.div.style.display;if(currentDisplay!=this.renderer.root.style.display){this.renderer.root.style.display=currentDisplay;}},addFeatures:function(features,options){if(!(features instanceof Array)){features=[features];}
var notify=!options||!options.silent;if(notify){var event={features:features};var ret=this.events.triggerEvent("beforefeaturesadded",event);if(ret===false){return;}
features=event.features;}
for(var i=0,len=features.length;i<len;i++){if(i!=(features.length-1)){this.renderer.locked=true;}else{this.renderer.locked=false;}
var feature=features[i];if(this.geometryType&&!(feature.geometry instanceof this.geometryType)){var throwStr=OpenLayers.i18n('componentShouldBe',{'geomType':this.geometryType.prototype.CLASS_NAME});throw throwStr;}
this.features.push(feature);feature.layer=this;if(!feature.style&&this.style){feature.style=OpenLayers.Util.extend({},this.style);}
if(notify){if(this.events.triggerEvent("beforefeatureadded",{feature:feature})===false){continue;};this.preFeatureInsert(feature);}
this.drawFeature(feature);if(notify){this.events.triggerEvent("featureadded",{feature:feature});this.onFeatureInsert(feature);}}
if(notify){this.events.triggerEvent("featuresadded",{features:features});}},removeFeatures:function(features,options){if(!features||features.length===0){return;}
if(!(features instanceof Array)){features=[features];}
if(features===this.features){features=features.slice();}
var notify=!options||!options.silent;for(var i=features.length-1;i>=0;i--){if(i!=0&&features[i-1].geometry){this.renderer.locked=true;}else{this.renderer.locked=false;}
var feature=features[i];delete this.unrenderedFeatures[feature.id];if(notify){this.events.triggerEvent("beforefeatureremoved",{feature:feature});}
this.features=OpenLayers.Util.removeItem(this.features,feature);feature.layer=null;if(feature.geometry){this.renderer.eraseFeatures(feature);}
if(OpenLayers.Util.indexOf(this.selectedFeatures,feature)!=-1){OpenLayers.Util.removeItem(this.selectedFeatures,feature);}
if(notify){this.events.triggerEvent("featureremoved",{feature:feature});}}
if(notify){this.events.triggerEvent("featuresremoved",{features:features});}},destroyFeatures:function(features,options){var all=(features==undefined);if(all){features=this.features;}
if(features){this.removeFeatures(features,options);for(var i=features.length-1;i>=0;i--){features[i].destroy();}}},drawFeature:function(feature,style){if(!this.drawn){return}
if(typeof style!="object"){if(!style&&feature.state===OpenLayers.State.DELETE){style="delete";}
var renderIntent=style||feature.renderIntent;style=feature.style||this.style;if(!style){style=this.styleMap.createSymbolizer(feature,renderIntent);}}
if(!this.renderer.drawFeature(feature,style)){this.unrenderedFeatures[feature.id]=feature;}else{delete this.unrenderedFeatures[feature.id];};},eraseFeatures:function(features){this.renderer.eraseFeatures(features);},getFeatureFromEvent:function(evt){if(!this.renderer){OpenLayers.Console.error(OpenLayers.i18n("getFeatureError"));return null;}
var featureId=this.renderer.getFeatureIdFromEvent(evt);return this.getFeatureById(featureId);},getFeatureById:function(featureId){var feature=null;for(var i=0,len=this.features.length;i<len;++i){if(this.features[i].id==featureId){feature=this.features[i];break;}}
return feature;},onFeatureInsert:function(feature){},preFeatureInsert:function(feature){},getDataExtent:function(){var maxExtent=null;if(this.features&&(this.features.length>0)){maxExtent=new OpenLayers.Bounds();for(var i=0,len=this.features.length;i<len;i++){maxExtent.extend(this.features[i].geometry.getBounds());}}
return maxExtent;},CLASS_NAME:"OpenLayers.Layer.Vector"});OpenLayers.Style=OpenLayers.Class({name:null,title:null,description:null,layerName:null,isDefault:false,rules:null,context:null,defaultStyle:null,defaultsPerSymbolizer:false,propertyStyles:null,initialize:function(style,options){OpenLayers.Util.extend(this,options);this.rules=[];if(options&&options.rules){this.addRules(options.rules);}
this.setDefaultStyle(style||OpenLayers.Feature.Vector.style["default"]);},destroy:function(){for(var i=0,len=this.rules.length;i<len;i++){this.rules[i].destroy();this.rules[i]=null;}
this.rules=null;this.defaultStyle=null;},createSymbolizer:function(feature){var style=this.defaultsPerSymbolizer?{}:this.createLiterals(OpenLayers.Util.extend({},this.defaultStyle),feature);var rules=this.rules;var rule,context;var elseRules=[];var appliedRules=false;for(var i=0,len=rules.length;i<len;i++){rule=rules[i];var applies=rule.evaluate(feature);if(applies){if(rule instanceof OpenLayers.Rule&&rule.elseFilter){elseRules.push(rule);}else{appliedRules=true;this.applySymbolizer(rule,style,feature);}}}
if(appliedRules==false&&elseRules.length>0){appliedRules=true;for(var i=0,len=elseRules.length;i<len;i++){this.applySymbolizer(elseRules[i],style,feature);}}
if(rules.length>0&&appliedRules==false){style.display="none";}
return style;},applySymbolizer:function(rule,style,feature){var symbolizerPrefix=feature.geometry?this.getSymbolizerPrefix(feature.geometry):OpenLayers.Style.SYMBOLIZER_PREFIXES[0];var symbolizer=rule.symbolizer[symbolizerPrefix]||rule.symbolizer;if(this.defaultsPerSymbolizer===true){var defaults=this.defaultStyle;OpenLayers.Util.applyDefaults(symbolizer,{pointRadius:defaults.pointRadius});if(symbolizer.stroke===true||symbolizer.graphic===true){OpenLayers.Util.applyDefaults(symbolizer,{strokeWidth:defaults.strokeWidth,strokeColor:defaults.strokeColor,strokeOpacity:defaults.strokeOpacity,strokeDashstyle:defaults.strokeDashstyle,strokeLinecap:defaults.strokeLinecap});}
if(symbolizer.fill===true||symbolizer.graphic===true){OpenLayers.Util.applyDefaults(symbolizer,{fillColor:defaults.fillColor,fillOpacity:defaults.fillOpacity});}
if(symbolizer.graphic===true){OpenLayers.Util.applyDefaults(symbolizer,{pointRadius:this.defaultStyle.pointRadius,externalGraphic:this.defaultStyle.externalGraphic,graphicName:this.defaultStyle.graphicName,graphicOpacity:this.defaultStyle.graphicOpacity,graphicWidth:this.defaultStyle.graphicWidth,graphicHeight:this.defaultStyle.graphicHeight,graphicXOffset:this.defaultStyle.graphicXOffset,graphicYOffset:this.defaultStyle.graphicYOffset});}}
return this.createLiterals(OpenLayers.Util.extend(style,symbolizer),feature);},createLiterals:function(style,feature){var context=this.context||feature.attributes||feature.data;for(var i in this.propertyStyles){style[i]=OpenLayers.Style.createLiteral(style[i],context,feature);}
return style;},findPropertyStyles:function(){var propertyStyles={};var style=this.defaultStyle;this.addPropertyStyles(propertyStyles,style);var rules=this.rules;var symbolizer,value;for(var i=0,len=rules.length;i<len;i++){symbolizer=rules[i].symbolizer;for(var key in symbolizer){value=symbolizer[key];if(typeof value=="object"){this.addPropertyStyles(propertyStyles,value);}else{this.addPropertyStyles(propertyStyles,symbolizer);break;}}}
return propertyStyles;},addPropertyStyles:function(propertyStyles,symbolizer){var property;for(var key in symbolizer){property=symbolizer[key];if(typeof property=="string"&&property.match(/\$\{\w+\}/)){propertyStyles[key]=true;}}
return propertyStyles;},addRules:function(rules){this.rules=this.rules.concat(rules);this.propertyStyles=this.findPropertyStyles();},setDefaultStyle:function(style){this.defaultStyle=style;this.propertyStyles=this.findPropertyStyles();},getSymbolizerPrefix:function(geometry){var prefixes=OpenLayers.Style.SYMBOLIZER_PREFIXES;for(var i=0,len=prefixes.length;i<len;i++){if(geometry.CLASS_NAME.indexOf(prefixes[i])!=-1){return prefixes[i];}}},CLASS_NAME:"OpenLayers.Style"});OpenLayers.Style.createLiteral=function(value,context,feature){if(typeof value=="string"&&value.indexOf("${")!=-1){value=OpenLayers.String.format(value,context,[feature]);value=(isNaN(value)||!value)?value:parseFloat(value);}
return value;};OpenLayers.Style.SYMBOLIZER_PREFIXES=['Point','Line','Polygon','Text'];OpenLayers.StyleMap=OpenLayers.Class({styles:null,extendDefault:true,initialize:function(style,options){this.styles={"default":new OpenLayers.Style(OpenLayers.Feature.Vector.style["default"]),"select":new OpenLayers.Style(OpenLayers.Feature.Vector.style["select"]),"temporary":new OpenLayers.Style(OpenLayers.Feature.Vector.style["temporary"]),"delete":new OpenLayers.Style(OpenLayers.Feature.Vector.style["delete"])};if(style instanceof OpenLayers.Style){this.styles["default"]=style;this.styles["select"]=style;this.styles["temporary"]=style;this.styles["delete"]=style;}else if(typeof style=="object"){for(var key in style){if(style[key]instanceof OpenLayers.Style){this.styles[key]=style[key];}else if(typeof style[key]=="object"){this.styles[key]=new OpenLayers.Style(style[key]);}else{this.styles["default"]=new OpenLayers.Style(style);this.styles["select"]=new OpenLayers.Style(style);this.styles["temporary"]=new OpenLayers.Style(style);this.styles["delete"]=new OpenLayers.Style(style);break;}}}
OpenLayers.Util.extend(this,options);},destroy:function(){for(var key in this.styles){this.styles[key].destroy();}
this.styles=null;},createSymbolizer:function(feature,intent){if(!feature){feature=new OpenLayers.Feature.Vector();}
if(!this.styles[intent]){intent="default";}
feature.renderIntent=intent;var defaultSymbolizer={};if(this.extendDefault&&intent!="default"){defaultSymbolizer=this.styles["default"].createSymbolizer(feature);}
return OpenLayers.Util.extend(defaultSymbolizer,this.styles[intent].createSymbolizer(feature));},addUniqueValueRules:function(renderIntent,property,symbolizers,context){var rules=[];for(var value in symbolizers){rules.push(new OpenLayers.Rule({symbolizer:symbolizers[value],context:context,filter:new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.EQUAL_TO,property:property,value:value})}));}
this.styles[renderIntent].addRules(rules);},CLASS_NAME:"OpenLayers.StyleMap"});OpenLayers.Format=OpenLayers.Class({options:null,externalProjection:null,internalProjection:null,data:null,keepData:false,initialize:function(options){OpenLayers.Util.extend(this,options);this.options=options;},destroy:function(){},read:function(data){OpenLayers.Console.userError(OpenLayers.i18n("readNotImplemented"));},write:function(object){OpenLayers.Console.userError(OpenLayers.i18n("writeNotImplemented"));},CLASS_NAME:"OpenLayers.Format"});OpenLayers.Format.WKT=OpenLayers.Class(OpenLayers.Format,{initialize:function(options){this.regExes={'typeStr':/^\s*(\w+)\s*\(\s*(.*)\s*\)\s*$/,'spaces':/\s+/,'parenComma':/\)\s*,\s*\(/,'doubleParenComma':/\)\s*\)\s*,\s*\(\s*\(/,'trimParens':/^\s*\(?(.*?)\)?\s*$/};OpenLayers.Format.prototype.initialize.apply(this,[options]);},read:function(wkt){var features,type,str;var matches=this.regExes.typeStr.exec(wkt);if(matches){type=matches[1].toLowerCase();str=matches[2];if(this.parse[type]){features=this.parse[type].apply(this,[str]);}
if(this.internalProjection&&this.externalProjection){if(features&&features.CLASS_NAME=="OpenLayers.Feature.Vector"){features.geometry.transform(this.externalProjection,this.internalProjection);}else if(features&&type!="geometrycollection"&&typeof features=="object"){for(var i=0,len=features.length;i<len;i++){var component=features[i];component.geometry.transform(this.externalProjection,this.internalProjection);}}}}
return features;},write:function(features){var collection,geometry,type,data,isCollection;if(features.constructor==Array){collection=features;isCollection=true;}else{collection=[features];isCollection=false;}
var pieces=[];if(isCollection){pieces.push('GEOMETRYCOLLECTION(');}
for(var i=0,len=collection.length;i<len;++i){if(isCollection&&i>0){pieces.push(',');}
geometry=collection[i].geometry;type=geometry.CLASS_NAME.split('.')[2].toLowerCase();if(!this.extract[type]){return null;}
if(this.internalProjection&&this.externalProjection){geometry=geometry.clone();geometry.transform(this.internalProjection,this.externalProjection);}
data=this.extract[type].apply(this,[geometry]);pieces.push(type.toUpperCase()+'('+data+')');}
if(isCollection){pieces.push(')');}
return pieces.join('');},extract:{'point':function(point){return point.x+' '+point.y;},'multipoint':function(multipoint){var array=[];for(var i=0,len=multipoint.components.length;i<len;++i){array.push(this.extract.point.apply(this,[multipoint.components[i]]));}
return array.join(',');},'linestring':function(linestring){var array=[];for(var i=0,len=linestring.components.length;i<len;++i){array.push(this.extract.point.apply(this,[linestring.components[i]]));}
return array.join(',');},'multilinestring':function(multilinestring){var array=[];for(var i=0,len=multilinestring.components.length;i<len;++i){array.push('('+
this.extract.linestring.apply(this,[multilinestring.components[i]])+')');}
return array.join(',');},'polygon':function(polygon){var array=[];for(var i=0,len=polygon.components.length;i<len;++i){array.push('('+
this.extract.linestring.apply(this,[polygon.components[i]])+')');}
return array.join(',');},'multipolygon':function(multipolygon){var array=[];for(var i=0,len=multipolygon.components.length;i<len;++i){array.push('('+
this.extract.polygon.apply(this,[multipolygon.components[i]])+')');}
return array.join(',');}},parse:{'point':function(str){var coords=OpenLayers.String.trim(str).split(this.regExes.spaces);return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(coords[0],coords[1]));},'multipoint':function(str){var points=OpenLayers.String.trim(str).split(',');var components=[];for(var i=0,len=points.length;i<len;++i){components.push(this.parse.point.apply(this,[points[i]]).geometry);}
return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.MultiPoint(components));},'linestring':function(str){var points=OpenLayers.String.trim(str).split(',');var components=[];for(var i=0,len=points.length;i<len;++i){components.push(this.parse.point.apply(this,[points[i]]).geometry);}
return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(components));},'multilinestring':function(str){var line;var lines=OpenLayers.String.trim(str).split(this.regExes.parenComma);var components=[];for(var i=0,len=lines.length;i<len;++i){line=lines[i].replace(this.regExes.trimParens,'$1');components.push(this.parse.linestring.apply(this,[line]).geometry);}
return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.MultiLineString(components));},'polygon':function(str){var ring,linestring,linearring;var rings=OpenLayers.String.trim(str).split(this.regExes.parenComma);var components=[];for(var i=0,len=rings.length;i<len;++i){ring=rings[i].replace(this.regExes.trimParens,'$1');linestring=this.parse.linestring.apply(this,[ring]).geometry;linearring=new OpenLayers.Geometry.LinearRing(linestring.components);components.push(linearring);}
return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon(components));},'multipolygon':function(str){var polygon;var polygons=OpenLayers.String.trim(str).split(this.regExes.doubleParenComma);var components=[];for(var i=0,len=polygons.length;i<len;++i){polygon=polygons[i].replace(this.regExes.trimParens,'$1');components.push(this.parse.polygon.apply(this,[polygon]).geometry);}
return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.MultiPolygon(components));},'geometrycollection':function(str){str=str.replace(/,\s*([A-Za-z])/g,'|$1');var wktArray=OpenLayers.String.trim(str).split('|');var components=[];for(var i=0,len=wktArray.length;i<len;++i){components.push(OpenLayers.Format.WKT.prototype.read.apply(this,[wktArray[i]]));}
return components;}},CLASS_NAME:"OpenLayers.Format.WKT"});OpenLayers.Lang={code:null,defaultCode:"en",getCode:function(){if(!OpenLayers.Lang.code){OpenLayers.Lang.setCode();}
return OpenLayers.Lang.code;},setCode:function(code){var lang;if(!code){code=(OpenLayers.Util.getBrowserName()=="msie")?navigator.userLanguage:navigator.language;}
var parts=code.split('-');parts[0]=parts[0].toLowerCase();if(typeof OpenLayers.Lang[parts[0]]=="object"){lang=parts[0];}
if(parts[1]){var testLang=parts[0]+'-'+parts[1].toUpperCase();if(typeof OpenLayers.Lang[testLang]=="object"){lang=testLang;}}
if(!lang){OpenLayers.Console.warn('Failed to find OpenLayers.Lang.'+parts.join("-")+' dictionary, falling back to default language');lang=OpenLayers.Lang.defaultCode;}
OpenLayers.Lang.code=lang;},translate:function(key,context){var dictionary=OpenLayers.Lang[OpenLayers.Lang.getCode()];var message=dictionary[key];if(!message){message=key;}
if(context){message=OpenLayers.String.format(message,context);}
return message;}};OpenLayers.i18n=OpenLayers.Lang.translate;OpenLayers.Lang.en={'unhandledRequest':"Unhandled request return ${statusText}",'permalink':"Permalink",'overlays':"Overlays",'baseLayer':"Base Layer",'sameProjection':"The overview map only works when it is in the same projection as the main map",'readNotImplemented':"Read not implemented.",'writeNotImplemented':"Write not implemented.",'noFID':"Can't update a feature for which there is no FID.",'errorLoadingGML':"Error in loading GML file ${url}",'browserNotSupported':"Your browser does not support vector rendering. Currently supported renderers are:\n${renderers}",'componentShouldBe':"addFeatures : component should be an ${geomType}",'getFeatureError':"getFeatureFromEvent called on layer with no renderer. This usually means you "+"destroyed a layer, but not some handler which is associated with it.",'minZoomLevelError':"The minZoomLevel property is only intended for use "+"with the FixedZoomLevels-descendent layers. That this "+"wfs layer checks for minZoomLevel is a relic of the"+"past. We cannot, however, remove it without possibly "+"breaking OL based applications that may depend on it."+" Therefore we are deprecating it -- the minZoomLevel "+"check below will be removed at 3.0. Please instead "+"use min/max resolution setting as described here: "+"http://trac.openlayers.org/wiki/SettingZoomLevels",'commitSuccess':"WFS Transaction: SUCCESS ${response}",'commitFailed':"WFS Transaction: FAILED ${response}",'googleWarning':"The Google Layer was unable to load correctly.<br><br>"+"To get rid of this message, select a new BaseLayer "+"in the layer switcher in the upper-right corner.<br><br>"+"Most likely, this is because the Google Maps library "+"script was either not included, or does not contain the "+"correct API key for your site.<br><br>"+"Developers: For help getting this working correctly, "+"<a href='http://trac.openlayers.org/wiki/Google' "+"target='_blank'>click here</a>",'getLayerWarning':"The ${layerType} Layer was unable to load correctly.<br><br>"+"To get rid of this message, select a new BaseLayer "+"in the layer switcher in the upper-right corner.<br><br>"+"Most likely, this is because the ${layerLib} library "+"script was not correctly included.<br><br>"+"Developers: For help getting this working correctly, "+"<a href='http://trac.openlayers.org/wiki/${layerLib}' "+"target='_blank'>click here</a>",'scale':"Scale = 1 : ${scaleDenom}",'layerAlreadyAdded':"You tried to add the layer: ${layerName} to the map, but it has already been added",'reprojectDeprecated':"You are using the 'reproject' option "+"on the ${layerName} layer. This option is deprecated: "+"its use was designed to support displaying data over commercial "+"basemaps, but that functionality should now be achieved by using "+"Spherical Mercator support. More information is available from "+"http://trac.openlayers.org/wiki/SphericalMercator.",'methodDeprecated':"This method has been deprecated and will be removed in 3.0. "+"Please use ${newMethod} instead.",'boundsAddError':"You must pass both x and y values to the add function.",'lonlatAddError':"You must pass both lon and lat values to the add function.",'pixelAddError':"You must pass both x and y values to the add function.",'unsupportedGeometryType':"Unsupported geometry type: ${geomType}",'pagePositionFailed':"OpenLayers.Util.pagePosition failed: element with id ${elemId} may be misplaced.",'end':'','filterEvaluateNotImplemented':"evaluate is not implemented for this filter type."};dhtmlx=function(obj){for(var a in obj)dhtmlx[a]=obj[a];return dhtmlx};dhtmlx.extend_api=function(name,map,ext){var t=window[name];if(!t)return;window[name]=function(obj){if(obj&&typeof obj=="object"&&!obj.tagName&&!(obj instanceof Array)){var that=t.apply(this,(map._init?map._init(obj):arguments));for(var a in dhtmlx)if(map[a])this[map[a]](dhtmlx[a]);for(var a in obj){if(map[a])this[map[a]](obj[a]);else if(a.indexOf("on")==0){this.attachEvent(a,obj[a])}}}else
var that=t.apply(this,arguments);if(map._patch)map._patch(this);return that||this};window[name].prototype=t.prototype;if(ext)dhtmlXHeir(window[name].prototype,ext)};dhtmlxAjax={get:function(url,callback){var t=new dtmlXMLLoaderObject(true);t.async=(arguments.length<3);t.waitCall=callback;t.loadXML(url)
return t},post:function(url,post,callback){var t=new dtmlXMLLoaderObject(true);t.async=(arguments.length<4);t.waitCall=callback;t.loadXML(url,true,post)
return t},getSync:function(url){return this.get(url,null,true)},postSync:function(url,post){return this.post(url,post,null,true)}};function dtmlXMLLoaderObject(funcObject,dhtmlObject,async,rSeed){this.xmlDoc="";if(typeof(async)!="undefined")
this.async=async;else
this.async=true;this.onloadAction=funcObject||null;this.mainObject=dhtmlObject||null;this.waitCall=null;this.rSeed=rSeed||false;return this};dtmlXMLLoaderObject.prototype.waitLoadFunction=function(dhtmlObject){var once=true;this.check=function(){if((dhtmlObject)&&(dhtmlObject.onloadAction!=null)){if((!dhtmlObject.xmlDoc.readyState)||(dhtmlObject.xmlDoc.readyState==4)){if(!once)return;once=false;if(typeof dhtmlObject.onloadAction=="function")dhtmlObject.onloadAction(dhtmlObject.mainObject,null,null,null,dhtmlObject);if(dhtmlObject.waitCall){dhtmlObject.waitCall.call(this,dhtmlObject);dhtmlObject.waitCall=null}}}};return this.check};dtmlXMLLoaderObject.prototype.getXMLTopNode=function(tagName,oldObj){if(this.xmlDoc.responseXML){var temp=this.xmlDoc.responseXML.getElementsByTagName(tagName);if(temp.length==0&&tagName.indexOf(":")!=-1)
var temp=this.xmlDoc.responseXML.getElementsByTagName((tagName.split(":"))[1]);var z=temp[0]}else
var z=this.xmlDoc.documentElement;if(z){this._retry=false;return z};if((_isIE)&&(!this._retry)){var xmlString=this.xmlDoc.responseText;var oldObj=this.xmlDoc;this._retry=true;this.xmlDoc=new ActiveXObject("Microsoft.XMLDOM");this.xmlDoc.async=false;this.xmlDoc["loadXM"+"L"](xmlString);return this.getXMLTopNode(tagName,oldObj)};dhtmlxError.throwError("LoadXML","Incorrect XML",[(oldObj||this.xmlDoc),this.mainObject]);return document.createElement("DIV")};dtmlXMLLoaderObject.prototype.loadXMLString=function(xmlString){{try{var parser=new DOMParser();this.xmlDoc=parser.parseFromString(xmlString,"text/xml")}catch(e){this.xmlDoc=new ActiveXObject("Microsoft.XMLDOM");this.xmlDoc.async=this.async;this.xmlDoc["loadXM"+"L"](xmlString)}};this.onloadAction(this.mainObject,null,null,null,this);if(this.waitCall){this.waitCall();this.waitCall=null}};dtmlXMLLoaderObject.prototype.loadXML=function(filePath,postMode,postVars,rpc){if(this.rSeed)filePath+=((filePath.indexOf("?")!=-1)?"&":"?")+"a_dhx_rSeed="+(new Date()).valueOf();this.filePath=filePath;if((!_isIE)&&(window.XMLHttpRequest))
this.xmlDoc=new XMLHttpRequest();else{if(document.implementation&&document.implementation.createDocument){this.xmlDoc=document.implementation.createDocument("","",null);this.xmlDoc.onload=new this.waitLoadFunction(this);this.xmlDoc.load(filePath);return}else
this.xmlDoc=new ActiveXObject("Microsoft.XMLHTTP")};if(this.async)this.xmlDoc.onreadystatechange=new this.waitLoadFunction(this);this.xmlDoc.open(postMode?"POST":"GET",filePath,this.async);if(rpc){this.xmlDoc.setRequestHeader("User-Agent","dhtmlxRPC v0.1 ("+navigator.userAgent+")");this.xmlDoc.setRequestHeader("Content-type","text/xml")}else if(postMode)this.xmlDoc.setRequestHeader('Content-type','application/x-www-form-urlencoded');this.xmlDoc.setRequestHeader("X-Requested-With","XMLHttpRequest");this.xmlDoc.send(null||postVars);if(!this.async)(new this.waitLoadFunction(this))()};dtmlXMLLoaderObject.prototype.destructor=function(){this.onloadAction=null;this.mainObject=null;this.xmlDoc=null;return null};dtmlXMLLoaderObject.prototype.xmlNodeToJSON=function(node){var t={};for(var i=0;i<node.attributes.length;i++)t[node.attributes[i].name]=node.attributes[i].value;t["_tagvalue"]=node.firstChild?node.firstChild.nodeValue:"";for(var i=0;i<node.childNodes.length;i++){var name=node.childNodes[i].tagName;if(name){if(!t[name])t[name]=[];t[name].push(this.xmlNodeToJSON(node.childNodes[i]))}};return t};function callerFunction(funcObject,dhtmlObject){this.handler=function(e){if(!e)e=window.event;funcObject(e,dhtmlObject);return true};return this.handler};function getAbsoluteLeft(htmlObject){return getOffset(htmlObject).left};function getAbsoluteTop(htmlObject){return getOffset(htmlObject).top};function getOffsetSum(elem){var top=0,left=0;while(elem){top=top+parseInt(elem.offsetTop);left=left+parseInt(elem.offsetLeft);elem=elem.offsetParent};return{top:top,left:left}};function getOffsetRect(elem){var box=elem.getBoundingClientRect();var body=document.body;var docElem=document.documentElement;var scrollTop=window.pageYOffset||docElem.scrollTop||body.scrollTop;var scrollLeft=window.pageXOffset||docElem.scrollLeft||body.scrollLeft;var clientTop=docElem.clientTop||body.clientTop||0;var clientLeft=docElem.clientLeft||body.clientLeft||0;var top=box.top+scrollTop-clientTop;var left=box.left+scrollLeft-clientLeft;return{top:Math.round(top),left:Math.round(left)}};function getOffset(elem){if(elem.getBoundingClientRect&&!_isChrome){return getOffsetRect(elem)}else{return getOffsetSum(elem)}};function convertStringToBoolean(inputString){if(typeof(inputString)=="string")
inputString=inputString.toLowerCase();switch(inputString){case"1":case"true":case"yes":case"y":case 1:case true:return true;break;default:return false}};function getUrlSymbol(str){if(str.indexOf("?")!=-1)
return"&"
else
return"?"};function dhtmlDragAndDropObject(){if(window.dhtmlDragAndDrop)return window.dhtmlDragAndDrop;this.lastLanding=0;this.dragNode=0;this.dragStartNode=0;this.dragStartObject=0;this.tempDOMU=null;this.tempDOMM=null;this.waitDrag=0;window.dhtmlDragAndDrop=this;return this};dhtmlDragAndDropObject.prototype.removeDraggableItem=function(htmlNode){htmlNode.onmousedown=null;htmlNode.dragStarter=null;htmlNode.dragLanding=null};dhtmlDragAndDropObject.prototype.addDraggableItem=function(htmlNode,dhtmlObject){htmlNode.onmousedown=this.preCreateDragCopy;htmlNode.dragStarter=dhtmlObject;this.addDragLanding(htmlNode,dhtmlObject)};dhtmlDragAndDropObject.prototype.addDragLanding=function(htmlNode,dhtmlObject){htmlNode.dragLanding=dhtmlObject};dhtmlDragAndDropObject.prototype.preCreateDragCopy=function(e){if((e||event)&&(e||event).button==2)
return;if(window.dhtmlDragAndDrop.waitDrag){window.dhtmlDragAndDrop.waitDrag=0;document.body.onmouseup=window.dhtmlDragAndDrop.tempDOMU;document.body.onmousemove=window.dhtmlDragAndDrop.tempDOMM;return false};window.dhtmlDragAndDrop.waitDrag=1;window.dhtmlDragAndDrop.tempDOMU=document.body.onmouseup;window.dhtmlDragAndDrop.tempDOMM=document.body.onmousemove;window.dhtmlDragAndDrop.dragStartNode=this;window.dhtmlDragAndDrop.dragStartObject=this.dragStarter;document.body.onmouseup=window.dhtmlDragAndDrop.preCreateDragCopy;document.body.onmousemove=window.dhtmlDragAndDrop.callDrag;window.dhtmlDragAndDrop.downtime=new Date().valueOf();if((e)&&(e.preventDefault)){e.preventDefault();return false};return false};dhtmlDragAndDropObject.prototype.callDrag=function(e){if(!e)e=window.event;dragger=window.dhtmlDragAndDrop;if((new Date()).valueOf()-dragger.downtime<100)return;if((e.button==0)&&(_isIE))
return dragger.stopDrag();if(!dragger.dragNode&&dragger.waitDrag){dragger.dragNode=dragger.dragStartObject._createDragNode(dragger.dragStartNode,e);if(!dragger.dragNode)return dragger.stopDrag();dragger.dragNode.onselectstart=function(){return false};dragger.gldragNode=dragger.dragNode;document.body.appendChild(dragger.dragNode);document.body.onmouseup=dragger.stopDrag;dragger.waitDrag=0;dragger.dragNode.pWindow=window;dragger.initFrameRoute()};if(dragger.dragNode.parentNode!=window.document.body){var grd=dragger.gldragNode;if(dragger.gldragNode.old)grd=dragger.gldragNode.old;grd.parentNode.removeChild(grd);var oldBody=dragger.dragNode.pWindow;if(_isIE){var div=document.createElement("Div");div.innerHTML=dragger.dragNode.outerHTML;dragger.dragNode=div.childNodes[0]}else
dragger.dragNode=dragger.dragNode.cloneNode(true);dragger.dragNode.pWindow=window;dragger.gldragNode.old=dragger.dragNode;document.body.appendChild(dragger.dragNode);oldBody.dhtmlDragAndDrop.dragNode=dragger.dragNode};dragger.dragNode.style.left=e.clientX+15+(dragger.fx?dragger.fx*(-1):0)
+(document.body.scrollLeft||document.documentElement.scrollLeft)+"px";dragger.dragNode.style.top=e.clientY+3+(dragger.fy?dragger.fy*(-1):0)
+(document.body.scrollTop||document.documentElement.scrollTop)+"px";if(!e.srcElement)var z=e.target;else
z=e.srcElement;dragger.checkLanding(z,e)};dhtmlDragAndDropObject.prototype.calculateFramePosition=function(n){if(window.name){var el=parent.frames[window.name].frameElement.offsetParent;var fx=0;var fy=0;while(el){fx+=el.offsetLeft;fy+=el.offsetTop;el=el.offsetParent};if((parent.dhtmlDragAndDrop)){var ls=parent.dhtmlDragAndDrop.calculateFramePosition(1);fx+=ls.split('_')[0]*1;fy+=ls.split('_')[1]*1};if(n)return fx+"_"+fy;else
this.fx=fx;this.fy=fy};return"0_0"};dhtmlDragAndDropObject.prototype.checkLanding=function(htmlObject,e){if((htmlObject)&&(htmlObject.dragLanding)){if(this.lastLanding)this.lastLanding.dragLanding._dragOut(this.lastLanding);this.lastLanding=htmlObject;this.lastLanding=this.lastLanding.dragLanding._dragIn(this.lastLanding,this.dragStartNode,e.clientX,e.clientY,e);this.lastLanding_scr=(_isIE?e.srcElement:e.target)}else{if((htmlObject)&&(htmlObject.tagName!="BODY"))
this.checkLanding(htmlObject.parentNode,e);else{if(this.lastLanding)this.lastLanding.dragLanding._dragOut(this.lastLanding,e.clientX,e.clientY,e);this.lastLanding=0;if(this._onNotFound)this._onNotFound()}}};dhtmlDragAndDropObject.prototype.stopDrag=function(e,mode){dragger=window.dhtmlDragAndDrop;if(!mode){dragger.stopFrameRoute();var temp=dragger.lastLanding;dragger.lastLanding=null;if(temp)temp.dragLanding._drag(dragger.dragStartNode,dragger.dragStartObject,temp,(_isIE?event.srcElement:e.target))};dragger.lastLanding=null;if((dragger.dragNode)&&(dragger.dragNode.parentNode==document.body))
dragger.dragNode.parentNode.removeChild(dragger.dragNode);dragger.dragNode=0;dragger.gldragNode=0;dragger.fx=0;dragger.fy=0;dragger.dragStartNode=0;dragger.dragStartObject=0;document.body.onmouseup=dragger.tempDOMU;document.body.onmousemove=dragger.tempDOMM;dragger.tempDOMU=null;dragger.tempDOMM=null;dragger.waitDrag=0};dhtmlDragAndDropObject.prototype.stopFrameRoute=function(win){if(win)window.dhtmlDragAndDrop.stopDrag(1,1);for(var i=0;i<window.frames.length;i++){try{if((window.frames[i]!=win)&&(window.frames[i].dhtmlDragAndDrop))
window.frames[i].dhtmlDragAndDrop.stopFrameRoute(window)}catch(e){}};try{if((parent.dhtmlDragAndDrop)&&(parent!=window)&&(parent!=win))
parent.dhtmlDragAndDrop.stopFrameRoute(window)}catch(e){}};dhtmlDragAndDropObject.prototype.initFrameRoute=function(win,mode){if(win){window.dhtmlDragAndDrop.preCreateDragCopy();window.dhtmlDragAndDrop.dragStartNode=win.dhtmlDragAndDrop.dragStartNode;window.dhtmlDragAndDrop.dragStartObject=win.dhtmlDragAndDrop.dragStartObject;window.dhtmlDragAndDrop.dragNode=win.dhtmlDragAndDrop.dragNode;window.dhtmlDragAndDrop.gldragNode=win.dhtmlDragAndDrop.dragNode;window.document.body.onmouseup=window.dhtmlDragAndDrop.stopDrag;window.waitDrag=0;if(((!_isIE)&&(mode))&&((!_isFF)||(_FFrv<1.8)))
window.dhtmlDragAndDrop.calculateFramePosition()};try{if((parent.dhtmlDragAndDrop)&&(parent!=window)&&(parent!=win))
parent.dhtmlDragAndDrop.initFrameRoute(window)}catch(e){};for(var i=0;i<window.frames.length;i++){try{if((window.frames[i]!=win)&&(window.frames[i].dhtmlDragAndDrop))
window.frames[i].dhtmlDragAndDrop.initFrameRoute(window,((!win||mode)?1:0))}catch(e){}}};var _isFF=false;var _isIE=false;var _isOpera=false;var _isKHTML=false;var _isMacOS=false;var _isChrome=false;if(navigator.userAgent.indexOf('Macintosh')!=-1)
_isMacOS=true;if(navigator.userAgent.toLowerCase().indexOf('chrome')>-1)
_isChrome=true;if((navigator.userAgent.indexOf('Safari')!=-1)||(navigator.userAgent.indexOf('Konqueror')!=-1)){var _KHTMLrv=parseFloat(navigator.userAgent.substr(navigator.userAgent.indexOf('Safari')+7,5));if(_KHTMLrv>525){_isFF=true;var _FFrv=1.9}else
_isKHTML=true}else if(navigator.userAgent.indexOf('Opera')!=-1){_isOpera=true;_OperaRv=parseFloat(navigator.userAgent.substr(navigator.userAgent.indexOf('Opera')+6,3))}else if(navigator.appName.indexOf("Microsoft")!=-1){_isIE=true;if(navigator.appVersion.indexOf("MSIE 8.0")!=-1&&document.compatMode!="BackCompat")_isIE=8}else{_isFF=true;var _FFrv=parseFloat(navigator.userAgent.split("rv:")[1])};dtmlXMLLoaderObject.prototype.doXPath=function(xpathExp,docObj,namespace,result_type){if(_isKHTML||(!_isIE&&!window.XPathResult))
return this.doXPathOpera(xpathExp,docObj);if(_isIE){if(!docObj)if(!this.xmlDoc.nodeName)docObj=this.xmlDoc.responseXML
else
docObj=this.xmlDoc;if(!docObj)dhtmlxError.throwError("LoadXML","Incorrect XML",[(docObj||this.xmlDoc),this.mainObject]);if(namespace!=null)docObj.setProperty("SelectionNamespaces","xmlns:xsl='"+namespace+"'");if(result_type=='single'){return docObj.selectSingleNode(xpathExp)}else{return docObj.selectNodes(xpathExp)||new Array(0)}}else{var nodeObj=docObj;if(!docObj){if(!this.xmlDoc.nodeName){docObj=this.xmlDoc.responseXML}else{docObj=this.xmlDoc}};if(!docObj)dhtmlxError.throwError("LoadXML","Incorrect XML",[(docObj||this.xmlDoc),this.mainObject]);if(docObj.nodeName.indexOf("document")!=-1){nodeObj=docObj}else{nodeObj=docObj;docObj=docObj.ownerDocument};var retType=XPathResult.ANY_TYPE;if(result_type=='single')retType=XPathResult.FIRST_ORDERED_NODE_TYPE
var rowsCol=new Array();var col=docObj.evaluate(xpathExp,nodeObj,function(pref){return namespace},retType,null);if(retType==XPathResult.FIRST_ORDERED_NODE_TYPE){return col.singleNodeValue};var thisColMemb=col.iterateNext();while(thisColMemb){rowsCol[rowsCol.length]=thisColMemb;thisColMemb=col.iterateNext()};return rowsCol}};function _dhtmlxError(type,name,params){if(!this.catches)this.catches=new Array();return this};_dhtmlxError.prototype.catchError=function(type,func_name){this.catches[type]=func_name};_dhtmlxError.prototype.throwError=function(type,name,params){if(this.catches[type])return this.catches[type](type,name,params);if(this.catches["ALL"])return this.catches["ALL"](type,name,params);alert("Error type: "+arguments[0]+"\nDescription: "+arguments[1]);return null};window.dhtmlxError=new _dhtmlxError();dtmlXMLLoaderObject.prototype.doXPathOpera=function(xpathExp,docObj){var z=xpathExp.replace(/[\/]+/gi,"/").split('/');var obj=null;var i=1;if(!z.length)return[];if(z[0]==".")obj=[docObj];else if(z[0]==""){obj=(this.xmlDoc.responseXML||this.xmlDoc).getElementsByTagName(z[i].replace(/\[[^\]]*\]/g,""));i++}else
return[];for(i;i<z.length;i++)obj=this._getAllNamedChilds(obj,z[i]);if(z[i-1].indexOf("[")!=-1)
obj=this._filterXPath(obj,z[i-1]);return obj};dtmlXMLLoaderObject.prototype._filterXPath=function(a,b){var c=new Array();var b=b.replace(/[^\[]*\[\@/g,"").replace(/[\[\]\@]*/g,"");for(var i=0;i<a.length;i++)if(a[i].getAttribute(b))
c[c.length]=a[i];return c};dtmlXMLLoaderObject.prototype._getAllNamedChilds=function(a,b){var c=new Array();if(_isKHTML)b=b.toUpperCase();for(var i=0;i<a.length;i++)for(var j=0;j<a[i].childNodes.length;j++){if(_isKHTML){if(a[i].childNodes[j].tagName&&a[i].childNodes[j].tagName.toUpperCase()==b)
c[c.length]=a[i].childNodes[j]}else if(a[i].childNodes[j].tagName==b)c[c.length]=a[i].childNodes[j]};return c};function dhtmlXHeir(a,b){for(var c in b)if(typeof(b[c])=="function")
a[c]=b[c];return a};function dhtmlxEvent(el,event,handler){if(el.addEventListener)el.addEventListener(event,handler,false);else if(el.attachEvent)el.attachEvent("on"+event,handler)};dtmlXMLLoaderObject.prototype.xslDoc=null;dtmlXMLLoaderObject.prototype.setXSLParamValue=function(paramName,paramValue,xslDoc){if(!xslDoc)xslDoc=this.xslDoc
if(xslDoc.responseXML)xslDoc=xslDoc.responseXML;var item=this.doXPath("/xsl:stylesheet/xsl:variable[@name='"+paramName+"']",xslDoc,"http:/\/www.w3.org/1999/XSL/Transform","single");if(item!=null)item.firstChild.nodeValue=paramValue};dtmlXMLLoaderObject.prototype.doXSLTransToObject=function(xslDoc,xmlDoc){if(!xslDoc)xslDoc=this.xslDoc;if(xslDoc.responseXML)xslDoc=xslDoc.responseXML
if(!xmlDoc)xmlDoc=this.xmlDoc;if(xmlDoc.responseXML)xmlDoc=xmlDoc.responseXML
if(!_isIE){if(!this.XSLProcessor){this.XSLProcessor=new XSLTProcessor();this.XSLProcessor.importStylesheet(xslDoc)};var result=this.XSLProcessor.transformToDocument(xmlDoc)}else{var result=new ActiveXObject("Msxml2.DOMDocument.3.0");try{xmlDoc.transformNodeToObject(xslDoc,result)}catch(e){result=xmlDoc.transformNode(xslDoc)}};return result};dtmlXMLLoaderObject.prototype.doXSLTransToString=function(xslDoc,xmlDoc){var res=this.doXSLTransToObject(xslDoc,xmlDoc);if(typeof(res)=="string")
return res;return this.doSerialization(res)};dtmlXMLLoaderObject.prototype.doSerialization=function(xmlDoc){if(!xmlDoc)xmlDoc=this.xmlDoc;if(xmlDoc.responseXML)xmlDoc=xmlDoc.responseXML
if(!_isIE){var xmlSerializer=new XMLSerializer();return xmlSerializer.serializeToString(xmlDoc)}else
return xmlDoc.xml};dhtmlxEventable=function(obj){obj.dhx_SeverCatcherPath="";obj.attachEvent=function(name,catcher,callObj){name='ev_'+name.toLowerCase();if(!this[name])this[name]=new this.eventCatcher(callObj||this);return(name+':'+this[name].addEvent(catcher))};obj.callEvent=function(name,arg0){name='ev_'+name.toLowerCase();if(this[name])return this[name].apply(this,arg0);return true};obj.checkEvent=function(name){return(!!this['ev_'+name.toLowerCase()])};obj.eventCatcher=function(obj){var dhx_catch=[];var z=function(){var res=true;for(var i=0;i<dhx_catch.length;i++){if(dhx_catch[i]!=null){var zr=dhx_catch[i].apply(obj,arguments);res=res&&zr}};return res};z.addEvent=function(ev){if(typeof(ev)!="function")
ev=eval(ev);if(ev)return dhx_catch.push(ev)-1;return false};z.removeEvent=function(id){dhx_catch[id]=null};return z};obj.detachEvent=function(id){if(id!=false){var list=id.split(':');this[list[0]].removeEvent(list[1])}}};function dhtmlxSlider(base,size,skin,vertical,min,max,value,step){if(_isIE)try{document.execCommand("BackgroundImageCache",false,true)}catch(e){};var parentNod;if(base&&typeof(base)=="object"&&!base.nodeName){parentNod=base.parent;skin=base.skin;min=base.min;max=base.max
step=base.step
vertical=base.vertical
value=base.value;size=base.size};if(!base){var z="slider_div_"+(new Date()).valueOf()+Math.random(1000);parentNod=document.createElement("div");parentNod.setAttribute("id",z);var child=document.body.lastChild;while(child.lastChild&&child.lastChild.nodeType==1)child=child.lastChild;child.parentNode.insertBefore(parentNod,child)}else if(typeof(base)!="object")
parentNod=document.getElementById(base);else
parentNod=base;if(typeof(size)=="object"){skin=size.skin;min=size.min;max=size.max
step=size.step
vertical=size.vertical
value=size.value;size=size.size};this.size=size;this.vMode=vertical||false;this.skin=dhtmlx.skin||skin||"default";this.parent=parentNod;this.isInit=false;this.disabled=false;this.value=value||min||0;this.inputPriority=true;this.stepping=false;this.imgURL=window.dhx_globalImgPath||dhtmlx.image_path||"";this._skinsImgs={"default":{ls:1,lz:1,rz:1,rs:1},ball:{ls:1,lz:1,rz:1,rs:1},zipper:{bg:1,lz:1,rz:1},arrow:{bg:1,ls:1,rs:1},arrowgreen:{bg:1,ls:1,rs:1},simplesilver:{lz:1,ls:1,rs:1,rz:1},simplegray:{lz:1,ls:1,rs:1,rz:1},bar:{bg:1,ls:1,rs:1},dhx_skyblue:{bg:1,ls:1,rs:1}};this._def=[min-0||0,max-0||100,step-0||1,value-0||0,size-0];dhtmlxEventable(this);return this};dhtmlxSlider.prototype.createStructure=function(){if(this.con){this.con.parentNode.removeChild(this.con);this.con=null};if(this.vMode){this._sW="height";this._sH="width";this._sL="top";this._sT="left";var skinImgPath=this.imgURL+"skins/"+this.skin+"/vertical/"}else{this._sW="width";this._sH="height";this._sL="left";this._sT="top";var skinImgPath=this.imgURL+"skins/"+this.skin+"/"};this.con=document.createElement("DIV");this.con.onselectstart=function(){return false};this.con._etype="slider";this.con.className="dhtmlxSlider"+(this.skin!='default'?"_"+this.skin:"");if(this._skinsImgs[this.skin]['bg'])this.con.style.backgroundImage="url("+skinImgPath+"bg.gif)";this.drag=document.createElement("DIV");this.drag._etype="drag";this.drag.className="selector";this.drag.style.backgroundImage="url("+skinImgPath+"selector.gif)";var leftSide=document.createElement("DIV");leftSide.className="leftSide";if(this._skinsImgs[this.skin]['ls'])leftSide.style.background="url("+skinImgPath+"leftside_bg.gif)";this.leftZone=document.createElement("DIV");this.leftZone.className="leftZone";if(this._skinsImgs[this.skin]['lz'])this.leftZone.style.background="url("+skinImgPath+"leftzone_bg.gif)";this.leftZone.style.width=this.value+'px';var rightSide=document.createElement("DIV");rightSide.className="rightSide";if(this._skinsImgs[this.skin]['rs'])rightSide.style.background="url("+skinImgPath+"rightside_bg.gif)";this.rightZone=document.createElement("DIV");this.rightZone.className="rightZone";if(this._skinsImgs[this.skin]['rz'])this.rightZone.style.background="url("+skinImgPath+"rightzone_bg.gif)";this.con.appendChild(leftSide);this.con.appendChild(this.leftZone);this.con.appendChild(this.rightZone);this.con.appendChild(rightSide);this.con.appendChild(this.drag);this.parent.appendChild(this.con);if(!this.parent.parentNode||!this.parent.parentNode.tagName)document.body.appendChild(this.parent);if(this.vMode){this._sW="height";this._sH="width";this._sL="top";this._sT="left";this.con.style.width=this.con.offsetHeight+'px';for(var i=0;i<this.con.childNodes.length;i++){this.con.childNodes[i].style.fontSize="0";var tmp=this.con.childNodes[i].offsetWidth;this.con.childNodes[i].style.width=this.con.childNodes[i].offsetHeight+'px';this.con.childNodes[i].style.height=tmp+'px';tmp=this.con.childNodes[i].offsetLeft;this.con.childNodes[i].style.left=this.con.childNodes[i].offsetTop+'px';this.con.childNodes[i].style.top=tmp+'px'};rightSide.style.top=this.size-rightSide.offsetHeight+'px';this.zoneSize=this.size-rightSide.offsetHeight;this.dragLeft=this.drag.offsetTop;this.dragWidth=this.drag.offsetHeight;this.rightZone.style.height=this.zoneSize+'px'}else{this.zoneSize=this.size-rightSide.offsetWidth;this.dragLeft=this.drag.offsetLeft;this.dragWidth=this.drag.offsetWidth;this.rightZone.style.width=this.zoneSize+'px'};this.con.style[this._sW]=this.size+"px";this.con.onmousedown=this._onMouseDown;this.con.onmouseup=this.con.onmouseout=function(){clearInterval(this.that._int)};this.con.that=this;this._aCalc(this._def)};dhtmlxSlider.prototype._aCalc=function(def){if(!this.isInit)return;this.shift=def[0];this.limit=def[1]-this.shift;this._mod=(def[4]-this.dragLeft*2-this.dragWidth)/this.limit;this._step=def[2];this.step=this._step*this._mod;this._xlimit=def[4]-this.dragLeft*2-this.dragWidth;if(!this.posX){this.posX=this._xlimit*(def[3]-this.shift)/this.limit};this._applyPos(true);return this};dhtmlxSlider.prototype.setMin=function(val){this._def[0]=val-0;this._aCalc(this._def)};dhtmlxSlider.prototype.setMax=function(val){this._def[1]=val-0;this._aCalc(this._def)};dhtmlxSlider.prototype.setStep=function(val){this._def[2]=val-0;this._aCalc(this._def)};dhtmlxSlider.prototype._applyPos=function(skip){if(!this.isInit)return;if(this.step!=1)this.posX=Math.round(this.posX/this.step)*this.step;if(this.posX<0)this.posX=0;if(this.value<(this._def[0]||0))
this.value=this._def[0]||0;if(this.value>this._def[1])this.value=this._def[1];if(this.posX>this._xlimit)this.posX=this._xlimit;var a_old=this.drag.style[this._sL];this.drag.style[this._sL]=this.posX+this.dragLeft*1+"px";this.leftZone.style[this._sW]=this.posX+this.dragLeft*1+"px";this.rightZone.style[this._sL]=this.posX+this.dragLeft*1+1+"px";this.rightZone.style[this._sW]=this.zoneSize-(this.posX+this.dragLeft*1)+"px";var nw=this.getValue();if(this._link){if(this._linkBoth)this._link.value=nw;else
this._link.innerHTML=nw};if(!skip&&a_old!=this.drag.style[this._sL])this.callEvent("onChange",[nw,this]);this.value=this.getValue();if(!this._dttp)this._setTooltip(nw)};dhtmlxSlider.prototype._setTooltip=function(nw){this.con.title=nw};dhtmlxSlider.prototype.setSkin=function(skin){this.skin=skin||"default";if(this.isInit)this.createStructure()};dhtmlxSlider.prototype.startDrag=function(e){if(this._busy)return;if((e.button===0)||(e.button===1)){this.drag_mx=e.clientX;this.drag_my=e.clientY;this.drag_cx=this.posX;this.d_b_move=document.body.onmousemove;this.d_b_up=document.body.onmouseup;var _c=this;document.body.onmouseup=function(e){_c.stopDrag(e||event);_c=null};document.body.onmousemove=function(e){_c.onDrag(e||event)};this._busy=true}};dhtmlxSlider.prototype.onDrag=function(e){if(this._busy){if(!this.vMode)this.posX=this.drag_cx+e.clientX-this.drag_mx;else
this.posX=this.drag_cx+e.clientY-this.drag_my;this._applyPos()}};dhtmlxSlider.prototype.stopDrag=function(e){document.body.onmousemove=this.d_b_move?this.d_b_move:null;document.body.onmouseup=this.d_b_up?this.d_b_up:null;this.d_b_move=this.d_b_up=null;this._busy=false;this.callEvent("onSlideEnd",[this.getValue()])};dhtmlxSlider.prototype.getValue=function(){if((!this._busy)&&(this.inputPriority))
return(Math.round(this.value/this._step)*this._step).toFixed(6)-0;return Math.round((Math.round((this.posX/this._mod)/this._step)*this._step+this.shift*1)*10000)/10000};dhtmlxSlider.prototype.setValue=function(val,skip){if(isNaN(val))return;this._def[3]=this.value=val-0;this.posX=(Math.round(((val||0)-this.shift)*this._mod))
this._applyPos(skip==null?true:skip)};dhtmlxSlider.prototype._getActionElement=function(nod){if(nod._etype)return nod;if(nod.parentNode)return this._getActionElement(nod.parentNode);return null};dhtmlxSlider.prototype._onMouseDown=function(e){if(this.that.disabled)return;e=e||event;var that=this.that;var nod=that._getActionElement(_isIE?e.srcElement:e.target);switch(nod._etype){case"slider":if(that.vMode)var z=e.clientY-(getAbsoluteTop(that.con)-document.body.scrollTop);else
var z=e.clientX-(getAbsoluteLeft(that.con)-document.body.scrollLeft);var posX=that.posX;that.posX=z-that.dragLeft-that.dragWidth/2;that.direction=that.posX>posX?1:-1;if(that.stepping){clearInterval(that._int);that.setValue(that.value+that._step*that.direction,false);that._int=setInterval(function(){that.setValue(that.value+that._step*that.direction,false)},600)}else
{that._busy=true;that._applyPos();that._busy=false};break;case"drag":that.startDrag(e||event);break};return false};dhtmlxSlider.prototype.setOnChangeHandler=function(func){this.attachEvent("onChange",func)};dhtmlxSlider.prototype._linkFrom=function(){if(this.disabled)return;this.setValue(parseFloat(this._link.value),false)};dhtmlxSlider.prototype.linkTo=function(obj){obj=(typeof(obj)!="object")?document.getElementById(obj):obj;this._link=obj;var name=obj.tagName.toString().toLowerCase();this._linkBoth=(((name=="input")||(name=="select")||(name=="textarea"))?1:0);if(this._linkBoth){var self=this;var f=function(){if(this._nextSlider)window.clearTimeout(this._nextSlider);this._nextSlider=window.setTimeout(function(){self._linkFrom()},500)};obj.onblur=obj.onkeypress=obj.onchange=f};this._applyPos()};dhtmlxSlider.prototype.enableTooltip=function(mode){this._dttp=(!convertStringToBoolean(mode));this._setTooltip(this._dttp?"":this.getValue())};dhtmlxSlider.prototype.setImagePath=function(path){this.imgURL=path};dhtmlxSlider.prototype.init=function(){this.isInit=true;this.createStructure()};dhtmlxSlider.prototype.setInputPriority=function(mode){this.inputPriority=mode};dhtmlxSlider.prototype.setSteppingMode=function(mode){this.stepping=mode};dhtmlxSlider.prototype.disable=function(mode){this.disabled=mode};(function(){dhtmlx.extend_api("dhtmlxSlider",{_init:function(obj){return[obj.parent,obj.size,obj.skin,obj.vertical,obj.min,obj.max,obj.value,obj.step]},link:"linkTo"},{})})();function dhx_init_sliders(){var z=document.getElementsByTagName("input");for(var i=0;i<z.length;i++)if(z[i].className=="dhtmlxSlider"){var n=z[i];var pos=n.getAttribute("position")||"over";var d=document.createElement("DIV");d.style.width=n.offsetWidth+"px";d.style.height=n.offsetHeight+"px";n.parentNode.insertBefore(d,n);if(pos=="over")n.style.display="none";else{var x=document.createElement("DIV");var w=Math.round(n.offsetWidth/3);if(w>50)w=50
x.style.width=n.offsetWidth-w+"px";d.style.position="relative";x.style[(pos=="left")?"right":"left"]=x.style.top=n.style.top=n.style[pos]="0px";x.style.position=n.style.position="absolute";n.style.width=w+"px";x.style.height=n.offsetHeight+"px";d.appendChild(n);d.appendChild(x);d=x};var l=new dhtmlxSlider(d,d.offsetWidth,(n.getAttribute("skin")||""),false,(n.getAttribute("min")||""),(n.getAttribute("max")||""),(n.value),(n.getAttribute("step")||""));l.linkTo(n);l.init()}};if(window.addEventListener)window.addEventListener("load",dhx_init_sliders,false);else if(window.attachEvent)window.attachEvent("onload",dhx_init_sliders);var jscolor={dir:'http://imgs.sapo.pt/fotos_gis/colorPicker/',bindClass:'color',binding:true,preloading:true,install:function(){jscolor.addEvent(window,'load',jscolor.init);},init:function(){if(jscolor.binding){jscolor.bind();}
if(jscolor.preloading){jscolor.preload();}},getDir:function(){if(!jscolor.dir){var detected=jscolor.detectDir();jscolor.dir=detected!==false?detected:'jscolor/';}
return jscolor.dir;},detectDir:function(){var base=location.href;var e=document.getElementsByTagName('base');for(var i=0;i<e.length;i+=1){if(e[i].href){base=e[i].href;}}
var e=document.getElementsByTagName('script');for(var i=0;i<e.length;i+=1){if(e[i].src&&/(^|\/)jscolor\.js([?#].*)?$/i.test(e[i].src)){var src=new jscolor.URI(e[i].src);var srcAbs=src.toAbsolute(base);srcAbs.path=srcAbs.path.replace(/[^\/]+$/,'');srcAbs.query=null;srcAbs.fragment=null;return srcAbs.toString();}}
return false;},bind:function(){var matchClass=new RegExp('(^|\\s)('+jscolor.bindClass+')\\s*(\\{[^}]*\\})?','i');var e=document.getElementsByTagName('input');for(var i=0;i<e.length;i+=1){var m;if(!e[i].color&&e[i].className&&(m=e[i].className.match(matchClass))){var prop={};if(m[3]){try{eval('prop='+m[3]);}catch(eInvalidProp){}}
e[i].color=new jscolor.color(e[i],prop);}}},preload:function(){for(var fn in jscolor.imgRequire){if(jscolor.imgRequire.hasOwnProperty(fn)){jscolor.loadImage(fn);}}},images:{pad:[181,101],sld:[16,101],cross:[15,15],arrow:[7,11]},imgRequire:{},imgLoaded:{},requireImage:function(filename){jscolor.imgRequire[filename]=true;},loadImage:function(filename){if(!jscolor.imgLoaded[filename]){jscolor.imgLoaded[filename]=new Image();jscolor.imgLoaded[filename].src=jscolor.getDir()+filename;}},fetchElement:function(mixed){return typeof mixed==='string'?document.getElementById(mixed):mixed;},addEvent:function(el,evnt,func){if(el.addEventListener){el.addEventListener(evnt,func,false);}else if(el.attachEvent){el.attachEvent('on'+evnt,func);}},fireEvent:function(el,evnt){if(!el){return;}
if(document.createEventObject){var ev=document.createEventObject();el.fireEvent('on'+evnt,ev);}else if(document.createEvent){var ev=document.createEvent('HTMLEvents');ev.initEvent(evnt,true,true);el.dispatchEvent(ev);}else if(el['on'+evnt]){el['on'+evnt]();}},getElementPos:function(e){var e1=e,e2=e;var x=0,y=0;if(e1.offsetParent){do{x+=e1.offsetLeft;y+=e1.offsetTop;}while(e1=e1.offsetParent);}
while((e2=e2.parentNode)&&e2.nodeName.toUpperCase()!=='BODY'){x-=e2.scrollLeft;y-=e2.scrollTop;}
return[x,y];},getElementSize:function(e){return[e.offsetWidth,e.offsetHeight];},getMousePos:function(e){if(!e){e=window.event;}
if(typeof e.pageX==='number'){return[e.pageX,e.pageY];}else if(typeof e.clientX==='number'){return[e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft,e.clientY+document.body.scrollTop+document.documentElement.scrollTop];}},getViewPos:function(){if(typeof window.pageYOffset==='number'){return[window.pageXOffset,window.pageYOffset];}else if(document.body&&(document.body.scrollLeft||document.body.scrollTop)){return[document.body.scrollLeft,document.body.scrollTop];}else if(document.documentElement&&(document.documentElement.scrollLeft||document.documentElement.scrollTop)){return[document.documentElement.scrollLeft,document.documentElement.scrollTop];}else{return[0,0];}},getViewSize:function(){if(typeof window.innerWidth==='number'){return[window.innerWidth,window.innerHeight];}else if(document.body&&(document.body.clientWidth||document.body.clientHeight)){return[document.body.clientWidth,document.body.clientHeight];}else if(document.documentElement&&(document.documentElement.clientWidth||document.documentElement.clientHeight)){return[document.documentElement.clientWidth,document.documentElement.clientHeight];}else{return[0,0];}},URI:function(uri){this.scheme=null;this.authority=null;this.path='';this.query=null;this.fragment=null;this.parse=function(uri){var m=uri.match(/^(([A-Za-z][0-9A-Za-z+.-]*)(:))?((\/\/)([^\/?#]*))?([^?#]*)((\?)([^#]*))?((#)(.*))?/);this.scheme=m[3]?m[2]:null;this.authority=m[5]?m[6]:null;this.path=m[7];this.query=m[9]?m[10]:null;this.fragment=m[12]?m[13]:null;return this;};this.toString=function(){var result='';if(this.scheme!==null){result=result+this.scheme+':';}
if(this.authority!==null){result=result+'//'+this.authority;}
if(this.path!==null){result=result+this.path;}
if(this.query!==null){result=result+'?'+this.query;}
if(this.fragment!==null){result=result+'#'+this.fragment;}
return result;};this.toAbsolute=function(base){var base=new jscolor.URI(base);var r=this;var t=new jscolor.URI;if(base.scheme===null){return false;}
if(r.scheme!==null&&r.scheme.toLowerCase()===base.scheme.toLowerCase()){r.scheme=null;}
if(r.scheme!==null){t.scheme=r.scheme;t.authority=r.authority;t.path=removeDotSegments(r.path);t.query=r.query;}else{if(r.authority!==null){t.authority=r.authority;t.path=removeDotSegments(r.path);t.query=r.query;}else{if(r.path===''){t.path=base.path;if(r.query!==null){t.query=r.query;}else{t.query=base.query;}}else{if(r.path.substr(0,1)==='/'){t.path=removeDotSegments(r.path);}else{if(base.authority!==null&&base.path===''){t.path='/'+r.path;}else{t.path=base.path.replace(/[^\/]+$/,'')+r.path;}
t.path=removeDotSegments(t.path);}
t.query=r.query;}
t.authority=base.authority;}
t.scheme=base.scheme;}
t.fragment=r.fragment;return t;};function removeDotSegments(path){var out='';while(path){if(path.substr(0,3)==='../'||path.substr(0,2)==='./'){path=path.replace(/^\.+/,'').substr(1);}else if(path.substr(0,3)==='/./'||path==='/.'){path='/'+path.substr(3);}else if(path.substr(0,4)==='/../'||path==='/..'){path='/'+path.substr(4);out=out.replace(/\/?[^\/]*$/,'');}else if(path==='.'||path==='..'){path='';}else{var rm=path.match(/^\/?[^\/]*/)[0];path=path.substr(rm.length);out=out+rm;}}
return out;}
if(uri){this.parse(uri);}},color:function(target,prop){this.required=true;this.adjust=true;this.hash=false;this.caps=true;this.valueElement=target;this.styleElement=target;this.hsv=[0,0,1];this.rgb=[1,1,1];this.pickerOnfocus=true;this.pickerMode='HSV';this.pickerPosition='bottom';this.pickerFace=10;this.pickerFaceColor='ThreeDFace';this.pickerBorder=1;this.pickerBorderColor='ThreeDHighlight ThreeDShadow ThreeDShadow ThreeDHighlight';this.pickerInset=1;this.pickerInsetColor='ThreeDShadow ThreeDHighlight ThreeDHighlight ThreeDShadow';this.pickerZIndex=10000;for(var p in prop){if(prop.hasOwnProperty(p)){this[p]=prop[p];}}
this.hidePicker=function(){if(isPickerOwner()){removePicker();}};this.showPicker=function(){if(!isPickerOwner()){var tp=jscolor.getElementPos(target);var ts=jscolor.getElementSize(target);var vp=jscolor.getViewPos();var vs=jscolor.getViewSize();var ps=[2*this.pickerBorder+4*this.pickerInset+2*this.pickerFace+jscolor.images.pad[0]+2*jscolor.images.arrow[0]+jscolor.images.sld[0],2*this.pickerBorder+2*this.pickerInset+2*this.pickerFace+jscolor.images.pad[1]];var a,b,c;switch(this.pickerPosition.toLowerCase()){case'left':a=1;b=0;c=-1;break;case'right':a=1;b=0;c=1;break;case'top':a=0;b=1;c=-1;break;default:a=0;b=1;c=1;break;}
var l=(ts[b]+ps[b])/2;var pp=[-vp[a]+tp[a]+ps[a]>vs[a]?(-vp[a]+tp[a]+ts[a]/2>vs[a]/2&&tp[a]+ts[a]-ps[a]>=0?tp[a]+ts[a]-ps[a]:tp[a]):tp[a],-vp[b]+tp[b]+ts[b]+ps[b]-l+l*c>vs[b]?(-vp[b]+tp[b]+ts[b]/2>vs[b]/2&&tp[b]+ts[b]-l-l*c>=0?tp[b]+ts[b]-l-l*c:tp[b]+ts[b]-l+l*c):(tp[b]+ts[b]-l+l*c>=0?tp[b]+ts[b]-l+l*c:tp[b]+ts[b]-l-l*c)];drawPicker(pp[a],pp[b]);}};this.importColor=function(){if(!valueElement){this.exportColor();}else{if(!this.adjust){if(!this.fromString(valueElement.value,leaveValue)){styleElement.style.backgroundColor=styleElement.jscStyle.backgroundColor;styleElement.style.color=styleElement.jscStyle.color;this.exportColor(leaveValue|leaveStyle);}}else if(!this.required&&/^\s*$/.test(valueElement.value)){valueElement.value='';styleElement.style.backgroundColor=styleElement.jscStyle.backgroundColor;styleElement.style.color=styleElement.jscStyle.color;this.exportColor(leaveValue|leaveStyle);}else if(this.fromString(valueElement.value)){}else{this.exportColor();}}};this.exportColor=function(flags){if(!(flags&leaveValue)&&valueElement){var value=this.toString();if(this.caps){value=value.toUpperCase();}
if(this.hash){value='#'+value;}
valueElement.value=value;}
if(!(flags&leaveStyle)&&styleElement){styleElement.style.backgroundColor='#'+this.toString();styleElement.style.color=0.213*this.rgb[0]+
0.715*this.rgb[1]+
0.072*this.rgb[2]<0.5?'#FFF':'#000';}
if(!(flags&leavePad)&&isPickerOwner()){redrawPad();}
if(!(flags&leaveSld)&&isPickerOwner()){redrawSld();}};this.fromHSV=function(h,s,v,flags){h<0&&(h=0)||h>6&&(h=6);s<0&&(s=0)||s>1&&(s=1);v<0&&(v=0)||v>1&&(v=1);this.rgb=HSV_RGB(h===null?this.hsv[0]:(this.hsv[0]=h),s===null?this.hsv[1]:(this.hsv[1]=s),v===null?this.hsv[2]:(this.hsv[2]=v));this.exportColor(flags);};this.fromRGB=function(r,g,b,flags){r<0&&(r=0)||r>1&&(r=1);g<0&&(g=0)||g>1&&(g=1);b<0&&(b=0)||b>1&&(b=1);var hsv=RGB_HSV(r===null?this.rgb[0]:(this.rgb[0]=r),g===null?this.rgb[1]:(this.rgb[1]=g),b===null?this.rgb[2]:(this.rgb[2]=b));if(hsv[0]!==null){this.hsv[0]=hsv[0];}
if(hsv[2]!==0){this.hsv[1]=hsv[1];}
this.hsv[2]=hsv[2];this.exportColor(flags);};this.fromString=function(hex,flags){var m=hex.match(/^\W*([0-9A-F]{3}([0-9A-F]{3})?)\W*$/i);if(!m){return false;}else{if(m[1].length===6){this.fromRGB(parseInt(m[1].substr(0,2),16)/255,parseInt(m[1].substr(2,2),16)/255,parseInt(m[1].substr(4,2),16)/255,flags);}else{this.fromRGB(parseInt(m[1].charAt(0)+m[1].charAt(0),16)/255,parseInt(m[1].charAt(1)+m[1].charAt(1),16)/255,parseInt(m[1].charAt(2)+m[1].charAt(2),16)/255,flags);}
return true;}};this.toString=function(){return((0x100|Math.round(255*this.rgb[0])).toString(16).substr(1)+
(0x100|Math.round(255*this.rgb[1])).toString(16).substr(1)+
(0x100|Math.round(255*this.rgb[2])).toString(16).substr(1));};function RGB_HSV(r,g,b){var n=Math.min(Math.min(r,g),b);var v=Math.max(Math.max(r,g),b);var m=v-n;if(m===0){return[null,0,v];}
var h=r===n?3+(b-g)/m:(g===n?5+(r-b)/m:1+(g-r)/m);return[h===6?0:h,m/v,v];}
function HSV_RGB(h,s,v){if(h===null){return[v,v,v];}
var i=Math.floor(h);var f=i%2?h-i:1-(h-i);var m=v*(1-s);var n=v*(1-s*f);switch(i){case 6:case 0:return[v,n,m];case 1:return[n,v,m];case 2:return[m,v,n];case 3:return[m,n,v];case 4:return[n,m,v];case 5:return[v,m,n];}}
function removePicker(){delete jscolor.picker.owner;document.getElementsByTagName('body')[0].removeChild(jscolor.picker.boxB);}
function drawPicker(x,y){if(!jscolor.picker){jscolor.picker={box:document.createElement('div'),boxB:document.createElement('div'),pad:document.createElement('div'),padB:document.createElement('div'),padM:document.createElement('div'),sld:document.createElement('div'),sldB:document.createElement('div'),sldM:document.createElement('div')};for(var i=0,segSize=4;i<jscolor.images.sld[1];i+=segSize){var seg=document.createElement('div');seg.style.height=segSize+'px';seg.style.fontSize='1px';seg.style.lineHeight='0';jscolor.picker.sld.appendChild(seg);}
jscolor.picker.sldB.appendChild(jscolor.picker.sld);jscolor.picker.box.appendChild(jscolor.picker.sldB);jscolor.picker.box.appendChild(jscolor.picker.sldM);jscolor.picker.padB.appendChild(jscolor.picker.pad);jscolor.picker.box.appendChild(jscolor.picker.padB);jscolor.picker.box.appendChild(jscolor.picker.padM);jscolor.picker.boxB.appendChild(jscolor.picker.box);}
var p=jscolor.picker;posPad=[x+THIS.pickerBorder+THIS.pickerFace+THIS.pickerInset,y+THIS.pickerBorder+THIS.pickerFace+THIS.pickerInset];posSld=[null,y+THIS.pickerBorder+THIS.pickerFace+THIS.pickerInset];p.box.onmouseup=p.box.onmouseout=function(){target.focus();};p.box.onmousedown=function(){abortBlur=true;};p.box.onmousemove=function(e){holdPad&&setPad(e);holdSld&&setSld(e);};p.padM.onmouseup=p.padM.onmouseout=function(){if(holdPad){holdPad=false;jscolor.fireEvent(valueElement,'change');}};p.padM.onmousedown=function(e){holdPad=true;setPad(e);};p.sldM.onmouseup=p.sldM.onmouseout=function(){if(holdSld){holdSld=false;jscolor.fireEvent(valueElement,'change');}};p.sldM.onmousedown=function(e){holdSld=true;setSld(e);};p.box.style.width=4*THIS.pickerInset+2*THIS.pickerFace+jscolor.images.pad[0]+2*jscolor.images.arrow[0]+jscolor.images.sld[0]+'px';p.box.style.height=2*THIS.pickerInset+2*THIS.pickerFace+jscolor.images.pad[1]+'px';p.boxB.style.position='absolute';p.boxB.style.clear='both';p.boxB.style.left=x+'px';p.boxB.style.top=y+'px';p.boxB.style.zIndex=THIS.pickerZIndex;p.boxB.style.border=THIS.pickerBorder+'px solid';p.boxB.style.borderColor=THIS.pickerBorderColor;p.boxB.style.background=THIS.pickerFaceColor;p.pad.style.width=jscolor.images.pad[0]+'px';p.pad.style.height=jscolor.images.pad[1]+'px';p.padB.style.position='absolute';p.padB.style.left=THIS.pickerFace+'px';p.padB.style.top=THIS.pickerFace+'px';p.padB.style.border=THIS.pickerInset+'px solid';p.padB.style.borderColor=THIS.pickerInsetColor;p.padM.style.position='absolute';p.padM.style.left='0';p.padM.style.top='0';p.padM.style.width=THIS.pickerFace+2*THIS.pickerInset+jscolor.images.pad[0]+jscolor.images.arrow[0]+'px';p.padM.style.height=p.box.style.height;p.padM.style.cursor='crosshair';p.sld.style.overflow='hidden';p.sld.style.width=jscolor.images.sld[0]+'px';p.sld.style.height=jscolor.images.sld[1]+'px';p.sldB.style.position='absolute';p.sldB.style.right=THIS.pickerFace+'px';p.sldB.style.top=THIS.pickerFace+'px';p.sldB.style.border=THIS.pickerInset+'px solid';p.sldB.style.borderColor=THIS.pickerInsetColor;p.sldM.style.position='absolute';p.sldM.style.right='0';p.sldM.style.top='0';p.sldM.style.width=jscolor.images.sld[0]+jscolor.images.arrow[0]+THIS.pickerFace+2*THIS.pickerInset+'px';p.sldM.style.height=p.box.style.height;try{p.sldM.style.cursor='pointer';}catch(eOldIE){p.sldM.style.cursor='hand';}
switch(modeID){case 0:var padImg='hs.png';break;case 1:var padImg='hv.png';break;}
p.padM.style.background="url('"+jscolor.getDir()+"cross.gif') no-repeat";p.sldM.style.background="url('"+jscolor.getDir()+"arrow.gif') no-repeat";p.pad.style.background="url('"+jscolor.getDir()+padImg+"') 0 0 no-repeat";redrawPad();redrawSld();jscolor.picker.owner=THIS;document.getElementsByTagName('body')[0].appendChild(p.boxB);}
function redrawPad(){switch(modeID){case 0:var yComponent=1;break;case 1:var yComponent=2;break;}
var x=Math.round((THIS.hsv[0]/6)*(jscolor.images.pad[0]-1));var y=Math.round((1-THIS.hsv[yComponent])*(jscolor.images.pad[1]-1));jscolor.picker.padM.style.backgroundPosition=(THIS.pickerFace+THIS.pickerInset+x-Math.floor(jscolor.images.cross[0]/2))+'px '+
(THIS.pickerFace+THIS.pickerInset+y-Math.floor(jscolor.images.cross[1]/2))+'px';var seg=jscolor.picker.sld.childNodes;switch(modeID){case 0:var rgb=HSV_RGB(THIS.hsv[0],THIS.hsv[1],1);for(var i=0;i<seg.length;i+=1){seg[i].style.backgroundColor='rgb('+
(rgb[0]*(1-i/seg.length)*100)+'%,'+
(rgb[1]*(1-i/seg.length)*100)+'%,'+
(rgb[2]*(1-i/seg.length)*100)+'%)';}
break;case 1:var rgb,s,c=[THIS.hsv[2],0,0];var i=Math.floor(THIS.hsv[0]);var f=i%2?THIS.hsv[0]-i:1-(THIS.hsv[0]-i);switch(i){case 6:case 0:rgb=[0,1,2];break;case 1:rgb=[1,0,2];break;case 2:rgb=[2,0,1];break;case 3:rgb=[2,1,0];break;case 4:rgb=[1,2,0];break;case 5:rgb=[0,2,1];break;}
for(var i=0;i<seg.length;i+=1){s=1-1/(seg.length-1)*i;c[1]=c[0]*(1-s*f);c[2]=c[0]*(1-s);seg[i].style.backgroundColor='rgb('+
(c[rgb[0]]*100)+'%,'+
(c[rgb[1]]*100)+'%,'+
(c[rgb[2]]*100)+'%)';}
break;}}
function redrawSld(){switch(modeID){case 0:var yComponent=2;break;case 1:var yComponent=1;break;}
var y=Math.round((1-THIS.hsv[yComponent])*(jscolor.images.sld[1]-1));jscolor.picker.sldM.style.backgroundPosition='0 '+(THIS.pickerFace+THIS.pickerInset+y-Math.floor(jscolor.images.arrow[1]/2))+'px';}
function isPickerOwner(){return jscolor.picker&&jscolor.picker.owner===THIS;}
function blurTarget(){if(valueElement===target){THIS.importColor();}
if(THIS.pickerOnfocus){THIS.hidePicker();}}
function blurValue(){if(valueElement!==target){THIS.importColor();}}
function setPad(e){var posM=jscolor.getMousePos(e);var x=posM[0]-posPad[0];var y=posM[1]-posPad[1];switch(modeID){case 0:THIS.fromHSV(x*(6/(jscolor.images.pad[0]-1)),1-y/(jscolor.images.pad[1]-1),null,leaveSld);break;case 1:THIS.fromHSV(x*(6/(jscolor.images.pad[0]-1)),null,1-y/(jscolor.images.pad[1]-1),leaveSld);break;}}
function setSld(e){var posM=jscolor.getMousePos(e);var y=posM[1]-posPad[1];switch(modeID){case 0:THIS.fromHSV(null,null,1-y/(jscolor.images.sld[1]-1),leavePad);break;case 1:THIS.fromHSV(null,1-y/(jscolor.images.sld[1]-1),null,leavePad);break;}}
var THIS=this;var modeID=this.pickerMode.toLowerCase()==='hvs'?1:0;var abortBlur=false;var
valueElement=jscolor.fetchElement(this.valueElement),styleElement=jscolor.fetchElement(this.styleElement);var
holdPad=false,holdSld=false;var
posPad,posSld;var
leaveValue=1<<0,leaveStyle=1<<1,leavePad=1<<2,leaveSld=1<<3;jscolor.addEvent(target,'focus',function(){if(THIS.pickerOnfocus){THIS.showPicker();}});jscolor.addEvent(target,'blur',function(){if(!abortBlur){window.setTimeout(function(){abortBlur||blurTarget();abortBlur=false;},0);}else{abortBlur=false;}});if(valueElement){var updateField=function(){THIS.fromString(valueElement.value,leaveValue);};jscolor.addEvent(valueElement,'keyup',updateField);jscolor.addEvent(valueElement,'input',updateField);jscolor.addEvent(valueElement,'blur',blurValue);valueElement.setAttribute('autocomplete','off');}
if(styleElement){styleElement.jscStyle={backgroundColor:styleElement.style.backgroundColor,color:styleElement.style.color};}
switch(modeID){case 0:jscolor.requireImage('hs.png');break;case 1:jscolor.requireImage('hv.png');break;}
jscolor.requireImage('cross.gif');jscolor.requireImage('arrow.gif');this.importColor();}};jscolor.install();SAPO.Maps.Control={};SAPO.Maps.Control.Stats={};SAPO.Maps.Popup={};SAPO.Maps.Markers={};SAPO.Maps.Marker={};SAPO.Maps.Handler={};SAPO.Maps.Overlay={};SAPO.Maps.Directions={};SAPO.Maps.Map=OpenLayers.Class(OpenLayers.Map,{baseLayers:{NORMAL_MAP:null,SATELLITE_MAP:null,HYBRID_MAP:null,TERRAIN_MAP:null,TERRITORY_MAP:null},unloadFirst:false,draggingenabled:true,zoomWheelEnabled:true,borders:null,outerBorders:null,markers:null,vectorLayer:null,dragControl:null,featureEventHandler:null,rightClicksControl:null,sapoSelectedBaseLayer:null,popup:null,messageBoardControl:null,beingDestroyed:false,NEW_EVENT_TYPES:['ondestroy'],initialize:function(container,opts){var defaultOpts={isDraggable:true,isWheelEnabled:true,borders:{left:0,top:0,bottom:0,right:0},outerBorders:{left:0,top:0,bottom:0,right:0},center:new OpenLayers.LonLat(-8.12714000,39.70453000),zoomLevel:4,layer:'m'};OpenLayers.Util.extend(defaultOpts,opts);this.borders=defaultOpts.borders;this.outerBorders=defaultOpts.outerBorders;this.unloadFirst=defaultOpts.unloadFirst;OpenLayers.Map.prototype.initialize.apply(this,[container,{tileSize:SAPO.Maps.Config.TILE_SIZE,controls:[new OpenLayers.Control.Navigation({handleRightClicks:true,borders:this.borders})],theme:null}]);var __SAPO_Layer_Opts={maxExtent:SAPO.Maps.Config.MAX_EXTENT,minResolution:SAPO.Maps.Config.MIN_RESOLUTION,maxResolution:SAPO.Maps.Config.MAX_RESOLUTION,resolutions:SAPO.Maps.Config.RESOLUTIONS,units:SAPO.Maps.Config.UNITS,numZoomLevels:SAPO.Maps.Config.NUMZOOMLEVELS,projection:SAPO.Maps.Config.PROJECTION,buffer:0};var __SAPO_Layer_Jpeg_Opts=OpenLayers.Util.extend({},__SAPO_Layer_Opts);__SAPO_Layer_Jpeg_Opts.format='image/jpeg';var __SAPO_TerrainLayer_Opts={maxExtent:SAPO.Maps.Config.MAX_EXTENT,minResolution:SAPO.Maps.Config.MIN_RESOLUTION_TERRAIN,maxResolution:SAPO.Maps.Config.MAX_RESOLUTION,resolutions:SAPO.Maps.Config.RESOLUTIONS_TERRAIN,units:SAPO.Maps.Config.UNITS,numZoomLevels:SAPO.Maps.Config.NUMZOOMLEVELS_TERRAIN,projection:SAPO.Maps.Config.PROJECTION,buffer:0};this.baseLayers={};this.baseLayers.NORMAL_MAP=new OpenLayers.Layer.TileCache('Map',SAPO.Maps.Config.WEB_SERVERS,'map',__SAPO_Layer_Opts);this.baseLayers.SATELLITE_MAP=new OpenLayers.Layer.TileCache('Satellite',SAPO.Maps.Config.WEB_SERVERS,'satellite',__SAPO_Layer_Jpeg_Opts);this.baseLayers.HYBRID_MAP={baseLayer:this.baseLayers.SATELLITE_MAP,labels:new OpenLayers.Layer.TileCache('Hybrid',SAPO.Maps.Config.WEB_SERVERS,'hybrid',__SAPO_Layer_Opts)};this.baseLayers.HYBRID_MAP.labels.transparent=true;this.baseLayers.HYBRID_MAP.labels.isBaseLayer=false;this.baseLayers.TERRAIN_MAP=new OpenLayers.Layer.TileCache('Terrain',SAPO.Maps.Config.WEB_SERVERS,'terrain',__SAPO_TerrainLayer_Opts);this.baseLayers.TERRITORY_MAP=new SAPO.Maps.Layer.Territory('Territory',SAPO.Maps.Config.WEB_SERVERS_TERRITORY,null,__SAPO_Layer_Opts);for(var e in this.baseLayers){var layer=this.baseLayers[e].baseLayer?this.baseLayers[e].baseLayer:this.baseLayers[e];this.addLayer(layer);}
var layers={m:this.baseLayers.NORMAL_MAP,s:this.baseLayers.SATELLITE_MAP,h:this.baseLayers.HYBRID_MAP,t:this.baseLayers.TERRAIN_MAP,tr:this.baseLayers.TERRITORY_MAP};this.setBaseLayer(layers[defaultOpts.layer]);this.setMapCenter(defaultOpts.center,defaultOpts.zoomLevel);OpenLayers.Map.prototype.addControl.apply(this,[new SAPO.Maps.Control.Scale()]);OpenLayers.Map.prototype.addControl.apply(this,[new SAPO.Maps.Control.PermanentLink()]);this.addListenersControls();if(defaultOpts.isDraggable===false){this.disableDragging();}
if(defaultOpts.isWheelEnabled===false){this.disableScrollWheelZoom();}
var event=false;for(var eventIdx=0;eventIdx<this.NEW_EVENT_TYPES.length;++eventIdx){event=this.NEW_EVENT_TYPES[eventIdx];this.events.addEventType(event);}
if(this.unloadFirst){OpenLayers.Event.stopObserving(window,'unload',this.unloadDestroy);OpenLayers.Event.observe(window,'beforeunload',this.unloadDestroy);}},destroy:function(){this.beingDestroyed=true;this.events.triggerEvent('ondestroy');if(this.unloadFirst){OpenLayers.Event.stopObserving(window,'beforeunload',this.unloadDestroy);}
this.events.unregister('addlayer',this,this.bringVectorLayerToTop);this.events.unregister('changelayer',this,this.bringVectorLayerToTop);this.events.unregister('removelayer',this,this.bringVectorLayerToTop);OpenLayers.Map.prototype.destroy.apply(this,arguments);},addListenersControls:function(){var vlayer=this.getOverlaysContainer();this.dragControl=new SAPO.Maps.Control.DragFeature(vlayer);this.featureEventHandler=new SAPO.Maps.Control.FeatureEventHandlers(vlayer);this.addControl(this.dragControl);this.addControl(this.featureEventHandler);this.dragControl.activate();this.featureEventHandler.activate();this.events.addEventType('singlerightclick');this.rightClicksControl=new SAPO.Maps.Control.RightClicks({singlerightclick:{func:this.events.triggerEvent,context:this.events,params:['singlerightclick']},dblrightclick:{func:this.events.triggerEvent,context:this.events,params:['dblrightclick']}});this.addControl(this.rightClicksControl);},isValidZoomLevel:function(zoomLevel){var valid=OpenLayers.Map.prototype.isValidZoomLevel.apply(this,[zoomLevel]);return(zoomLevel>=SAPO.Maps.Config.MIN_ZOOM)&&valid;},checkIsADefinedBaseLayer:function(layer){for(var l in this.baseLayers){if(this.baseLayers[l]==layer){return true;}}
return false;},setBaseLayer:function(newBaseLayer){if(this.sapoSelectedBaseLayer){if(this.sapoSelectedBaseLayer.labels){OpenLayers.Map.prototype.removeLayer.apply(this,[this.sapoSelectedBaseLayer.labels]);}}
this.sapoSelectedBaseLayer=null;var layer=newBaseLayer;if(this.checkIsADefinedBaseLayer(newBaseLayer)===true&&newBaseLayer.baseLayer){layer=newBaseLayer.baseLayer;if(newBaseLayer.labels){this.sapoSelectedBaseLayer=newBaseLayer;this.addLayer(newBaseLayer.labels);newBaseLayer.labels.setZIndex(Number(newBaseLayer.baseLayer.getZIndex()));}}
OpenLayers.Map.prototype.setBaseLayer.apply(this,[layer]);},getBaseLayers:function(){return this.baseLayers;},enableDragging:function(){this.draggingenabled=true;var controls=this.getControlsByClass('OpenLayers.Control.Navigation');for(var i=0;i<controls.length;++i){controls[i].activate();}},disableDragging:function(){this.draggingenabled=false;var controls=this.getControlsByClass('OpenLayers.Control.Navigation');for(var i=0;i<controls.length;++i){controls[i].deactivate();}},draggingEnabled:function(){return this.draggingenabled;},enableScrollWheelZoom:function(){this.zoomWheelEnabled=true;var controls=this.getControlsByClass('OpenLayers.Control.Navigation');for(var i=0;i<controls.length;++i){controls[i].enableZoomWheel();}},disableScrollWheelZoom:function(){this.zoomWheelEnabled=false;var controls=this.getControlsByClass('OpenLayers.Control.Navigation');for(var i=0;i<controls.length;++i){controls[i].disableZoomWheel();}},scrollWheelZoomEnabled:function(){return this.zoomWheelEnabled;},addLayer:function(layer){var _newlayer=layer;if(this.checkIsADefinedBaseLayer(layer)===true&&layer.baselayer){_newlayer=layer.baselayer;}
OpenLayers.Map.prototype.addLayer.apply(this,[_newlayer]);},removeLayer:function(layer,setNewBaseLayer){if(this.checkIsADefinedBaseLayer(layer)===true&&layer.baselayer){if(layer.labels){OpenLayers.Map.prototype.removeLayer.apply(this,[layer.labels,setNewBaseLayer]);}
OpenLayers.Map.prototype.removeLayer.apply(this,[layer.baselayer,setNewBaseLayer]);return;}
OpenLayers.Map.prototype.removeLayer.apply(this,arguments);},createVectorLayer:function(){this.vectorLayer=new OpenLayers.Layer.Vector('SAPO.Maps.Overlays.Layer',{rendererOptions:{zIndexing:true}});this.events.register('addlayer',this,this.bringVectorLayerToTop);this.events.register('changelayer',this,this.bringVectorLayerToTop);this.events.register('removelayer',this,this.bringVectorLayerToTop);this.addLayer(this.vectorLayer);},bringVectorLayerToTop:function(evt){var newLayer=evt.layer;if(!newLayer.div||!this.vectorLayer.div){return;}
if(Number(newLayer.getZIndex())>Number(this.vectorLayer.getZIndex())){this.vectorLayer.setZIndex(Number(newLayer.getZIndex())+1);}},addMarkers:function(markers){var vlayer=this.getOverlaysContainer();markers.setMap(this);},addOverlay:function(overlay){var vlayer=this.getOverlaysContainer();var feature=overlay.getFeature();feature.overlay=overlay;vlayer.addFeatures([feature]);overlay.setLayer(vlayer);},removeOverlay:function(overlay){var feature=overlay.getFeature();this.vectorLayer.removeFeatures([feature]);overlay.removed();},removeMarkers:function(markers){markers.unloadLayer();},getOverlaysContainer:function(){if(!this.vectorLayer){this.createVectorLayer();}
return this.vectorLayer;},convertFormat:function(format){format.externalProjection=new OpenLayers.Projection("EPSG:4326");format.internalProjection=new OpenLayers.Projection("EPSG:900913");return format;},getLonLatFromContainerPixel:function(px){var lonlat=OpenLayers.Map.prototype.getLonLatFromPixel.apply(this,[px]);return lonlat.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));},getContainerPixelFromLonLat:function(lonlat){var coords=lonlat.clone().transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));return OpenLayers.Map.prototype.getViewPortPxFromLonLat.apply(this,[coords]);},getBounds:function(){var size=this.getSize();var topLeft=this.getLonLatFromContainerPixel(new OpenLayers.Pixel(0,0));var bottomRight=this.getLonLatFromContainerPixel(new OpenLayers.Pixel(size.w,size.h));return new OpenLayers.Bounds(topLeft.lon,bottomRight.lat,bottomRight.lon,topLeft.lat);},setBounds:function(bounds,closest){var bbox=bounds.clone().transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));closest=closest?closest:false;this.zoomToExtent(bbox,closest);},setBorders:function(borders,outerBorders){this.borders=OpenLayers.Util.extend(this.borders,borders);this.getControlsByClass('OpenLayers.Control.Navigation').borders=this.borders;if(outerBorders){this.outerBorders=outerBorders;if(this.messageBoardControl&&outerBorders){this.messageBoardControl.setBorders(outerBorders);}}},getMapCenter:function(){var center=OpenLayers.Map.prototype.getCenter.apply(this,arguments);if(center){var lonlat=center.clone();return lonlat.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));}
return null;},setMapCenter:function(lonlat,zoom){if(zoom&&zoom<4){zoom=4;}
var coords=lonlat.clone();coords.transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));OpenLayers.Map.prototype.setCenter.apply(this,[coords,zoom]);},openPopup:function(lonlat,content){var newLonLat=lonlat.transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));this.popup=new SAPO.Maps.Popup.SapoPopup(null,newLonLat,null,content,true,function(){this.closePopup();}.bindObj(this),this.options.popupAnchor,this.borders,true);this.addPopup(this.popup,false);},closePopup:function(){if(this.popup){this.removePopup(this.popup);this.popup=null;}},getMessageBoardControl:function(){if(!this.messageBoardControl){this.messageBoardControl=new SAPO.Maps.Control.MessageBoardControl(this.outerBorders);this.addControl(this.messageBoardControl);}
return this.messageBoardControl;},CLASS_NAME:'SAPO.Maps.Map'});(function(){var type=(window.SVGAngle||document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")?"SVG":"VML");var svg,vml;svg=!(vml=type=="VML");if(vml){document.createStyleSheet().addRule(".patch_vml","behavior:url(#default#VML)");if(!document.namespaces.patch_vml){document.namespaces.add("patch_vml","urn:schemas-microsoft-com:vml");}}})();OpenLayers.ImgPath='http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/openlayers_imgs/';SAPO.Maps.Config={WEB_SERVERS:['http://map1.mapas.sapo.pt/images','http://map2.mapas.sapo.pt/images','http://map3.mapas.sapo.pt/images','http://map4.mapas.sapo.pt/images','http://map5.mapas.sapo.pt/images','http://map6.mapas.sapo.pt/images','http://map7.mapas.sapo.pt/images','http://map8.mapas.sapo.pt/images'],WEB_SERVERS_TERRITORY:['http://map1.mapas.sapo.pt/images/territory','http://map2.mapas.sapo.pt/images/territory','http://map3.mapas.sapo.pt/images/territory','http://map4.mapas.sapo.pt/images/territory','http://map5.mapas.sapo.pt/images/territory','http://map6.mapas.sapo.pt/images/territory','http://map7.mapas.sapo.pt/images/territory','http://map8.mapas.sapo.pt/images/territory'],MAX_EXTENT:new OpenLayers.Bounds(-20037508.3427892,-20037508.3427892,20037508.3427892,20037508.3427892),MIN_RESOLUTION:0.29858214168548586,MIN_RESOLUTION_TERRAIN:19.109257067871095,MAX_RESOLUTION:9783.9396187500006,RESOLUTIONS:[156543.03390000001,78271.516950000005,39135.758475000002,19567.879237500001,9783.9396187500006,4891.9698093750003,2445.9849046875001,1222.9924523437501,611.49622617187504,305.74811308593752,152.87405654296876,76.43702827148438,38.21851413574219,19.109257067871095,9.5546285339355475,4.7773142669677737,2.3886571334838869,1.1943285667419434,0.59716428337097172,0.29858214168548586],RESOLUTIONS_TERRAIN:[156543.03390000001,78271.516950000005,39135.758475000002,19567.879237500001,9783.9396187500006,4891.9698093750003,2445.9849046875001,1222.9924523437501,611.49622617187504,305.74811308593752,152.87405654296876,76.43702827148438,38.21851413574219,19.109257067871095,9.5546285339355475],UNITS:'m',NUMZOOMLEVELS:16,NUMZOOMLEVELS_TERRAIN:11,MIN_ZOOM:4,PROJECTION:new OpenLayers.Projection("EPSG:900913"),TILE_SIZE:new OpenLayers.Size(256,256)};SAPO.Maps.Lang={pt:{map:'Mapa',satellite:'Sat&eacute;lite',hybrid:'H&iacute;brido',terrain:'Terreno',territoryDivisions:'Territorial',territoryDivisionsConfig:'Configura&ccedil;&atilde;o',directions_first_step_description:'Siga por ',directions_step_forward:'Continue',directions_step_forward_description:'Continue para ',directions_step_left:'Vire &agrave; esquerda',directions_step_left_description:'Vire &agrave; esquerda para ',directions_step_right:'Vire &agrave; direita',directions_step_right_description:'Vire &agrave; direita para ',directions_go:'Siga',directions_to:'por',show_map:'Ver mapa',distance:'Dist&acirc;ncia',estimated_time:'Tempo Estimado'},en:{map:'Map',satellite:'Satellite',hybrid:'Hybrid',terrain:'Terrain',territoryDivisions:'Territory',territoryDivisionsConfig:'Configuration',directions_first_step_description:'Go through ',directions_step_forward:'Continue',directions_step_forward_description:'Continue to ',directions_step_left:'Turn left',directions_step_left_description:'Turn left to ',directions_step_right:'Turn right',directions_step_right_description:'Turn right to ',directions_go:'Go',directions_to:'to',show_map:'Show map',distance:'Distance',estimated_time:'Estimated Time'}};SAPO.Maps.Handler.Feature=OpenLayers.Class(OpenLayers.Handler,{EVENTMAP:{'click':{'in':'click','out':'clickout'},'rightclick':{'in':'rightclick','out':null},'mousemove':{'in':'over','out':'out'},'dblclick':{'in':'dblclick','out':null},'mousedown':{'in':'mousedown','out':null},'mouseup':{'in':'mouseup','out':'out'}},layer:null,feature:null,lastFeature:null,lastMouseMoveEvent:null,ignoreInterval:null,periodicInterval:null,down:null,up:null,clickoutTolerance:4,geometryTypes:null,stopClick:true,stopDown:true,stopUp:false,initialize:function(control,layer,callbacks,options){OpenLayers.Handler.prototype.initialize.apply(this,[control,callbacks,options]);this.layer=layer;this.lastMouseMoveEvent={};this.numExecutors=0;},mousedown:function(evt){this.down=evt.xy;return this.handle(evt)?!this.stopDown:true;},mouseup:function(evt){if(evt&&evt.button===2){this.rightclick(evt);return;}
this.up=evt.xy;return this.handle(evt)?!this.stopUp:true;},click:function(evt){return this.handle(evt)?!this.stopClick:true;},rightclick:function(evt){return this.handle(evt)?!this.stopClick:true;},mousemove:function(evt){if(!this.callbacks.over&&!this.callbacks.out){return true;}
this.handle(evt);return true;},dealMousemove:function(){if(this.myevt.type=="mousemove"){OpenLayers.Util.extend(this.lastMouseMoveEvent,this.myevt);}
this.handle(this.myevt);window.clearTimeout(this.periodicInterval);this.periodicInterval=null;return true;},dblclick:function(evt){return!this.handle(evt);},geometryTypeMatches:function(feature){return!this.geometryTypes||OpenLayers.Util.indexOf(this.geometryTypes,feature.geometry.CLASS_NAME)>-1;},handle:function(evt){var type=evt.type;if(type==='mouseup'&&evt.button===2){type='rightclick';}
var handled=false;var previouslyIn=!!(this.feature);var click=(type==='click'||type==='dblclick'||type==='mousedown'||type==='mouseup'||type==='rightclick');this.feature=this.layer.getFeatureFromEvent(evt);if(this.feature){var inNew=(this.feature!=this.lastFeature);if(this.geometryTypeMatches(this.feature)){if(previouslyIn&&inNew){this.triggerCallback(type,'out',[this.lastFeature]);this.triggerCallback(type,'in',[this.feature]);}else if(!previouslyIn||click){this.triggerCallback(type,'in',[this.feature]);}
this.lastFeature=this.feature;handled=true;}else{if(previouslyIn&&inNew||(click&&this.lastFeature)){this.triggerCallback(type,'out',[this.lastFeature]);}
this.feature=null;}}else{if(previouslyIn||(click&&this.lastFeature)){this.triggerCallback(type,'out',[this.lastFeature]);}}
return handled;},getFeatureFromEvent:function(evt){var features=this.control.features;if(!features){return null;}
var featureToReturn=[];var feature;var point;var latlon;for(var i=features.length-1;i>=0;--i){feature=features[i];if(this.control.CLASS_NAME=="SAPO.Maps.Control.FeatureEventHandlers"){if(evt.type=="mousedown"||evt.type=="mouseup"||evt.type=="click"){if(!feature._events.click&&!feature._events.dblclick&&!feature._events.mousedown&&!feature._events.mouseup){continue;}}
if(evt.type=="mousemove"){if(!feature._events.mouseover&&!feature._events.mouseout){continue;}}}
if(feature.geometry.CLASS_NAME=="OpenLayers.Geometry.Point"){if(this.intersectsPoint(evt.xy,feature)){featureToReturn.push(feature);if(evt.type=="mousemove"){break;}}}
else{if(feature.geometry.CLASS_NAME=="OpenLayers.Geometry.LineString"){if(this.intersectsLine(evt.xy,feature)){featureToReturn.push(feature);if(evt.type=="mousemove"){break;}}}
else{lonlat=feature.layer.getLonLatFromViewPortPx(evt.xy);point=new OpenLayers.Geometry.Point(lonlat.lon,lonlat.lat);if(!point){continue;}
if(feature.geometry.intersects(point)){featureToReturn.push(feature);if(evt.type=="mousemove"){break;}}}}}
if(featureToReturn.length===0){return null;}
if(featureToReturn.length===1){return featureToReturn[0];}
var upperFeature=featureToReturn[0];for(var j=1;j<featureToReturn.length;++j){if(Number(featureToReturn[j].layer.getZIndex())>Number(upperFeature.layer.getZIndex())){upperFeature=featureToReturn[j];}}
return upperFeature;},intersectsPoint:function(point,feature){if(!point.x||!point.y){return false;}
var xy=feature.layer.getViewPortPxFromLonLat(new OpenLayers.LonLat(feature.geometry.x,feature.geometry.y));if(feature.style&&feature.style.graphicWidth&&feature.style.graphicHeight){var width=feature.style.graphicWidth;var height=feature.style.graphicHeight;xy.x+=feature.style.graphicXOffset?feature.style.graphicXOffset+width/2:width/2;xy.y+=feature.style.graphicYOffset?feature.style.graphicYOffset+height/2:height/2;var edges={top:xy.y+height/2,right:xy.x+width/2,bottom:xy.y-height/2,left:xy.x-width/2};if(point.x<=edges.right&&point.x>=edges.left&&point.y<=edges.top&&point.y>=edges.bottom){return true;}}
else{if(feature.style&&feature.style.graphicXOffset&&feature.style.graphicYOffset){xy.x+=feature.style.graphicXOffset?feature.style.graphicXOffset/2:0;xy.y+=feature.style.graphicYOffset?feature.style.graphicYOffset/2:0;}
var radius=null;if(feature.style){radius=feature.style.pointRadius?feature.style.pointRadius:OpenLayers.Feature.Vector.style['default'].pointRadius;}
else{radius=OpenLayers.Feature.Vector.style['default'].pointRadius;}
if(Math.abs(point.x-xy.x)<=radius&&Math.abs(point.y-xy.y)<=radius){return true;}}},intersectsLine:function(point,feature){if(!point.x||!point.y){return false;}
var segments=feature.geometry.getSortedSegments();var x1,y1,x2,y2;var px=point.x;var py=point.y;var xy;var distance=-1;var strokeWidth=null;for(i in segments){xy=feature.layer.getViewPortPxFromLonLat(new OpenLayers.LonLat(segments[i].x1,segments[i].y1));x1=xy.x;y1=xy.y;xy=feature.layer.getViewPortPxFromLonLat(new OpenLayers.LonLat(segments[i].x2,segments[i].y2));x2=xy.x;y2=xy.y;distance=this.distanceBetweenLineAndPoint(x1,y1,x2,y2,px,py,feature.style.strokeWidth/2);if(feature.style){strokeWidth=feature.style.strokeWidth?feature.style.strokeWidth:OpenLayers.Feature.Vector.style['default'].strokeWidth;}
else{strokeWidth=OpenLayers.Feature.Vector.style['default'].strokeWidth;}
if(distance!=-1&&distance<strokeWidth/2){return true;}}
return false;},distanceBetweenLineAndPoint:function(x1,y1,x2,y2,px,py,offset){if(px<(Math.min(x1,x2)-offset)){return-1;}
if(px>(Math.max(x1,x2)+offset)){return-1;}
if(py<(Math.min(y1,y2)-offset)){return-1;}
if(py>(Math.max(y1,y2)+offset)){return-1;}
var u=(px-x1)*(x2-x1)+(py-y1)*(y2-y1);u/=Math.pow((x2-x1),2)+Math.pow((y2-y1),2);var px_=x1+u*(x2-x1);var py_=y1+u*(y2-y1);var distance=Math.sqrt(Math.pow(px_-px,2)+Math.pow(py_-py,2));return distance;},triggerCallback:function(type,mode,args){if(!this.EVENTMAP[type]){return;}
var key=this.EVENTMAP[type][mode];if(key){if(type=='click'&&mode=='out'&&this.up&&this.down){var dpx=Math.sqrt(Math.pow(this.up.x-this.down.x,2)+
Math.pow(this.up.y-this.down.y,2));if(dpx<=this.clickoutTolerance){this.callback(key,args);}}else{this.callback(key,args);}}},regenerateMouseMoveEvent:function(evt){if(this.lastMouseMoveEvent.xy){this.mousemove(this.lastMouseMoveEvent);return true;}},activate:function(byControl){var activated=false;if(OpenLayers.Handler.prototype.activate.apply(this,arguments)){this.moveLayerToTop();this.map.events.on({"removelayer":this.handleMapEvents,"changelayer":this.handleMapEvents,scope:this});activated=true;}
if(!this.registeredEvent){this.map.events.register("zoomend",this,this.regenerateMouseMoveEvent);this.registeredEvent=true;}
return activated;},deactivate:function(byControl){var deactivated=false;if(OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){this.moveLayerBack();this.down=null;this.up=null;this.map.events.un({"removelayer":this.handleMapEvents,"changelayer":this.handleMapEvents,scope:this});deactivated=true;}
return deactivated;},handleMapEvents:function(evt){if(!evt.property||evt.property=="order"){this.moveLayerToTop();}},moveLayerToTop:function(){},moveLayerBack:function(){},CLASS_NAME:"SAPO.Maps.Handler.Feature"});SAPO.Maps.Control.MapType=OpenLayers.Class(OpenLayers.Control,{_controlWidth:250,donotupdate:false,selected:null,pixel:null,language:null,initialize:function(language){this.language='pt';if(language&&SAPO.Maps.Lang[language]){this.language=language;}},destroy:function(){this.map.events.unregister("changebaselayer",this,this.updateLayerBt);for(var i=0;i<this.div.childNodes.length;++i){OpenLayers.Event.stopObservingElement(this.div.childNodes[i]);}
OpenLayers.Control.prototype.destroy.apply(this,arguments);},draw:function(px){OpenLayers.Control.prototype.draw.apply(this,arguments);var _this=this;var mapbt=document.createElement("div");var satellitebt=document.createElement("div");var hybridbt=document.createElement("div");mapbt.innerHTML=SAPO.Maps.Lang[this.language].map;satellitebt.innerHTML=SAPO.Maps.Lang[this.language].satellite;hybridbt.innerHTML=SAPO.Maps.Lang[this.language].hybrid;var layers=this.map.getBaseLayers();mapbt.layer=layers.NORMAL_MAP;satellitebt.layer=layers.SATELLITE_MAP;hybridbt.layer=layers.HYBRID_MAP;OpenLayers.Event.observe(this.div,"mousedown",function(e){OpenLayers.Event.stop(e);});OpenLayers.Event.observe(this.div,"dblclick",function(e){OpenLayers.Event.stop(e);});OpenLayers.Event.observe(mapbt,"click",function(e){_this.changeBaseLayer(e,mapbt,_this.map.getBaseLayers().NORMAL_MAP);});OpenLayers.Event.observe(satellitebt,"click",function(e){_this.changeBaseLayer(e,satellitebt,_this.map.getBaseLayers().SATELLITE_MAP);});OpenLayers.Event.observe(hybridbt,"click",function(e){_this.changeBaseLayer(e,hybridbt,_this.map.getBaseLayers().HYBRID_MAP);});this.map.events.register("changebaselayer",this,this.updateLayerBt);if(!px){this.div.style.right="35px";this.div.style.top="5px";}
else{this.pixel=px;}
mapbt.className='status_btn_smapi_MapTypeControl2';satellitebt.className='status_btn_smapi_MapTypeControl2';hybridbt.className='status_btn_smapi_MapTypeControl2';this.checkIE6(mapbt,false);this.checkIE6(satellitebt,false);this.checkIE6(hybridbt,false);this.div.appendChild(mapbt);this.div.appendChild(hybridbt);this.div.appendChild(satellitebt);this.updateLayerBt();return this.div;},changeBaseLayer:function(evt,clickedElem,layer){OpenLayers.Event.stop(evt);if(!this.map||(this.map.baseLayer===layer||this.map.baseLayer===layer.baseLayer)&&!(this.map.baseLayer===this.map.baseLayers.SATELLITE_MAP&&layer.labels&&!this.map.sapoSelectedBaseLayer||this.map.sapoSelectedBaseLayer&&layer===this.map.baseLayers.SATELLITE_MAP)){return;}
this.selected.className="status_btn_smapi_MapTypeControl2";this.checkIE6(this.selected,false);this.selected=clickedElem;clickedElem.className="status_btn_smapi_MapTypeControl2 status_btn_checked_smapi_MapTypeControl2";this.checkIE6(this.selected,true);this.donotupdate=true;this.map.setBaseLayer(layer);},updateLayerBt:function(){if(this.donotupdate){this.donotupdate=false;return;}
if(this.selected){this.selected.className="status_btn_smapi_MapTypeControl2";this.checkIE6(this.selected,false);}
var base=this.map.baseLayer;for(var i=0;i<this.div.childNodes.length;++i){if(base===this.div.childNodes[i].layer||base===this.div.childNodes[i].layer.baseLayer){this.selected=this.div.childNodes[i];this.selected.className="status_btn_smapi_MapTypeControl2 status_btn_checked_smapi_MapTypeControl2";this.checkIE6(this.selected,true);break;}}},checkIE6:function(elem,selected){if(OpenLayers.Util.getBrowserName()!='msie'){return;}
var ie_version=parseFloat(navigator.appVersion.split("MSIE")[1]);if(ie_version>=7){return;}
elem.className+=' status_btn_smapi_MapTypeControl2_if_ie6';if(selected){elem.className+=' status_btn_checked_smapi_MapTypeControl2_if_ie6';}},CLASS_NAME:"SAPO.Maps.Control.MapType"});SAPO.Maps.Control.MapType2=OpenLayers.Class(OpenLayers.Control,{_controlWidth:250,_hybrid_shown:false,_hybrid_state:1,donotupdate:false,selected:null,pixel:null,territoryBt:false,windowManger:null,territoryPanel:null,territoryConfigurationPanel:null,territoryConfigurationPanelActive:false,language:null,listeners:null,layers_bts:null,expand2hybridDiv:null,expand2satelliteDiv:null,expand2territoryConfDiv:null,elements:null,EVENT_TYPES:["activate","deactivate","mapselected","hybridselected","satelliteselected","terrainselected","territoryselected","panelvisibilitychanged"],initialize:function(language,options){OpenLayers.Control.prototype.initialize.apply(this,[options]);this.language='pt';if(language&&SAPO.Maps.Lang[language]){this.language=language;}
if(this.territoryConfigurationPanel!==null&&typeof(this.territoryConfigurationPanel)==="string"){this.territoryConfigurationPanel=document.getElementById(this.territoryConfigurationPanel);}
this.elements={};},destroy:function(){OpenLayers.Control.prototype.destroy.apply(this,arguments);this.elements=null;},getTerritoryPanel:function(){return this.territoryPanel;},draw:function(px){OpenLayers.Control.prototype.draw.apply(this,arguments);var holder=document.createElement('div');var map=document.createElement('div');var satellite_hybrid=document.createElement('div');var satellite=document.createElement('div');var hybrid=document.createElement('div');var terrain=document.createElement('div');var territoryDivisions_configuration=document.createElement('div');var territoryDivisions=document.createElement('div');var territoryConfiguration=document.createElement('div');var expand2hybrid=document.createElement('span');var expand2satellite=document.createElement('span');var expand2territoryConfig=document.createElement('span');this.expand2hybridDiv=document.createElement('div');this.expand2satelliteDiv=document.createElement('div');this.expand2territoryConfDiv=document.createElement('div');map.innerHTML="<a href='#'>"+SAPO.Maps.Lang[this.language].map+"</a><span>&nbsp;</span>";satellite.innerHTML="<a href='#'>"+SAPO.Maps.Lang[this.language].satellite+"</a>";hybrid.innerHTML="<a href='#'>"+SAPO.Maps.Lang[this.language].hybrid+"</a>";terrain.innerHTML="<a href='#'>"+SAPO.Maps.Lang[this.language].terrain+"</a><span>&nbsp;</span>";territoryDivisions.innerHTML="<a href='#' style='width:57px'>"+SAPO.Maps.Lang[this.language].territoryDivisions+"</a>";territoryConfiguration.innerHTML="<a href='#' style='width:75px'>"+SAPO.Maps.Lang[this.language].territoryDivisionsConfig+"</a><span style='width:10px'>&nbsp;</span>";territoryConfiguration._visible=false;expand2hybrid.appendChild(this.expand2hybridDiv);expand2satellite.appendChild(this.expand2satelliteDiv);expand2territoryConfig.appendChild(this.expand2territoryConfDiv);SAPO.Maps.Utils.addClassName(holder,'mapict_viewController');SAPO.Maps.Utils.addClassName(holder,'mapict_viewController');this.checkIE6AndAddStyle(map,'mapict_viewbtn','mapict_viewbtn_ie6');this.checkIE6AndAddStyle(satellite_hybrid,'mapict_viewbtn','mapict_viewbtn_ie6');this.checkIE6AndAddStyle(satellite_hybrid,'multioption_view','multioption_view_ie6');this.checkIE6AndAddStyle(terrain,'mapict_viewbtn','mapict_viewbtn_ie6');this.checkIE6AndAddStyle(territoryDivisions_configuration,'mapict_viewbtn','mapict_viewbtn_ie6');this.checkIE6AndAddStyle(territoryDivisions_configuration,'multioption_view','multioption_view_ie6');SAPO.Maps.Utils.addClassName(territoryConfiguration,'hide');SAPO.Maps.Utils.addClassName(territoryConfiguration,'mapict_config_button');SAPO.Maps.Utils.addClassName(satellite,'hide');this.checkIE6AndAddStyle(satellite,'unselected_item','unselected_item_ie6');this.expand2hybridDiv.style.display='none';map.event='mapselected';hybrid.event='mapselected';satellite.event='mapselected';terrain.event='mapselected';territoryDivisions.event='territoryselected';var layers=this.map.getBaseLayers();OpenLayers.Event.observe(this.div,"mousedown",OpenLayers.Event.stop);OpenLayers.Event.observe(this.div,"dblclick",OpenLayers.Event.stop);var _this=this;this.listeners={map:OpenLayers.Function.bind(this.changeBaseLayer,this,map,layers.NORMAL_MAP),satellite:OpenLayers.Function.bind(this.changeBaseLayer,this,satellite,layers.SATELLITE_MAP),hybrid:OpenLayers.Function.bind(this.changeBaseLayer,this,hybrid,layers.HYBRID_MAP),terrain:OpenLayers.Function.bind(this.changeBaseLayer,this,terrain,layers.TERRAIN_MAP),territory:OpenLayers.Function.bind(this.changeBaseLayer,this,territoryDivisions,layers.TERRITORY_MAP),expandhybrid:OpenLayers.Function.bind(this.toggleMenu,this,hybrid),expandsatellite:OpenLayers.Function.bind(this.toggleMenu,this,satellite),expandTerritoryConfig:OpenLayers.Function.bind(this.toggleTerritoryConfigButton,this,territoryConfiguration),showConfigurationPanel:OpenLayers.Function.bind(this.toggleTerritoryConfigurationPanel,this,territoryConfiguration)};this.elements.territoryConfigurationButton=territoryConfiguration;this.layers_bts={NORMAL_MAP:map,SATELLITE_MAP:satellite,HYBRID_MAP:hybrid,TERRAIN_MAP:terrain,TERRITORY_MAP:territoryDivisions,SATELLITE_HYBRID_MAP:satellite_hybrid};OpenLayers.Event.observe(map,"click",this.listeners.map);OpenLayers.Event.observe(satellite_hybrid,"click",this.listeners.satellite);OpenLayers.Event.observe(hybrid,"click",this.listeners.hybrid);OpenLayers.Event.observe(terrain,"click",this.listeners.terrain);OpenLayers.Event.observe(territoryDivisions,"click",this.listeners.territory);OpenLayers.Event.observe(this.expand2hybridDiv,"click",this.listeners.expandhybrid);OpenLayers.Event.observe(this.expand2satelliteDiv,"click",this.listeners.expandsatellite);OpenLayers.Event.observe(this.expand2territoryConfDiv,"click",this.listeners.expandTerritoryConfig);OpenLayers.Event.observe(territoryConfiguration,"click",this.listeners.showConfigurationPanel);this.map.events.register("changebaselayer",this,this.updateLayerBt);holder.appendChild(map);holder.appendChild(satellite_hybrid);holder.appendChild(terrain);if(this.territoryBt){territoryDivisions.appendChild(expand2territoryConfig);territoryDivisions_configuration.appendChild(territoryDivisions);territoryDivisions_configuration.appendChild(territoryConfiguration);holder.appendChild(territoryDivisions_configuration);this.territoryPanel=new SAPO.Maps.Renderer.TerritoryPanel(this.map.baseLayers.TERRITORY_MAP,this.territoryConfigurationPanel,this.windowManger);}
hybrid.appendChild(expand2satellite);satellite.appendChild(expand2hybrid);satellite_hybrid.appendChild(hybrid);satellite_hybrid.appendChild(satellite);this.div.appendChild(holder);this.updateLayerBt();if(!px){this.div.style.right="32px";this.div.style.top="5px";}
else{this.pixel=px;}
return this.div;},toggleMenu:function(button,evt){if(evt){OpenLayers.Event.stop(evt);}
this._hybrid_shown=!this._hybrid_shown;var remove=this._hybrid_shown?"hide":"show";var add=this._hybrid_shown?"show":"hide";SAPO.Maps.Utils.removeClassName(button,remove);SAPO.Maps.Utils.addClassName(button,add);},toggleTerritoryConfigButton:function(button,evt){if(evt){OpenLayers.Event.stop(evt);}
var remove=button._visible?"show":"hide";var add=button._visible?"hide":"show";SAPO.Maps.Utils.removeClassName(button,remove);SAPO.Maps.Utils.addClassName(button,add);button._visible=!button._visible;},selectTerritoryConfigButton:function(){SAPO.Maps.Utils.addClassName(this.elements.territoryConfigurationButton,"active_view");this.territoryConfigurationPanelActive=true;},unselectTerritoryConfigButton:function(){SAPO.Maps.Utils.removeClassName(this.elements.territoryConfigurationButton,"active_view");this.territoryConfigurationPanelActive=false;},toggleTerritoryConfigurationPanel:function(button){if(this.territoryConfigurationPanelActive){SAPO.Maps.Utils.removeClassName(button,"active_view");this.territoryPanel.hide();this.events.triggerEvent("panelvisibilitychanged",{visible:false});this.territoryConfigurationPanelActive=false;}
else{if(!this.territoryPanel.isDrawn()){this.territoryPanel.draw();}
this.territoryPanel.show();SAPO.Maps.Utils.addClassName(button,"active_view");this.events.triggerEvent("panelvisibilitychanged",{visible:true});this.territoryConfigurationPanelActive=true;this.map.setBaseLayer(this.map.getBaseLayers().TERRITORY_MAP);}
window.setTimeout(function(){this.toggleTerritoryConfigButton(button);}.bindObj(this),1000);},swapElements:function(hybrid,satellite){var remove=this._hybrid_state===0?satellite:hybrid;var parent=remove.parentNode;parent.removeChild(remove);parent.appendChild(remove);var divToShow=this._hybrid_state===0?this.expand2satelliteDiv:this.expand2hybridDiv;var divToHide=this._hybrid_state===0?this.expand2hybridDiv:this.expand2satelliteDiv;divToShow.style.display="block";divToHide.style.display="none";this._hybrid_state=this._hybrid_state===0?1:0;},changeBaseLayer:function(clickedElem,layer,evt,updateUI){if(evt){OpenLayers.Event.stop(evt);}
if(!this.map||(this.map.baseLayer===layer||this.map.baseLayer===layer.baseLayer)&&!updateUI&&!(this.map.baseLayer===this.map.baseLayers.SATELLITE_MAP&&layer.labels&&!this.map.sapoSelectedBaseLayer||this.map.sapoSelectedBaseLayer&&layer===this.map.baseLayers.SATELLITE_MAP)){return;}
if(this.selected){this.checkIE6AndRemoveStyle(this.selected,'active_view','active_view_ie6');}
if(clickedElem===this.layers_bts.SATELLITE_MAP||clickedElem===this.layers_bts.HYBRID_MAP)
{this.selected=this.layers_bts.SATELLITE_HYBRID_MAP;var elemToAddClassName=clickedElem===this.layers_bts.SATELLITE_MAP?this.layers_bts.HYBRID_MAP:this.layers_bts.SATELLITE_MAP;var elemToRemoveClassName=clickedElem===this.layers_bts.SATELLITE_MAP?this.layers_bts.SATELLITE_MAP:this.layers_bts.HYBRID_MAP;this.checkIE6AndAddStyle(elemToAddClassName,'unselected_item','unselected_item_ie6');this.checkIE6AndRemoveStyle(elemToRemoveClassName,'unselected_item','unselected_item_ie6');if((clickedElem===this.layers_bts.HYBRID_MAP&&this._hybrid_state===0)||(clickedElem===this.layers_bts.SATELLITE_MAP&&this._hybrid_state===1))
{if(!this._hybrid_shown){var elemToOpen=this._hybrid_state===0?this.layers_bts.HYBRID_MAP:this.layers_bts.SATELLITE_MAP;this.toggleMenu(elemToOpen);}
this.swapElements(this.layers_bts.HYBRID_MAP,this.layers_bts.SATELLITE_MAP);}}else{this.selected=clickedElem;}
this.checkIE6AndAddStyle(this.selected,'active_view','active_view_ie6');if(this._hybrid_shown){var elem=this._hybrid_state===0?this.layers_bts.HYBRID_MAP:this.layers_bts.SATELLITE_MAP;this.toggleMenu(elem);}
if(!updateUI){this.events.triggerEvent(clickedElem.event);this.donotupdate=true;this.map.setBaseLayer(layer);if(layer==this.map.baseLayer.TERRITORY_MAP){this.toggleTerritoryConfigurationPanel(this.elements.territoryConfigurationButton);}}},updateLayerBt:function(){if(this.donotupdate){this.donotupdate=false;return;}
var layers=this.map.getBaseLayers();for(var e in this.layers_bts){if(this.map.baseLayer===layers[e]){if(this.map.sapoSelectedBaseLayer){e='HYBRID_MAP';}
var elem=this.layers_bts[e];var layer=layers[e];if(!layer){continue;}
this.changeBaseLayer(elem,layer,null,true);break;}}},checkIE6AndAddStyle:function(elem,className,classNameIe6){if(SAPO.Maps.Utils.checkIE6()){SAPO.Maps.Utils.addClassName(elem,classNameIe6);}else{SAPO.Maps.Utils.addClassName(elem,className);}},checkIE6AndRemoveStyle:function(elem,className,classNameIe6){if(SAPO.Maps.Utils.checkIE6()){SAPO.Maps.Utils.removeClassName(elem,classNameIe6);}else{SAPO.Maps.Utils.removeClassName(elem,className);}},CLASS_NAME:'SAPO.Maps.Control.MapType2'});SAPO.Maps.Control.MapTypeTerrain=OpenLayers.Class(OpenLayers.Control,{_controlWidth:250,donotupdate:false,selected:null,pixel:null,language:null,initialize:function(language){this.language='pt';if(language&&SAPO.Maps.Lang[language]){this.language=language;}},destroy:function(){this.map.events.unregister("changebaselayer",this,this.updateLayerBt);for(var i=0;i<this.div.childNodes.length;++i){OpenLayers.Event.stopObservingElement(this.div.childNodes[i]);}
OpenLayers.Control.prototype.destroy.apply(this,arguments);},draw:function(px){OpenLayers.Control.prototype.draw.apply(this,arguments);var _this=this;var mapbt=document.createElement("div");var satellitebt=document.createElement("div");var hybridbt=document.createElement("div");var terrainbt=document.createElement("div");mapbt.innerHTML=SAPO.Maps.Lang[this.language].map;satellitebt.innerHTML=SAPO.Maps.Lang[this.language].satellite;hybridbt.innerHTML=SAPO.Maps.Lang[this.language].hybrid;terrainbt.innerHTML=SAPO.Maps.Lang[this.language].terrain;var layers=this.map.getBaseLayers();mapbt.layer=layers.NORMAL_MAP;satellitebt.layer=layers.SATELLITE_MAP;hybridbt.layer=layers.HYBRID_MAP;terrainbt.layer=layers.TERRAIN_MAP;OpenLayers.Event.observe(this.div,"mousedown",function(e){OpenLayers.Event.stop(e);});OpenLayers.Event.observe(this.div,"dblclick",function(e){OpenLayers.Event.stop(e);});OpenLayers.Event.observe(mapbt,"click",function(e){_this.changeBaseLayer(e,mapbt,_this.map.getBaseLayers().NORMAL_MAP);});OpenLayers.Event.observe(satellitebt,"click",function(e){_this.changeBaseLayer(e,satellitebt,_this.map.getBaseLayers().SATELLITE_MAP);});OpenLayers.Event.observe(hybridbt,"click",function(e){_this.changeBaseLayer(e,hybridbt,_this.map.getBaseLayers().HYBRID_MAP);});OpenLayers.Event.observe(terrainbt,"click",function(e){_this.changeBaseLayer(e,terrainbt,_this.map.getBaseLayers().TERRAIN_MAP);});this.map.events.register("changebaselayer",this,this.updateLayerBt);if(!px){this.div.style.right="35px";this.div.style.top="5px";}
else{this.pixel=px;}
mapbt.className='status_btn_smapi_MapTypeControl2';satellitebt.className='status_btn_smapi_MapTypeControl2';hybridbt.className='status_btn_smapi_MapTypeControl2';terrainbt.className='status_btn_smapi_MapTypeControl2';this.checkIE6(mapbt,false);this.checkIE6(satellitebt,false);this.checkIE6(hybridbt,false);this.checkIE6(terrainbt,false);this.div.appendChild(mapbt);this.div.appendChild(hybridbt);this.div.appendChild(satellitebt);this.div.appendChild(terrainbt);this.updateLayerBt();return this.div;},changeBaseLayer:function(evt,clickedElem,layer){OpenLayers.Event.stop(evt);if(!this.map||(this.map.baseLayer===layer||this.map.baseLayer===layer.baseLayer)&&!(this.map.baseLayer===this.map.baseLayers.SATELLITE_MAP&&layer.labels&&!this.map.sapoSelectedBaseLayer||this.map.sapoSelectedBaseLayer&&layer===this.map.baseLayers.SATELLITE_MAP)){return;}
this.selected.className="status_btn_smapi_MapTypeControl2";this.checkIE6(this.selected,false);this.selected=clickedElem;clickedElem.className="status_btn_smapi_MapTypeControl2 status_btn_checked_smapi_MapTypeControl2";this.checkIE6(this.selected,true);this.donotupdate=true;this.map.setBaseLayer(layer);},updateLayerBt:function(){if(this.donotupdate){this.donotupdate=false;return;}
if(this.selected){this.selected.className="status_btn_smapi_MapTypeControl2";this.checkIE6(this.selected,false);}
var base=this.map.baseLayer;for(var i=0;i<this.div.childNodes.length;++i){if(base===this.div.childNodes[i].layer||base===this.div.childNodes[i].layer.baseLayer){this.selected=this.div.childNodes[i];this.selected.className="status_btn_smapi_MapTypeControl2 status_btn_checked_smapi_MapTypeControl2";this.checkIE6(this.selected,true);break;}}},checkIE6:function(elem,selected){if(OpenLayers.Util.getBrowserName()!='msie'){return;}
var ie_version=parseFloat(navigator.appVersion.split("MSIE")[1]);if(ie_version>=7){return;}
elem.className+=' status_btn_smapi_MapTypeControl2_if_ie6';if(selected){elem.className+=' status_btn_checked_smapi_MapTypeControl2_if_ie6';}},CLASS_NAME:"SAPO.Maps.Control.MapType"});SAPO.Maps.Control.PermanentLink=OpenLayers.Class(OpenLayers.Control,{_link:"http://mapas.sapo.pt",_images:["http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/PermanentLinkControl/sapo_black.png","http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/PermanentLinkControl/sapo_white.png"],_controlWidth:100,_controlHeight:23,initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,[options]);},draw:function(px){OpenLayers.Control.prototype.draw.apply(this,arguments);var div_img=document.createElement("div");var img=document.createElement("img");var imgSrc=this.map.baseLayer===this.map.getBaseLayers().NORMAL_MAP?this._images[0]:this._images[1];img.src=imgSrc;div_img.style.width=this._controlWidth+"px";div_img.style.height=this._controlHeight+"px";div_img.onclick=function(e){window.open(this._link);if(!e){e=window.event;}
OpenLayers.Event.stop(e);}.bindObj(this);div_img.style.cursor="pointer";this.div.style.right="5px";this.div.style.bottom="5px";div_img.appendChild(img);this.div.appendChild(div_img);this.map.events.register("changebaselayer",this,function(e){var imgSrc=this.map.baseLayer===this.map.getBaseLayers().NORMAL_MAP||this.map.baseLayer===this.map.getBaseLayers().TERRAIN_MAP||this.map.baseLayer===this.map.getBaseLayers().ADMINISTRATIVE_MAP?this._images[0]:this._images[1];img.src=imgSrc;});return this.div;},CLASS_NAME:"SAPO.Maps.Control.PermanentLink"});SAPO.Maps.Control.Scale=OpenLayers.Class(OpenLayers.Control,{_controlHeight:20,_scaleBarWidth:81,_boundsIP:null,_boundsMadeira:null,_images:["http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/ScaleControl/mapas_escala.gif","http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/ScaleControl/mapas_escalaw.gif"],initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,[options]);this._boundsIP=[new OpenLayers.Bounds(-8.7110358,41.3772515,-8.5400064,41.7372256),new OpenLayers.Bounds(-8.85,40.3868612,-8.5104144,41.3767354),new OpenLayers.Bounds(-8.5124119,40.2975049,-8.1335597,40.6575257),new OpenLayers.Bounds(-8.9094,40.2059518,-8.6973301,40.3859),new OpenLayers.Bounds(-9.5146903,38.40109,-9.0657679,39.6749520),new OpenLayers.Bounds(-9.0359352,39.0346679,-8.7802692,39.1237121),new OpenLayers.Bounds(-9.0878811,38.7644567,-8.7778166,39.0334726),new OpenLayers.Bounds(-9.0843785,38.4040238,-8.7974915,38.7632771)];this._boundsMadeira=[new OpenLayers.Bounds(-16.412055,32.993953,-16.257602,33.128362),new OpenLayers.Bounds(-17.326109,32.399939,-16.381284,32.886769)];},draw:function(px){OpenLayers.Control.prototype.draw.apply(this,arguments);this.div.className+=" Sapo_Control_ScaleControl_div";var span_leftnr=document.createElement("span");span_leftnr.className="Sapo_Control_ScaleControl_leftnr";var span_rightnr=document.createElement("span");span_rightnr.className="Sapo_Control_ScaleControl_rightnr";var span_credits=document.createElement("span");span_credits.className="Sapo_Control_ScaleControl_credits";var img_bar=document.createElement("img");var distance=this._getDistance();span_leftnr.innerHTML="0";span_rightnr.innerHTML=distance>1.0?(distance.toFixed(0))+"km":((distance*1000)).toFixed(0)+"m";if(this.map.baseLayer===this.map.getBaseLayers().NORMAL_MAP||this.map.baseLayer===this.map.getBaseLayers().TERRAIN_MAP||this.map.baseLayer===this.map.getBaseLayers().TERRITORY){img_bar.src=this._images[0];this.div.style.color="black";}
else{img_bar.src=this._images[1];this.div.style.color="white";}
span_credits.innerHTML=this.getCredits();this.div.style.left="5px";this.div.style.bottom="5px";this.div.appendChild(span_leftnr);this.div.appendChild(img_bar);this.div.appendChild(span_rightnr);this.div.appendChild(span_credits);this.map.events.register("changebaselayer",this,function(e){if(this.map.baseLayer===this.map.getBaseLayers().NORMAL_MAP||this.map.baseLayer===this.map.getBaseLayers().TERRAIN_MAP||this.map.baseLayer===this.map.getBaseLayers().TERRITORY){this.div.style.color="black";img_bar.src=this._images[0];}
else{this.div.style.color="white";img_bar.src=this._images[1];}});this.map.events.register("moveend",this,function(e){var distance=this._getDistance();span_rightnr.innerHTML=distance>1.0?(distance.toFixed(0))+"km":((distance*1000)).toFixed(0)+"m";span_credits.innerHTML=this.getCredits();});return this.div;},_getDistance:function(start,end){var center_x=Math.round(this.map.getSize().w/2);var center_y=Math.round(this.map.getSize().h/2);var startPointPx=new OpenLayers.Pixel(center_x,center_y);var endPointPx=startPointPx.add(this._scaleBarWidth,0);var startPoint=this.map.getLonLatFromContainerPixel(startPointPx);var endPoint=this.map.getLonLatFromContainerPixel(endPointPx);var distance=OpenLayers.Util.distVincenty(startPoint,endPoint);return distance;},getCredits:function(){var date=new Date();var start=date.getTime();var year="&copy;"+(new Date()).getFullYear();var igp_ip=year+" Infoportugal, IGP/DGRF";var nasa=year+" NASA ";var ip=year+" Infoportugal";var intersectiveBounds=[];if(this.map.baseLayer==this.map.getBaseLayers().NORMAL_MAP){if(this.map.getZoom()<7){return year+" SAPO";}
else{return year+" SAPO"+" - Dados do mapa "+year+" Infoportugal";}}
else{if(this.map.getZoom()<12){if(this.map.baseLayer==this.map.getBaseLayers().SATELLITE_MAP&&this.map.sapoSelectedBaseLayer){if(this.map.getZoom()<7){return year+" SAPO"+" - Imagens "+year+" NASA";}
else{return year+" SAPO"+" - Dados do mapa "+year+" Infoportugal; Imagens "+year+" NASA";}}
else{return year+" SAPO"+" - Imagens "+year+" NASA";}}
var mapBounds=this.map.getBounds();for(var i=0;i<this._boundsIP.length;++i){if(mapBounds.intersectsBounds(this._boundsIP[i])){intersectiveBounds.push(this._boundsIP[i]);}}
if(intersectiveBounds.length>0){var area=0,tmpBounds=new OpenLayers.Bounds(0,0,0,0);for(var j=0;j<intersectiveBounds.length;++j){if(intersectiveBounds[j].containsBounds(mapBounds)){if(this.map.baseLayer==this.map.getBaseLayers().SATELLITE_MAP&&this.map.sapoSelectedBaseLayer){return year+" SAPO"+" - Dados do mapa "+year+" Infoportugal; Imagens "+year+" Infoportugal";}
else{return year+" SAPO"+" - Imagens "+year+" Infoportugal";}}
tmpBounds.left=intersectiveBounds[j].left<mapBounds.left?mapBounds.left:intersectiveBounds[j].left;tmpBounds.top=intersectiveBounds[j].top>mapBounds.top?mapBounds.top:intersectiveBounds[j].top;tmpBounds.bottom=intersectiveBounds[j].bottom<mapBounds.bottom?mapBounds.bottom:intersectiveBounds[j].bottom;tmpBounds.right=intersectiveBounds[j].right>mapBounds.right?mapBounds.right:intersectiveBounds[j].right;area+=tmpBounds.toGeometry().getArea();}
if(area>=mapBounds.toGeometry().getArea()){if(this.map.baseLayer==this.map.getBaseLayers().SATELLITE_MAP&&this.map.sapoSelectedBaseLayer){return year+" SAPO"+" - Dados do mapa "+year+" Infoportugal; Imagens "+year+" Infoportugal";}
else{return year+" SAPO"+" - Imagens "+year+" Infoportugal";}}
else{if(this.map.baseLayer==this.map.getBaseLayers().SATELLITE_MAP&&this.map.sapoSelectedBaseLayer){return year+" SAPO"+" - Dados do mapa "+year+" Infoportugal; Imagens "+year+" Infoportugal, IGP/DGRF";}
else{return year+" SAPO"+" - Imagens "+year+" Infoportugal, IGP/DGRF";}}}
else{var madeiraInBounds=false;for(var k=0;k<this._boundsMadeira.length;++k){if(mapBounds.intersectsBounds(this._boundsMadeira[k])){madeiraInBounds=true;break;}}
var provider=madeiraInBounds?" IRIG Madeira":" IGP/DGRF";if(this.map.baseLayer==this.map.getBaseLayers().SATELLITE_MAP&&this.map.sapoSelectedBaseLayer){return year+" SAPO"+" - Dados do mapa "+year+" Infoportugal; Imagens "+year+provider;}
else{return year+" SAPO"+" - Imagens "+year+provider;}}}},CLASS_NAME:"SAPO.Maps.Control.Scale"});SAPO.Maps.Control.MiniMap=OpenLayers.Class(OpenLayers.Control,{element:null,ovmap:null,size:new OpenLayers.Size(127,102),layers:null,minRectSize:15,minRectDisplayClass:"RectReplacement",minRatio:15,maxRatio:15,mapOptions:null,autoPan:true,handlers:null,resolutionFactor:1,listeners:null,opening:false,isMinimized:true,initialize:function(options){this.layers=[];this.handlers={};OpenLayers.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.holderMapDiv.removeChild(this.mapDiv);this.mapDiv=null;this.element.removeChild(this.holderMapDiv);this.holderMapDiv=null;this.div.removeChild(this.element);this.element=null;if(this.maximizeDiv){OpenLayers.Event.stopObservingElement(this.maximizeDiv);this.div.removeChild(this.maximizeDiv);this.maximizeDiv=null;}
if(this.minimizeDiv){OpenLayers.Event.stopObservingElement(this.minimizeDiv);this.div.removeChild(this.minimizeDiv);this.minimizeDiv=null;}
this.map.events.un({"moveend":this.update,"changebaselayer":this.baseLayerDraw,scope:this});this.map.events.unregister("changebaselayer",this,this.changeLayer);this.map.events.unregister("addlayer",this,this.addLayer);this.map.events.unregister("removelayer",this,this.removeLayer);OpenLayers.Control.prototype.destroy.apply(this,arguments);},changeLayer:function(){var newLayer=this.map.baseLayer.clone();this.ovmap.addLayer(newLayer);this.ovmap.setBaseLayer(newLayer);var layerToRemove=this.ovmap.layers[0];this.ovmap.removeLayer(layerToRemove,false);layerToRemove.map=this.ovmap;},addLayer:function(evt){if(this.map.sapoSelectedBaseLayer&&this.map.sapoSelectedBaseLayer.labels===evt.layer){var newLayer=evt.layer.clone();this.ovmap.addLayer(newLayer);}},removeLayer:function(evt){if(this.map.sapoSelectedBaseLayer&&this.map.sapoSelectedBaseLayer.labels===evt.layer){var layerToRemove=null;for(var i=0;i<this.ovmap.layers.length;++i){if(this.ovmap.layers[i].layername==='hybrid'){layerToRemove=this.ovmap.layers[i];}}
if(layerToRemove){this.ovmap.removeLayer(layerToRemove);}}},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);this.map.events.register("changebaselayer",this,this.changeLayer);this.map.events.register("addlayer",this,this.addLayer);this.map.events.register("removelayer",this,this.removeLayer);if(!(this.layers.length>0)){if(this.map.baseLayer){var layer=this.map.baseLayer.clone();layer.loadTilesTimer=null;this.layers=[layer];if(this.map.sapoSelectedBaseLayer){this.layers.push(this.map.sapoSelectedBaseLayer.labels.clone());}}else{this.map.events.register("changebaselayer",this,this.baseLayerDraw);return this.div;}}
this.element=document.createElement('div');this.element.className=this.displayClass+'Element';var ie_version=parseFloat(navigator.appVersion.split("MSIE")[1]);if(ie_version<7){this.element.className=this.displayClass+'Element_ie6';}
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.holderMapDiv=document.createElement('div');this.holderMapDiv.style.overflow='hidden';this.holderMapDiv.style.position='relative';this.holderMapDiv.appendChild(this.mapDiv);this.extentRectangle=document.createElement('div');this.extentRectangle.style.zIndex=1000;this.extentRectangle.className=this.displayClass+'ExtentRectangle';this.mapDiv.appendChild(this.extentRectangle);this.element.appendChild(this.holderMapDiv);this.div.appendChild(this.element);if(!this.outsideViewport){this.div.className+=" "+this.displayClass+'Container';var imgLocation=OpenLayers.Util.getImagesLocation();var img='http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/MiniMap/mini_map_off.png';this.maximizeDiv=OpenLayers.Util.createAlphaImageDiv(this.displayClass+'MaximizeButton',null,new OpenLayers.Size(32,32),img,'absolute');this.maximizeDiv.style.display='none';this.maximizeDiv.className=this.displayClass+'MaximizeButton';OpenLayers.Event.observe(this.maximizeDiv,'mouseup',OpenLayers.Function.bindAsEventListener(this.maximizeControl,this));this.div.appendChild(this.maximizeDiv);img='http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/MiniMap/mini_map_on.png';this.minimizeDiv=OpenLayers.Util.createAlphaImageDiv('OpenLayers_Control_minimizeDiv',null,new OpenLayers.Size(32,32),img,'absolute');this.minimizeDiv.style.display='none';this.minimizeDiv.className=this.displayClass+'MinimizeButton';OpenLayers.Event.observe(this.minimizeDiv,'mouseup',OpenLayers.Function.bindAsEventListener(this.minimizeControl,this));this.div.appendChild(this.minimizeDiv);var eventsToStop=['dblclick','mousedown'];for(var i=0,len=eventsToStop.length;i<len;i++){OpenLayers.Event.observe(this.maximizeDiv,eventsToStop[i],OpenLayers.Event.stop);OpenLayers.Event.observe(this.minimizeDiv,eventsToStop[i],OpenLayers.Event.stop);}
if(!this.isMinimized){this.showToggle(false,false);}else{this.maximizeDiv.style.display='';}}else{this.element.style.display='';}
if(this.map.getExtent()){this.update();this.ovmap.viewPortDiv.style.position="static";}
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();},maximizeControl:function(e){this.showToggle(false,true);if(e!==null){OpenLayers.Event.stop(e);}},minimizeControl:function(e){this.showToggle(true,true);if(e){OpenLayers.Event.stop(e);}},isOpened:function(){return!this.isMinimized;},showToggle:function(minimize,animation){this.isMinimized=minimize;if(!minimize){this.update();}
if(!this.opening&&!animation){this.maximizeDiv.style.display=minimize?'':'none';this.minimizeDiv.style.display=minimize?'none':'';this.element.style.display=minimize?'none':'';return;}
if(this.opening){return;}
if(!this.ovmap){this.element.style.display=minimize?'none':'';this.maximizeDiv.style.display=minimize?'':'none';this.minimizeDiv.style.display=minimize?'none':'';return;}
var nrSteps=3;var w=0,h=0;var delta_w=0,delta_h=0;if(!minimize){this.element.style.display='block';}
w=this.ovmap.div.offsetWidth;h=this.ovmap.div.offsetHeight;delta_w=Math.ceil(w/nrSteps);delta_h=Math.ceil(h/nrSteps);if(minimize){delta_w*=-1;delta_h*=-1;}else{this.holderMapDiv.style.width="0px";this.holderMapDiv.style.height="0px";}
var curr_w=minimize?w:0;var curr_h=minimize?h:0;var _this=this;this.opening=true;var interval=setInterval(function(){curr_w+=delta_w;curr_h+=delta_h;if(!minimize&&(curr_w>w||curr_h>h)||minimize&&(curr_w<0||curr_h<0)){_this.holderMapDiv.style.width=w+"px";_this.holderMapDiv.style.height=h+"px";_this.element.style.display=minimize?'none':'';_this.maximizeDiv.style.display=minimize?'':'none';_this.minimizeDiv.style.display=minimize?'none':'';w=minimize?0:w;h=minimize?0:h;_this.notifyOpenAndCloseListeners(new OpenLayers.Pixel(w,h));_this.opening=false;clearInterval(interval);return;}
_this.holderMapDiv.style.width=curr_w+"px";_this.holderMapDiv.style.height=curr_h+"px";_this.notifyOpenAndCloseListeners(new OpenLayers.Pixel(curr_w,curr_h));},5);},update:function(){if(this.ovmap&&!this.isOpened()){return;}
if(!this.ovmap){this.createMap();}
if(!this.isSuitableOverview()||this.autoPan){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));if(this.ovmap.getProjection()!==this.map.getProjection()){testExtent=testExtent.transform(this.map.getProjectionObject(),this.ovmap.getProjectionObject());}
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;}
var center;if(this.ovmap.getProjection()!==this.map.getProjection()){center=this.map.center.clone();center.transform(this.map.getProjectionObject(),this.ovmap.getProjectionObject());}else{center=this.map.center;}
this.ovmap.setCenter(center,this.ovmap.getZoomForResolution(targetRes*this.resolutionFactor));this.updateRectToMap();},createMap:function(){var options=OpenLayers.Util.extend({controls:[],maxResolution:'auto',fallThrough:false,theme:null},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=Number(OpenLayers.Element.getStyle(this.extentRectangle,'border-left-width'))+
Number(OpenLayers.Element.getStyle(this.extentRectangle,'border-right-width'));this.wComp=(this.wComp)?this.wComp:2;this.hComp=Number(OpenLayers.Element.getStyle(this.extentRectangle,'border-top-width'))+
Number(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();}});if(this.ovmap.getProjection()!==this.map.getProjection()){var sourceUnits=this.map.getProjectionObject().getUnits()||this.map.units||this.map.baseLayer.units;var targetUnits=this.ovmap.getProjectionObject().getUnits()||this.ovmap.units||this.ovmap.baseLayer.units;this.resolutionFactor=sourceUnits&&targetUnits?OpenLayers.INCHES_PER_UNIT[sourceUnits]/OpenLayers.INCHES_PER_UNIT[targetUnits]:1;}},updateRectToMap:function(){var bounds;if(this.ovmap.getProjection()!==this.map.getProjection()){bounds=this.map.getExtent().transform(this.map.getProjectionObject(),this.ovmap.getProjectionObject());}else{bounds=this.map.getExtent();}
var pxBounds=this.getRectBoundsFromMapBounds(bounds);if(pxBounds){this.setRectPxBounds(pxBounds);}},updateMapToRect:function(){var lonLatBounds=this.getMapBoundsFromRectBounds(this.rectPxBounds);if(this.ovmap.getProjection()!==this.map.getProjection()){lonLatBounds=lonLatBounds.transform(this.ovmap.getProjectionObject(),this.map.getProjectionObject());}
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;},OpenAndCloseListener:function(func,context){if(!this.listeners){this.listeners=[];}
var obj={'func':func,'context':context};this.listeners.push(obj);},OpenAndCloseStopListening:function(func,context){if(!this.listeners){return false;}
var obj=false;for(var i=0;i<this.listeners.length;++i){obj=this.listeners[i];if(obj.func==func&&obj.context==context){this.listeners.splice(i,1);return true;}}
return false;},notifyOpenAndCloseListeners:function(px){if(!this.listeners){return;}
for(var i=0;i<this.listeners.length;++i){this.listeners[i].func.apply(this.listeners[i].context,[px]);}},CLASS_NAME:'SAPO.Maps.Control.MiniMap'});SAPO.Maps.Control.MiniMap2=OpenLayers.Class(OpenLayers.Control,{element:null,ovmap:null,size:new OpenLayers.Size(127,102),layers:null,minRectSize:15,minRectDisplayClass:"RectReplacement",minRatio:15,maxRatio:15,mapOptions:null,autoPan:true,handlers:null,resolutionFactor:1,listeners:null,opening:false,isMinimized:true,initialize:function(options){this.layers=[];this.handlers={};OpenLayers.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.holderMapDiv.removeChild(this.mapDiv);this.mapDiv=null;this.element.removeChild(this.holderMapDiv);this.holderMapDiv=null;this.div.removeChild(this.element);this.element=null;this.map.events.un({"moveend":this.update,"changebaselayer":this.baseLayerDraw,scope:this});this.map.events.unregister("changebaselayer",this,this.changeLayer);this.map.events.unregister("addlayer",this,this.addLayer);this.map.events.unregister("removelayer",this,this.removeLayer);OpenLayers.Control.prototype.destroy.apply(this,arguments);},changeLayer:function(){var newLayer=this.map.baseLayer.clone();this.ovmap.addLayer(newLayer);this.ovmap.setBaseLayer(newLayer);var layerToRemove=this.ovmap.layers[0];this.ovmap.removeLayer(layerToRemove,false);layerToRemove.map=this.ovmap;},addLayer:function(evt){if(this.map.sapoSelectedBaseLayer&&this.map.sapoSelectedBaseLayer.labels===evt.layer){var newLayer=evt.layer.clone();this.ovmap.addLayer(newLayer);}},removeLayer:function(evt){if(this.map.sapoSelectedBaseLayer&&this.map.sapoSelectedBaseLayer.labels===evt.layer){var layerToRemove=null;for(var i=0;i<this.ovmap.layers.length;++i){if(this.ovmap.layers[i].layername==='hybrid'){layerToRemove=this.ovmap.layers[i];}}
if(layerToRemove){this.ovmap.removeLayer(layerToRemove);}}},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);this.map.events.register("changebaselayer",this,this.changeLayer);this.map.events.register("addlayer",this,this.addLayer);this.map.events.register("removelayer",this,this.removeLayer);if(!(this.layers.length>0)){if(this.map.baseLayer){var layer=this.map.baseLayer.clone();layer.loadTilesTimer=null;this.layers=[layer];if(this.map.sapoSelectedBaseLayer){this.layers.push(this.map.sapoSelectedBaseLayer.labels.clone());}}else{this.map.events.register("changebaselayer",this,this.baseLayerDraw);return this.div;}}
this.element=document.createElement('div');this.element.className=SAPO.Maps.Utils.checkIE6()?'mapict_viewController_minimap_ie6':'mapict_viewController_minimap';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.holderMapDiv=document.createElement('div');this.holderMapDiv.style.overflow='hidden';this.holderMapDiv.style.position='relative';this.holderMapDiv.appendChild(this.mapDiv);this.extentRectangle=document.createElement('div');this.extentRectangle.style.zIndex=1000;this.extentRectangle.className=this.displayClass+'ExtentRectangle';this.mapDiv.appendChild(this.extentRectangle);this.element.appendChild(this.holderMapDiv);if(!this.outsideViewport){this.div.className+=" "+this.displayClass+'Container';var maximize_minimizeDiv=document.createElement('div');SAPO.Maps.Utils.addClassName(maximize_minimizeDiv,'mapict_viewController_minimap_switch');var imgDiv=document.createElement('div');this.MaxMinBt=imgDiv;imgDiv.innerHTML="&nbsp;";if(SAPO.Maps.Utils.checkIE6()){SAPO.Maps.Utils.addClassName(imgDiv,'mapict_minimap_active_ie6');}else{SAPO.Maps.Utils.addClassName(imgDiv,'mapict_minimap_active');}
maximize_minimizeDiv.appendChild(imgDiv);OpenLayers.Event.observe(maximize_minimizeDiv,'mouseup',OpenLayers.Function.bindAsEventListener(this.toggleControl,this));this.div.appendChild(maximize_minimizeDiv);var eventsToStop=['dblclick','mousedown'];for(var i=0,len=eventsToStop.length;i<len;i++){OpenLayers.Event.observe(maximize_minimizeDiv,eventsToStop[i],OpenLayers.Event.stop);}
if(!this.isMinimized){this.showToggle(false,false);}}else{this.element.style.display='';}
this.div.appendChild(this.element);if(this.map.getExtent()){this.update();this.ovmap.viewPortDiv.style.position="static";}
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();},toggleControl:function(e){this.showToggle(!this.isMinimized,true);if(e!==null){OpenLayers.Event.stop(e);}},isOpened:function(){return!this.isMinimized;},showToggle:function(minimize,animation){this.isMinimized=minimize;if(!minimize){this.update();}
var activeClass=false,deactiveClass=false,classToAdd=false,classToRem=false;if(!this.opening&&!animation){activeClass=SAPO.Maps.Utils.checkIE6()?'mapict_minimap_active_ie6':'mapict_minimap_active';deactiveClass=SAPO.Maps.Utils.checkIE6()?'mapict_minimap_deactive_ie6':'mapict_minimap_deactive';classToAdd=minimize?activeClass:deactiveClass;classToRem=minimize?deactiveClass:activeClass;SAPO.Maps.Utils.addClassName(this.MaxMinBt,classToAdd);SAPO.Maps.Utils.removeClassName(this.MaxMinBt,classToRem);this.element.style.display=minimize?'none':'block';return;}
if(this.opening){return;}
if(!this.ovmap){this.element.style.display=minimize?'none':'';activeClass=SAPO.Maps.Utils.checkIE6()?'mapict_minimap_active_ie6':'mapict_minimap_active';deactiveClass=SAPO.Maps.Utils.checkIE6()?'mapict_minimap_deactive_ie6':'mapict_minimap_deactive';classToAdd=minimize?activeClass:deactiveClass;classToRem=minimize?deactiveClass:activeClass;SAPO.Maps.Utils.addClassName(this.MaxMinBt,classToAdd);SAPO.Maps.Utils.removeClassName(this.MaxMinBt,classToRem);return;}
var nrSteps=3;var w=0,h=0;var delta_w=0,delta_h=0;if(!minimize){this.element.style.display='block';}
w=this.ovmap.div.offsetWidth;h=this.ovmap.div.offsetHeight;delta_w=Math.ceil(w/nrSteps);delta_h=Math.ceil(h/nrSteps);if(minimize){delta_w*=-1;delta_h*=-1;}else{this.holderMapDiv.style.width="0px";this.holderMapDiv.style.height="0px";}
var curr_w=minimize?w:0;var curr_h=minimize?h:0;var _this=this;this.opening=true;var interval=setInterval(function(){curr_w+=delta_w;curr_h+=delta_h;if(!minimize&&(curr_w>w||curr_h>h)||minimize&&(curr_w<0||curr_h<0)){_this.holderMapDiv.style.width=w+"px";_this.holderMapDiv.style.height=h+"px";var activeClass=SAPO.Maps.Utils.checkIE6()?'mapict_minimap_active_ie6':'mapict_minimap_active';var deactiveClass=SAPO.Maps.Utils.checkIE6()?'mapict_minimap_deactive_ie6':'mapict_minimap_deactive';var classToAdd=minimize?activeClass:deactiveClass;var classToRem=minimize?deactiveClass:activeClass;SAPO.Maps.Utils.addClassName(_this.MaxMinBt,classToAdd);SAPO.Maps.Utils.removeClassName(_this.MaxMinBt,classToRem);_this.element.style.display=minimize?'none':'';w=minimize?0:w;h=minimize?0:h;_this.notifyOpenAndCloseListeners(new OpenLayers.Pixel(w,h));_this.opening=false;clearInterval(interval);return;}
_this.holderMapDiv.style.width=curr_w+"px";_this.holderMapDiv.style.height=curr_h+"px";_this.notifyOpenAndCloseListeners(new OpenLayers.Pixel(curr_w,curr_h));},5);},update:function(){if(this.ovmap&&!this.isOpened()){return;}
if(!this.ovmap){this.createMap();}
if(!this.isSuitableOverview()||this.autoPan){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));if(this.ovmap.getProjection()!==this.map.getProjection()){testExtent=testExtent.transform(this.map.getProjectionObject(),this.ovmap.getProjectionObject());}
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;}
var center;if(this.ovmap.getProjection()!==this.map.getProjection()){center=this.map.center.clone();center.transform(this.map.getProjectionObject(),this.ovmap.getProjectionObject());}else{center=this.map.center;}
if(!this.isMinimized){this.ovmap.setCenter(center,this.ovmap.getZoomForResolution(targetRes*this.resolutionFactor));}
this.updateRectToMap();},createMap:function(){var options=OpenLayers.Util.extend({controls:[],maxResolution:'auto',fallThrough:false,theme:null},this.mapOptions);this.ovmap=new OpenLayers.Map(this.mapDiv,options);OpenLayers.Event.stopObserving(window,'unload',this.ovmap.unloadDestroy);this.ovmap.addLayers(this.layers);this.wComp=Number(OpenLayers.Element.getStyle(this.extentRectangle,'border-left-width'))+
Number(OpenLayers.Element.getStyle(this.extentRectangle,'border-right-width'));this.wComp=(this.wComp)?this.wComp:2;this.hComp=Number(OpenLayers.Element.getStyle(this.extentRectangle,'border-top-width'))+
Number(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();}});if(this.ovmap.getProjection()!==this.map.getProjection()){var sourceUnits=this.map.getProjectionObject().getUnits()||this.map.units||this.map.baseLayer.units;var targetUnits=this.ovmap.getProjectionObject().getUnits()||this.ovmap.units||this.ovmap.baseLayer.units;this.resolutionFactor=sourceUnits&&targetUnits?OpenLayers.INCHES_PER_UNIT[sourceUnits]/OpenLayers.INCHES_PER_UNIT[targetUnits]:1;}},updateRectToMap:function(){var bounds;if(this.ovmap.getProjection()!==this.map.getProjection()){bounds=this.map.getExtent().transform(this.map.getProjectionObject(),this.ovmap.getProjectionObject());}else{bounds=this.map.getExtent();}
var pxBounds=this.getRectBoundsFromMapBounds(bounds);if(pxBounds){this.setRectPxBounds(pxBounds);}},updateMapToRect:function(){var lonLatBounds=this.getMapBoundsFromRectBounds(this.rectPxBounds);if(this.ovmap.getProjection()!==this.map.getProjection()){lonLatBounds=lonLatBounds.transform(this.ovmap.getProjectionObject(),this.map.getProjectionObject());}
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;},OpenAndCloseListener:function(func,context){if(!this.listeners){this.listeners=[];}
var obj={'func':func,'context':context};this.listeners.push(obj);},OpenAndCloseStopListening:function(func,context){if(!this.listeners){return false;}
var obj=false;for(var i=0;i<this.listeners.length;++i){obj=this.listeners[i];if(obj.func==func&&obj.context==context){this.listeners.splice(i,1);return true;}}
return false;},notifyOpenAndCloseListeners:function(px){if(!this.listeners){return;}
for(var i=0;i<this.listeners.length;++i){this.listeners[i].func.apply(this.listeners[i].context,[px]);}},CLASS_NAME:'SAPO.Maps.Control.MiniMap2'});SAPO.Maps.Control.Navigation=OpenLayers.Class(OpenLayers.Control,{pixel:null,_panValue:null,_numZoomLevels:null,_maxZoomLevel:null,_minZoomLevel:null,borders:null,initialize:function(options){this.borders={left:0,top:0,right:0,bottom:0};OpenLayers.Control.prototype.initialize.apply(this,[options]);this._panValue=100;},setMap:function(map){OpenLayers.Control.prototype.setMap.apply(this,arguments);this.pixel=new OpenLayers.Pixel(5,5);},adjustSizeToBaseLayer:function(e){var numZoomLevels=e.layer.numZoomLevels-SAPO.Maps.Config.MIN_ZOOM;var minZoomLevel=SAPO.Maps.Config.MIN_ZOOM;var maxZoomLevel=(numZoomLevels+minZoomLevel)-1;if(numZoomLevels!==this._numZoomLevels||maxZoomLevel!==this._maxZoomLevel||minZoomLevel!==this._minZoomLevel){this.redraw();}},draw:function(px){OpenLayers.Control.prototype.draw.apply(this,arguments);this._numZoomLevels=this.map.baseLayer.numZoomLevels-SAPO.Maps.Config.MIN_ZOOM;this._minZoomLevel=SAPO.Maps.Config.MIN_ZOOM;this._maxZoomLevel=(this._numZoomLevels+this._minZoomLevel)-1;while(this.div.hasChildNodes()){this.div.removeChild(this.div.childNodes[0]);}
var controlHTML=this.buildControl();this.div.appendChild(controlHTML);if(px){this.pixel.x=px.x;this.pixel.y=px.y;}
this.div.style.top=this.pixel.y+"px";this.div.style.left=this.pixel.x+"px";var zoom=this.map.getZoom();if(zoom<this._minZoomLevel){this.wheelChange(this._minZoomLevel-zoom);}
if(zoom>this._maxZoomLevel){this.wheelChange(this._maxZoomLevel-zoom);}
return this.div;},redraw:function(){this._numZoomLevels=this.map.baseLayer.numZoomLevels-SAPO.Maps.Config.MIN_ZOOM;this._minZoomLevel=SAPO.Maps.Config.MIN_ZOOM;this._maxZoomLevel=(this._numZoomLevels+this._minZoomLevel)-1;while(this.div.hasChildNodes()){this.div.removeChild(this.div.childNodes[0]);}
var controlHTML=this.buildControl();this.div.appendChild(controlHTML);var zoom=this.map.getZoom();if(zoom<this._minZoomLevel){this.wheelChange(zoom-this._minZoomLevel);}
if(zoom>this._maxZoomLevel){this.wheelChange(zoom-this._minZoomLevel);}},buildControl:function(){var div_navigation_sys_smapi=document.createElement("div");div_navigation_sys_smapi.className="navigation_sys_smapi";var div_nav_circle_smapi=document.createElement("div");div_nav_circle_smapi.className="nav_circle_smapi";var div_nav_up_smapi=document.createElement("div");div_nav_up_smapi.className="nav_up_smapi";var div_nav_middle_smapi=document.createElement("div");div_nav_middle_smapi.className="nav_middle_smapi";var div_nav_left_smapi=document.createElement("div");div_nav_left_smapi.className="nav_left_smapi";var div_nav_center_smapi=document.createElement("div");div_nav_center_smapi.className="nav_center_smapi";var div_nav_right_smapi=document.createElement("div");div_nav_right_smapi.className="nav_right_smapi";var div_nav_down_smapi=document.createElement("div");div_nav_down_smapi.className="nav_down_smapi";var div_zoom_smapi=document.createElement("div");div_zoom_smapi.className="zoom_smapi";var div_zoom_in_smapi=document.createElement("div");div_zoom_in_smapi.className="zoom_in_smapi";var div_zoom_slide_smapi=document.createElement("div");div_zoom_slide_smapi.className="zoom_slide_smapi";var div_zoom_out_smapi=document.createElement("div");div_zoom_out_smapi.className="zoom_out_smapi";if(OpenLayers.Util.getBrowserName()==='msie'){var ie_version=parseFloat(navigator.appVersion.split("MSIE")[1]);if(ie_version<7){div_zoom_smapi.className+=" zoom_smapi_ie6";div_zoom_slide_smapi.className+=" zoom_slide_smapi_ie6";div_zoom_in_smapi.className+=" zoom_in_smapi_ie6";div_zoom_out_smapi.className+=" zoom_out_smapi_ie6";div_nav_circle_smapi.className+=" nav_circle_smapi_ie6";div_nav_center_smapi.className+=" nav_center_smapi_ie6";}}
var img_arrow_up=document.createElement("img");img_arrow_up.src="http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/NavigationControl/arrow_up.gif";img_arrow_up.width=17;img_arrow_up.height=17;var img_arrow_left=document.createElement("img");img_arrow_left.src="http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/NavigationControl/arrow_left.gif";img_arrow_left.width=17;img_arrow_left.height=17;var img_arrow_center=document.createElement("img");img_arrow_center.src="http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/NavigationControl/arrow_center.gif";img_arrow_center.width=17;img_arrow_center.height=17;var img_arrow_right=document.createElement("img");img_arrow_right.src="http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/NavigationControl/arrow_right.gif";img_arrow_right.width=18;img_arrow_right.height=17;var img_arrow_down=document.createElement("img");img_arrow_down.src="http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/NavigationControl/arrow_down.gif";img_arrow_down.width=17;img_arrow_down.height=18;var img_plus=document.createElement("img");img_plus.src="http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/NavigationControl/plus.gif";img_plus.width=12;img_plus.height=11;var div_plus=document.createElement("div");div_plus.appendChild(img_plus);var img_minus=document.createElement("img");img_minus.src="http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/NavigationControl/minus.gif";img_minus.width=12;img_minus.height=4;var div_zoom,img_zoom;for(var i=this._numZoomLevels-1;i>=0;--i){div_zoom=document.createElement("div");img_zoom=document.createElement("img");div_zoom.className="zoom_point_wraper_smapi";img_zoom.src="http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/NavigationControl/zoom_point.gif";img_zoom.width=4;img_zoom.height=2;div_zoom.appendChild(img_zoom);div_zoom_slide_smapi.appendChild(div_zoom);div_zoom._zoomLevel=i+this._minZoomLevel;OpenLayers.Event.observe(div_zoom,"click",function(e){var newZoom=this._zoomLevel?this._zoomLevel:e.srcElement._zoomLevel;_this.wheelChange(newZoom-_this.map.getZoom());OpenLayers.Event.stop(e);},true);}
this.div_zoom_slide_smapi=div_zoom_slide_smapi;this.img_zoom_select=document.createElement("img");this.img_zoom_select.src="http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/NavigationControl/zoom_select.gif";this.img_zoom_select.width=12;this.img_zoom_select.height=12;this.img_zoom_select.style.position="absolute";this.img_zoom_select.basePosition=78+((this._numZoomLevels-1)*10);this.img_zoom_select.style.top=this.img_zoom_select.basePosition+"px";this.img_zoom_select.style.left="19px";div_zoom_slide_smapi.appendChild(this.img_zoom_select);div_nav_left_smapi.appendChild(img_arrow_left);div_nav_center_smapi.appendChild(img_arrow_center);div_nav_right_smapi.appendChild(img_arrow_right);div_nav_middle_smapi.appendChild(div_nav_left_smapi);div_nav_middle_smapi.appendChild(div_nav_center_smapi);div_nav_middle_smapi.appendChild(div_nav_right_smapi);div_nav_up_smapi.appendChild(img_arrow_up);div_nav_down_smapi.appendChild(img_arrow_down);div_nav_circle_smapi.appendChild(div_nav_up_smapi);div_nav_circle_smapi.appendChild(div_nav_middle_smapi);div_nav_circle_smapi.appendChild(div_nav_down_smapi);div_zoom_in_smapi.appendChild(img_plus);div_zoom_out_smapi.appendChild(img_minus);div_zoom_smapi.appendChild(div_zoom_in_smapi);div_zoom_smapi.appendChild(div_zoom_slide_smapi);div_zoom_smapi.appendChild(div_zoom_out_smapi);div_navigation_sys_smapi.appendChild(div_nav_circle_smapi);div_navigation_sys_smapi.appendChild(div_zoom_smapi);var initialZoom=this.map.getZoom();this.img_zoom_select.style.top=(this.img_zoom_select.basePosition-((initialZoom-this._minZoomLevel)*10))+"px";var _this=this;OpenLayers.Event.observe(this.div,"mousedown",function(e){var target=e.srcElement?e.srcElement:e.target;if(target!==_this.img_zoom_select&&target.className!=="zoom_point_wraper_smapi"){OpenLayers.Event.stop(e);}},true);OpenLayers.Event.observe(this.div,"dblclick",function(e){OpenLayers.Event.stop(e);},true);OpenLayers.Event.observe(this.div,"mousedown",OpenLayers.Event.stop);OpenLayers.Event.observe(this.div,"click",OpenLayers.Event.stop);this.map.events.register("zoomend",this,function(e){var newZoom=this.map.getZoom();_this.img_zoom_select.style.top=(_this.img_zoom_select.basePosition-((newZoom-this._minZoomLevel)*10))+"px";});var funcToZoomIn=OpenLayers.Function.bindAsEventListener(this.zoomInClicked,this);var funcToZoomOut=OpenLayers.Function.bindAsEventListener(this.zoomOutClicked,this);OpenLayers.Event.observe(div_zoom_in_smapi,"click",funcToZoomIn,true);OpenLayers.Event.observe(div_zoom_out_smapi,"click",funcToZoomOut,true);this.map.events.unregister("changebaselayer",this,this.adjustSizeToBaseLayer);this.map.events.register("changebaselayer",this,this.adjustSizeToBaseLayer);OpenLayers.Event.observe(img_arrow_up,"click",function(e){_this.map.pan(0,-_this._panValue);});OpenLayers.Event.observe(img_arrow_left,"click",function(e){_this.map.pan(-_this._panValue,0);});OpenLayers.Event.observe(img_arrow_down,"click",function(e){_this.map.pan(0,_this._panValue);});OpenLayers.Event.observe(img_arrow_right,"click",function(e){_this.map.pan(_this._panValue,0);});OpenLayers.Event.observe(img_arrow_center,"click",function(e){var center=new OpenLayers.LonLat(-904709.086279709,4823097.824952432);if(_this.map.getZoom()-this._minZoomLevel===0){_this.map.panTo(center);}
else{_this.wheelChange(_this._minZoomLevel-_this.map.getZoom());}});OpenLayers.Event.observe(this.img_zoom_select,"mousedown",function(e){_this._offset=e.layerY?e.layerY:e.offsetY;document.getElementsByTagName("body")[0]._this=_this;OpenLayers.Event.observe(document.getElementsByTagName("body")[0],"mousemove",_this.moveSlider,true);OpenLayers.Event.observe(document.getElementsByTagName("body")[0],"mouseup",_this.endMoveSlider);OpenLayers.Event.stop(e);},true);return div_navigation_sys_smapi;},zoomInClicked:function(evt){this.wheelChange(1);OpenLayers.Event.stop(evt);},zoomOutClicked:function(evt){this.wheelChange(-1);OpenLayers.Event.stop(evt);},wheelChange:function(deltaZ){var newZoom=this.map.getZoom()+deltaZ;if(!this.map.isValidZoomLevel(newZoom)){return;}
var size=this.map.getSize();var right=size.w-this.borders.right;var bottom=size.h-this.borders.bottom;var pixel_center_x=Math.floor((right-this.borders.left)/2)+this.borders.left;var pixel_center_y=Math.floor((bottom-this.borders.top)/2)+this.borders.top;var mapCenterConsideringBorders=new OpenLayers.Pixel(pixel_center_x,pixel_center_y);var deltaX=size.w/2-pixel_center_x;var deltaY=pixel_center_y-size.h/2;var newRes=this.map.baseLayer.getResolutionForZoom(newZoom);var zoomPoint=this.map.getLonLatFromPixel(mapCenterConsideringBorders);var newCenter=new OpenLayers.LonLat(zoomPoint.lon+deltaX*newRes,zoomPoint.lat+deltaY*newRes);this.map.setCenter(newCenter,newZoom);},moveSlider:function(e){if(!e.pageY){e.pageY=e.clientY;}
var _this=document.getElementsByTagName("body")[0]._this;var offset=e.layerY?0:2;var topDistance=0;var element=_this.div;while(element){topDistance+=element.offsetTop;element=element.offsetParent;}
if(e.pageY<(topDistance+_this.div_zoom_slide_smapi.offsetTop+offset)||e.pageY>(topDistance+_this.div_zoom_slide_smapi.offsetTop+offset+_this.div_zoom_slide_smapi.clientHeight)){return;}
_this.img_zoom_select.style.top=(e.pageY-topDistance-offset-_this._offset)+"px";OpenLayers.Event.stop(e);},endMoveSlider:function(e){var _this=document.getElementsByTagName("body")[0]._this;var sliderPx=_this.img_zoom_select.offsetTop-_this.div_zoom_slide_smapi.offsetTop;sliderPx=_this.img_zoom_select.offsetTop-_this.div_zoom_slide_smapi.offsetTop>(_this._numZoomLevels*10)?(_this._numZoomLevels*10):_this.img_zoom_select.offsetTop-_this.div_zoom_slide_smapi.offsetTop;sliderPx=_this.img_zoom_select.offsetTop-_this.div_zoom_slide_smapi.offsetTop<0?0:_this.img_zoom_select.offsetTop-_this.div_zoom_slide_smapi.offsetTop;var zoom=Math.abs(Math.floor(sliderPx/10)-_this._numZoomLevels-_this._minZoomLevel+1);if(zoom===_this.map.getZoom()){_this.img_zoom_select.style.top=(_this.img_zoom_select.basePosition-((zoom-_this._minZoomLevel)*10))+"px";}
else{_this.wheelChange(zoom-_this.map.getZoom());}
OpenLayers.Event.stopObserving(document.getElementsByTagName("body")[0],"mousemove",_this.moveSlider,true);OpenLayers.Event.stopObserving(document.getElementsByTagName("body")[0],"mouseup",_this.endMoveSlider);},CLASS_NAME:"SAPO.Maps.Control.Navigation"});SAPO.Maps.Control.Navigation2=OpenLayers.Class(OpenLayers.Control,{pixel:null,_panValue:100,_numZoomLevels:null,_maxZoomLevel:null,_minZoomLevel:null,borders:null,showMyLocationBt:false,select_ball:null,slider:null,zoomHolder:null,locationBtn:null,listeners:null,dragging:false,contextFunction:null,initialize:function(options){this.borders={left:0,top:0,right:0,bottom:0};OpenLayers.Control.prototype.initialize.apply(this,[options]);},destroy:function(){this.destroyHTML();this.map.events.unregister("changebaselayer",this,this.adjustSizeToBaseLayer);OpenLayers.Control.prototype.destroy.apply(this,arguments);},setMap:function(map){OpenLayers.Control.prototype.setMap.apply(this,arguments);this.pixel=new OpenLayers.Pixel(5,5);this.map.events.register("changebaselayer",this,this.adjustSizeToBaseLayer);},adjustSizeToBaseLayer:function(e){var numZoomLevels=e.layer.numZoomLevels-SAPO.Maps.Config.MIN_ZOOM;var minZoomLevel=SAPO.Maps.Config.MIN_ZOOM;var maxZoomLevel=(numZoomLevels+minZoomLevel)-1;if(numZoomLevels!==this._numZoomLevels||maxZoomLevel!==this._maxZoomLevel||minZoomLevel!==this._minZoomLevel){this.redraw();}},setContextFunction:function(obj){this.contextFunction=obj;},draw:function(px){OpenLayers.Control.prototype.draw.apply(this,arguments);this._numZoomLevels=this.map.baseLayer.numZoomLevels-SAPO.Maps.Config.MIN_ZOOM;this._minZoomLevel=SAPO.Maps.Config.MIN_ZOOM;this._maxZoomLevel=(this._numZoomLevels+this._minZoomLevel)-1;while(this.div.hasChildNodes()){this.div.removeChild(this.div.childNodes[0]);}
var controlHTML=this.buildControl();this.div.appendChild(controlHTML);if(px){this.pixel.x=px.x;this.pixel.y=px.y;}
this.div.style.top=this.pixel.y+"px";this.div.style.left=this.pixel.x+"px";var zoom=this.map.getZoom();if(zoom<this._minZoomLevel){this.wheelChange(this._minZoomLevel-zoom);}
if(zoom>this._maxZoomLevel){this.wheelChange(this._maxZoomLevel-zoom);}
return this.div;},redraw:function(){this._numZoomLevels=this.map.baseLayer.numZoomLevels-SAPO.Maps.Config.MIN_ZOOM;this._minZoomLevel=SAPO.Maps.Config.MIN_ZOOM;this._maxZoomLevel=(this._numZoomLevels+this._minZoomLevel)-1;this.destroyHTML();var controlHTML=this.buildControl();this.div.appendChild(controlHTML);var zoom=this.map.getZoom();if(zoom<this._minZoomLevel){this.wheelChange(zoom-this._minZoomLevel);}
if(zoom>this._maxZoomLevel){this.wheelChange(zoom-this._minZoomLevel);}},buildControl:function(){var holder=document.createElement('div');var navigation_holder=document.createElement('div');var mylocation_btn=document.createElement('div');var zoom_holder=document.createElement('div');var top_arrow=document.createElement('div');var left_arrow=document.createElement('div');var bottom_arrow=document.createElement('div');var right_arrow=document.createElement('div');var center_arrow=document.createElement('div');navigation_holder.appendChild(top_arrow);navigation_holder.appendChild(left_arrow);navigation_holder.appendChild(bottom_arrow);navigation_holder.appendChild(right_arrow);navigation_holder.appendChild(center_arrow);var div_zoomin=document.createElement('div');var slider=document.createElement('div');var div_zoomout=document.createElement('div');var div_zoom=false;var zoomTo=OpenLayers.Function.bind(this.zoomTo,this);for(var i=this._numZoomLevels-1;i>=0;--i){div_zoom=document.createElement("div");this.checkIE6AndAddStyle(div_zoom,'mapict_zoom_point_wraper','mapict_zoom_point_wraper_ie6');slider.appendChild(div_zoom);div_zoom._zoomLevel=i+this._minZoomLevel;OpenLayers.Event.observe(div_zoom,'mouseup',zoomTo,true);}
var select=document.createElement('div');slider.appendChild(select);this.select_ball=select;this.slider=slider;this.zoomHolder=zoom_holder;this.locationBtn=mylocation_btn;div_zoomin.innerHTML="+";div_zoomout.innerHTML="-";zoom_holder.appendChild(div_zoomin);zoom_holder.appendChild(slider);zoom_holder.appendChild(div_zoomout);holder.className='mapict_NavigationController';this.checkIE6AndAddStyle(navigation_holder,'mapict_NavigationPan','mapict_NavigationPan_ie6');this.checkIE6AndAddStyle(top_arrow,'mapict_NavigationPan_top','mapict_NavigationPan_top_ie6');this.checkIE6AndAddStyle(left_arrow,'mapict_NavigationPan_left','mapict_NavigationPan_left_ie6');this.checkIE6AndAddStyle(bottom_arrow,'mapict_NavigationPan_bottom','mapict_NavigationPan_bottom_ie6');this.checkIE6AndAddStyle(right_arrow,'mapict_NavigationPan_right','mapict_NavigationPan_right_ie6');this.checkIE6AndAddStyle(center_arrow,'mapict_NavigationPan_center','mapict_NavigationPan_center_ie6');this.checkIE6AndAddStyle(mylocation_btn,'mapict_imherebtn','mapict_imherebtn_ie6');zoom_holder.className="mapict_NavigationZoom";this.checkIE6AndAddStyle(div_zoomin,'mapict_NavigationZoom_zoomin','mapict_NavigationZoom_zoomin_ie6');this.checkIE6AndAddStyle(slider,'mapict_NavigationZoom_zoom_slider','mapict_NavigationZoom_zoom_slider_ie6');this.checkIE6AndAddStyle(div_zoomout,'mapict_NavigationZoom_zoomout','mapict_NavigationZoom_zoomout_ie6');this.checkIE6AndAddStyle(select,'mapict_NavigationZoom_selector','mapict_NavigationZoom_selector_ie6');holder.appendChild(navigation_holder);if(this.showMyLocationBt){holder.appendChild(mylocation_btn);}
holder.appendChild(zoom_holder);this.listeners={selectMouseDown:OpenLayers.Function.bind(this.startMoveSlider,this),selectMouseMove:OpenLayers.Function.bind(this.moveSlider,this),selectMouseUp:OpenLayers.Function.bind(this.endMoveSlider,this),panTop:OpenLayers.Function.bind(this.pan,this,0,-this._panValue),panLeft:OpenLayers.Function.bind(this.pan,this,-this._panValue,0),panBottom:OpenLayers.Function.bind(this.pan,this,0,this._panValue),panRight:OpenLayers.Function.bind(this.pan,this,this._panValue,0),zoomIn:OpenLayers.Function.bind(this.zoomInClicked,this),zoomOut:OpenLayers.Function.bind(this.zoomOutClicked,this),zoomTo:zoomTo,centerBt:OpenLayers.Function.bind(this.centerBtClicked,this),myLocation:OpenLayers.Function.bind(this.showMyLocation,this)};OpenLayers.Event.observe(select,'mousedown',this.listeners.selectMouseDown);OpenLayers.Event.observe(document.body,'mousemove',this.listeners.selectMouseMove,true);OpenLayers.Event.observe(document.body,'mouseup',this.listeners.selectMouseUp);OpenLayers.Event.observe(top_arrow,'mousedown',this.listeners.panTop);OpenLayers.Event.observe(left_arrow,'mousedown',this.listeners.panLeft);OpenLayers.Event.observe(bottom_arrow,'mousedown',this.listeners.panBottom);OpenLayers.Event.observe(right_arrow,'mousedown',this.listeners.panRight);OpenLayers.Event.observe(center_arrow,'mousedown',this.listeners.centerBt);OpenLayers.Event.observe(div_zoomin,'mousedown',this.listeners.zoomIn);OpenLayers.Event.observe(div_zoomout,'mousedown',this.listeners.zoomOut);OpenLayers.Event.observe(mylocation_btn,'click',this.listeners.myLocation);this.map.events.register('zoomend',this,this.zoomChanged);OpenLayers.Event.observe(holder,'dblclick',OpenLayers.Event.stop);OpenLayers.Event.observe(holder,'mousedown',OpenLayers.Event.stop);OpenLayers.Event.observe(holder,'click',OpenLayers.Event.stop);var gap_position=this._numZoomLevels-(this.map.getZoom()-SAPO.Maps.Config.MIN_ZOOM);this.select_ball.style.top=20+(gap_position-1)*11+'px';return holder;},destroyHTML:function(){var holder=this.div.firstChild;this.div.removeChild(holder);var navigation=holder.firstChild,top_arrow=navigation.childNodes[0],left_arrow=navigation.childNodes[1],bottom_arrow=navigation.childNodes[2],right_arrow=navigation.childNodes[3],center_arrow=navigation.childNodes[4],slider_zone=holder.lastChild,div_zoomin=slider_zone.firstChild,div_zoomout=slider_zone.lastChild,slider_element=false;for(var i=this.slider.childNodes.length-1;i>=0;--i){slider_element=this.slider.childNodes[i];if(slider_element!=this.select_ball){OpenLayers.Event.stopObservingElement(slider_element,'mouseup',this.listeners.zoomTo,true);}
this.slider.removeChild(slider_element);}
OpenLayers.Event.stopObserving(this.select_ball,'mousedown',this.listeners.selectMouseDown);OpenLayers.Event.stopObserving(document.body,'mousemove',this.listeners.selectMouseMove,true);OpenLayers.Event.stopObserving(document.body,'mouseup',this.listeners.selectMouseUp);OpenLayers.Event.stopObserving(top_arrow,'mousedown',this.listeners.panTop);OpenLayers.Event.stopObserving(left_arrow,'mousedown',this.listeners.panLeft);OpenLayers.Event.stopObserving(bottom_arrow,'mousedown',this.listeners.panBottom);OpenLayers.Event.stopObserving(right_arrow,'mousedown',this.listeners.panRight);OpenLayers.Event.stopObserving(center_arrow,'mousedown',this.listeners.centerBt);OpenLayers.Event.stopObserving(div_zoomin,'mousedown',this.listeners.zoomIn);OpenLayers.Event.stopObserving(div_zoomout,'mousedown',this.listeners.zoomOut);OpenLayers.Event.stopObserving(this.locationBtn,'click',this.listeners.showMyLocation);this.map.events.unregister('zoomend',this,this.zoomChanged);OpenLayers.Event.stopObserving(holder,'dblclick',OpenLayers.Event.stop);OpenLayers.Event.stopObserving(holder,'mousedown',OpenLayers.Event.stop);OpenLayers.Event.stopObserving(holder,'click',OpenLayers.Event.stop);holder.removeChild(navigation);if(this.showMyLocationBt){holder.removeChild(slider_zone.previousSibling);}
holder.removeChild(slider_zone);navigation.removeChild(top_arrow);navigation.removeChild(left_arrow);navigation.removeChild(bottom_arrow);navigation.removeChild(right_arrow);navigation.removeChild(center_arrow);slider_zone.removeChild(div_zoomin);slider_zone.removeChild(this.slider);slider_zone.removeChild(div_zoomout);this.listeners=null;this.select_ball=null;this.slider=null;this.zoomHolder=null;this.locationBtn=null;},zoomChanged:function(){var first_offset=this.slider.firstChild.offsetTop;var last_offset=this.slider.childNodes[this.slider.childNodes.length-2].offsetTop;var gap=(last_offset-first_offset)/(this._numZoomLevels-1);var zoom=this._maxZoomLevel-this.map.getZoom();var px=(zoom*gap)+first_offset;this.select_ball.style.top=px+"px";},centerBtClicked:function(){if(this.contextFunction!==null){this.contextFunction.func.apply(this.contextFunction.context,[]);}
else{this.map.zoomTo(SAPO.Maps.Config.MIN_ZOOM+2);}},zoomTo:function(evt){if((!evt||!evt.target)&&(!evt||!evt.srcElement)){return;}
var element=evt.target||evt.srcElement;var zoom=element._zoomLevel;this.wheelChange(zoom-this.map.getZoom());},pan:function(x,y){this.map.pan(x,y);var subsection=x===0&&y>0?"topArrow":(x<0&&y===0?"leftArrow":(x===0&&y>0?"bottomArrow":"rightArrow"));},startMoveSlider:function(e){OpenLayers.Event.stop(e);this.dragging=true;},moveSlider:function(e){if(!this.dragging){return;}
OpenLayers.Event.stop(e);var topDistance=0;var element=this.div;while(element){topDistance+=element.offsetTop;element=element.offsetParent;}
var offset=6;var sliderOffset=this.slider.firstChild.offsetTop;var firstElement_offsetTop=sliderOffset+this.zoomHolder.offsetTop+offset+topDistance;var lastElement_offsetTop=this.slider.childNodes[this.slider.childNodes.length-2].offsetTop+firstElement_offsetTop-sliderOffset;var pageY=e.pageY?e.pageY:e.clientY;if(pageY<firstElement_offsetTop){return;}
if(pageY>lastElement_offsetTop+offset){return;}
this.select_ball.style.top=(pageY-firstElement_offsetTop+sliderOffset)+'px';},endMoveSlider:function(e){if(!this.dragging){return;}
this.dragging=false;var first_offset=this.slider.firstChild.offsetTop;var last_offset=this.slider.childNodes[this.slider.childNodes.length-2].offsetTop;var gap=(last_offset-first_offset)/(this._numZoomLevels-1);var space=Math.floor((this.select_ball.offsetTop-first_offset)/gap);var zoom=((this._numZoomLevels-space)+SAPO.Maps.Config.MIN_ZOOM)-1;zoom=zoom>this._maxZoomLevel?this._maxZoomLevel:zoom;zoom=zoom<this._minZoomLevel?this._minZoomLevel:zoom;space=space<0?0:space;space=space>this._numZoomLevels?this._numZoomLevels:space;var px=(space*gap)+first_offset;this.select_ball.style.top=px+"px";this.wheelChange(zoom-this.map.getZoom());},zoomInClicked:function(evt){this.wheelChange(1);OpenLayers.Event.stop(evt);},zoomOutClicked:function(evt){this.wheelChange(-1);OpenLayers.Event.stop(evt);},showMyLocation:function(){var syndicationObj=new SAPO.Communication.Syndication();var reqID=syndicationObj.push("http://services.sapo.pt/Maps/GetMyLocationJSON",{timeout:4,onComplete:function(obj){var lat=Number(obj.GetMyLocationResponse.GetMyLocationResult["a:Latitude"].value);var lon=Number(obj.GetMyLocationResponse.GetMyLocationResult["a:Longitude"].value);SAPO.Maps.Utils.CenterMapConsideringBorders(this.map,new OpenLayers.LonLat(lon,lat),this.borders,14);}.bindObj(this)});syndicationObj.run(reqID);},wheelChange:function(deltaZ){var newZoom=this.map.getZoom()+deltaZ;if(!this.map.isValidZoomLevel(newZoom)){return;}
var size=this.map.getSize();var right=size.w-this.borders.right;var bottom=size.h-this.borders.bottom;var pixel_center_x=Math.floor((right-this.borders.left)/2)+this.borders.left;var pixel_center_y=Math.floor((bottom-this.borders.top)/2)+this.borders.top;var mapCenterConsideringBorders=new OpenLayers.Pixel(pixel_center_x,pixel_center_y);var deltaX=size.w/2-pixel_center_x;var deltaY=pixel_center_y-size.h/2;var newRes=this.map.baseLayer.getResolutionForZoom(newZoom);var zoomPoint=this.map.getLonLatFromPixel(mapCenterConsideringBorders);var newCenter=new OpenLayers.LonLat(zoomPoint.lon+deltaX*newRes,zoomPoint.lat+deltaY*newRes);this.map.setCenter(newCenter,newZoom);},checkIE6AndAddStyle:function(elem,className,classNameIe6){if(SAPO.Maps.Utils.checkIE6()){SAPO.Maps.Utils.addClassName(elem,classNameIe6);}else{SAPO.Maps.Utils.addClassName(elem,className);}},checkIE6AndRemoveStyle:function(elem,className,classNameIe6){if(SAPO.Maps.Utils.checkIE6()){SAPO.Maps.Utils.removeClassName(elem,classNameIe6);}else{SAPO.Maps.Utils.removeClassName(elem,className);}},CLASS_NAME:"SAPO.Maps.Control.Navigation2"});SAPO.Maps.Control.DragFeature=OpenLayers.Class(OpenLayers.Control,{layer:null,geometryTypes:null,feature:null,features:null,isDragging:false,dragCallbacks:{},featureCallbacks:{},lastPixel:null,initialize:function(layer,features,listeners,options){this.layer=layer;this.features=[];OpenLayers.Control.prototype.initialize.apply(this,[options]);this.handlers={drag:new OpenLayers.Handler.Drag(this,OpenLayers.Util.extend({down:this.downFeature,move:this.moveFeature,up:this.upFeature,out:this.cancel,done:this.doneDragging},this.dragCallbacks)),feature:new SAPO.Maps.Handler.Feature(this,this.layer,OpenLayers.Util.extend({over:this.overFeature,out:this.outFeature},this.featureCallbacks),{geometryTypes:this.geometryTypes})};},destroy:function(){OpenLayers.Control.prototype.destroy.apply(this,[]);},activate:function(){return(this.handlers.feature.activate(true)&&OpenLayers.Control.prototype.activate.apply(this,arguments));},deactivate:function(){this.handlers.drag.deactivate();this.handlers.feature.deactivate(true);this.feature=null;this.dragging=false;this.lastPixel=null;return OpenLayers.Control.prototype.deactivate.apply(this,arguments);},overFeature:function(feature){if(!feature.overlay||!feature.overlay.draggable){return;}
if(!this.handlers.drag.dragging){this.feature=feature;this.handlers.drag.activate();this.over=true;this.map.div.style.cursor="url(\"http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/openhand.cur\"), move";}else{if(this.feature.id===feature.id){this.over=true;}else{this.over=false;}}},downFeature:function(pixel){this.lastPixel=pixel;},moveFeature:function(pixel){if(this.isDragging===false&&this.lastPixel.equals(pixel)===false){this.isDragging=true;this.onStart(this.feature,pixel);}
var res=this.map.getResolution();this.feature.geometry.move(res*(pixel.x-this.lastPixel.x),res*(this.lastPixel.y-pixel.y));this.feature.layer.drawFeature(this.feature);this.lastPixel=pixel;this.onDrag(this.feature,pixel);},upFeature:function(pixel){if(!this.over){this.handlers.drag.deactivate();this.map.div.style.cursor="url(\"http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/openhand.cur\"), pointer";}else{this.map.div.style.cursor="url(\"http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/closedhand.cur\"), move";}},doneDragging:function(pixel){this.onComplete(this.feature,pixel);},outFeature:function(feature){if(!feature.overlay||!feature.overlay.draggable){return;}
if(!this.handlers.drag.dragging){this.over=false;this.handlers.drag.deactivate();this.map.div.style.cursor="url(\"http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/openhand.cur\"), pointer";this.feature=null;}else{if(this.feature.id===feature.id){this.over=false;}}},onStart:function(feature,pixel){this.notifyListeners(feature,'dragstart',[feature]);},onDrag:function(feature,pixel){this.notifyListeners(feature,'drag',[feature]);},onComplete:function(feature,pixel){this.isDragging=false;this.notifyListeners(feature,'dragend',[feature]);},supportEvent:function(evtType){if(evtType==="drag"||evtType==="dragstart"||evtType==="dragend"){return true;}
return false;},registerEvent:function(feature,eventType,context,func,params){if(!feature._eventsDrag){feature._eventsDrag={};}
if(!feature._eventsDrag[eventType]){feature._eventsDrag[eventType]=[];}
feature._eventsDrag[eventType].push({context:context,func:func,params:params});},unRegisterEvent:function(feature,eventType,context,func){if(!feature._eventsDrag){return false;}
if(!feature._eventsDrag[eventType]){return false;}
var length=feature._eventsDrag[eventType].length;for(var i=0;i<feature._eventsDrag[eventType].length;++i){if(feature._eventsDrag[eventType][i].context===context&&feature._eventsDrag[eventType][i].func===func){feature._eventsDrag[eventType].splice(i,1);}}
if(length===feature._eventsDrag[eventType].length){return false;}
if(feature._eventsDrag[eventType].length===0){delete feature._eventsDrag[eventType];}
var hasProperties=false;for(var e in feature._eventsDrag){hasProperties=true;break;}
if(!hasProperties){delete feature._eventsDrag;}
return true;},notifyListeners:function(feature,eventType,args){if(!feature._eventsDrag){return;}
if(!feature._eventsDrag[eventType]){return;}
var evts=feature._eventsDrag[eventType];var func,context,params;for(var i=0;i<evts.length;++i){func=evts[i].func;context=evts[i].context;params=evts[i].params;func.apply(context,params);}},addFeature:function(feature){this.features.push(feature);},removeFeature:function(feature){var index=-1;for(i=0;i<this.features.length;++i){if(feature===this.features[i]){index=i;break;}}
if(index!==-1){this.features.splice(index,1);}},cancel:function(){this.handlers.drag.deactivate();this.over=false;},setMap:function(map){this.handlers.drag.setMap(map);this.handlers.feature.setMap(map);OpenLayers.Control.prototype.setMap.apply(this,arguments);this.map.events.register("movestart",this,function(){this.deactivate();});this.map.events.register("moveend",this,function(){this.activate();});},CLASS_NAME:"SAPO.Maps.Control.DragFeature"});SAPO.Maps.Control.FeatureEventHandlers=OpenLayers.Class(OpenLayers.Control,{layer:null,features:null,callbacks:null,handlers:null,initialize:function(layer,options){OpenLayers.Control.prototype.initialize.apply(this,[options]);this.layer=layer;this.features=[];var callbacks={click:this.clickFeature,rightclick:this.rightclickFeature,mousedown:this.mousedownFeature,mouseup:this.mouseupFeature,over:this.overFeature,out:this.outFeature,dblclick:this.dblclickFeature};this.callbacks=OpenLayers.Util.extend(callbacks,this.callbacks);this.handlers={feature:new SAPO.Maps.Handler.Feature(this,this.layer,this.callbacks)};},activate:function(){this.handlers.feature.activate(true);return OpenLayers.Control.prototype.activate.apply(this,arguments);},deactivate:function(){this.handlers.feature.deactivate(true);return OpenLayers.Control.prototype.deactivate.apply(this,arguments);},clickFeature:function(feature){this.notifyListeners(feature,'click',[feature]);},rightclickFeature:function(feature){this.notifyListeners(feature,'rightclick',[feature]);},mousedownFeature:function(feature){this.notifyListeners(feature,'mousedown',[feature]);},mouseupFeature:function(feature){this.notifyListeners(feature,'mouseup',[feature]);},overFeature:function(feature){this.notifyListeners(feature,'mouseover',[feature]);},outFeature:function(feature){this.notifyListeners(feature,'mouseout',[feature]);},dblclickFeature:function(feature){this.notifyListeners(feature,'dblclick',[feature]);},supportEvent:function(evtType){if(evtType==="click"||evtType==="dblclick"||evtType==="mouseover"||evtType==="mouseout"||evtType==='mousedown'||evtType==='mouseup'||evtType==='rightclick'){return true;}
return false;},registerEvent:function(feature,eventType,context,func,params){if(!feature._events){feature._events={};this.features.push(feature);}
if(!feature._events[eventType]){feature._events[eventType]=[];}
feature._events[eventType].push({context:context,func:func,params:params});},unRegisterEvent:function(feature,eventType,context,func){if(!feature._events){return false;}
if(!feature._events[eventType]){return false;}
var length=feature._events[eventType].length;for(var i=0;i<feature._events[eventType].length;++i){if(feature._events[eventType][i].context===context&&feature._events[eventType][i].func===func){feature._events[eventType].splice(i,1);}}
if(length===feature._events[eventType].length){return false;}
if(feature._events[eventType].length===0){delete feature._events[eventType];}
var hasProperties=false;for(var e in feature._events){hasProperties=true;break;}
if(!hasProperties){delete feature._events;for(var j=0;j<this.features.length;++j){if(this.features[j]===feature){this.features.splice(j,1);}}}
return true;},notifyListeners:function(feature,eventType,args){if(!feature._events){return;}
if(!feature._events[eventType]){return;}
var evts=feature._events[eventType];var func,context,params;for(var i=0;i<evts.length;++i){func=evts[i].func;context=evts[i].context;params=evts[i].params;func.apply(context,params);}},setMap:function(map){this.handlers.feature.setMap(map);OpenLayers.Control.prototype.setMap.apply(this,arguments);this.map.events.register("movestart",this,function(){this.deactivate();});this.map.events.register("moveend",this,function(){this.activate();});},CLASS_NAME:"SAPO.Maps.Control.FeatureEventHandlers"});SAPO.Maps.Control.RightClicks=OpenLayers.Class(OpenLayers.Control,{click:null,callbacks:null,handleRightClicks:true,initialize:function(callbacks){OpenLayers.Control.prototype.initialize.apply(this,arguments);this.callbacks=callbacks;},destroy:function(){OpenLayers.Control.prototype.destroy.apply(this,arguments);},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);var clickCallbacks={'rightclick':this.singleRightClick,'dblrightclick':this.dblRightClick};var clickOptions={'double':true,'stopDouble':false};this.click=new OpenLayers.Handler.Click(this,clickCallbacks,clickOptions);this.click.activate();},singleRightClick:function(evt){if(this.callbacks&&this.callbacks.singlerightclick){var func=this.callbacks.singlerightclick.func;var params=this.callbacks.singlerightclick.params?this.callbacks.singlerightclick.params:[];var context=this.callbacks.singlerightclick.context;var args=params.slice();args.push(evt);func.apply(context,args);}},dblRightClick:function(evt){if(this.callbacks&&this.callbacks.dblrightclick){var func=this.callbacks.dblrightclick.func;var params=this.callbacks.dblrightclick.params?this.callbacks.dblrightclick.params:[];var context=this.callbacks.dblrightclick.context;var args=params.slice();args.push(evt);func.apply(context,args);}},CLASS_NAME:'RIGHT_CLICKS_CONTROL'});SAPO.Maps.Control.ContextMenu=OpenLayers.Class(OpenLayers.Control,{contextMenuHtml:null,contextMenuOptions:null,showContextMenu:null,hideContextMenu:null,isOnTheMap:false,lonlat:null,px:null,borders:null,selectedItem:null,search:null,changed:null,initialize:function(contextMenu,options){this.borders={left:0,right:0,bottom:0,top:0};this.changed=false;OpenLayers.Control.prototype.initialize.apply(this,[options]);var clickOpt=OpenLayers.Function.bind(this.clickOption,this);this.contextMenuOptions=[[{text:'Centrar o mapa aqui',callback:clickOpt},{text:'Zoom in',callback:clickOpt},{text:'Zoom out',callback:clickOpt}],[{text:'Copiar coordenadas',callback:clickOpt}]];this.addContextMenuOptions(contextMenu);},addContextMenuOptions:function(contextMenu){if(!contextMenu){return;}
var opts=false;var array=false;for(var i=0;i<contextMenu.length;++i){opts=contextMenu[i];if(!opts.section||opts.section>=this.contextMenuOptions.length){array=[];this.contextMenuOptions.push(array);}else if(opts.section==-1){array=[];this.contextMenuOptions.unshift(array);}else{array=this.contextMenuOptions[opts.section];}
for(var j=0;j<opts.options.length;++j){array.push(opts.options[j]);}}
if(this.map){this.changed=true;}},generateHtml:function(contextMenu)
{var click_top=document.createElement('div');var optionsContainer=document.createElement('div');var click_bottom=document.createElement('div');var options_list=document.createElement('ul');if(contextMenu.hasChildNodes()){while(contextMenu.childNodes.length>=1){contextMenu.removeChild(contextMenu.firstChild);}}
contextMenu.className='right_click';click_top.className='click_top';optionsContainer.className='click_middle';click_bottom.className='click_bottom';if(SAPO.Maps.Utils.checkIE6()){contextMenu.className+=' right_click_ie6';click_top.className+=' click_top_ie6';optionsContainer.className+=' click_middle_ie6';click_bottom.className+=' click_bottom_ie6';}
var _this=this;var section=false;var option=false;var li=false;var mouseover_handler=false;var mouseout_handler=false;for(var i=0;i<this.contextMenuOptions.length;++i){if(i!==0){li=document.createElement('li');li.className='separator';options_list.appendChild(li);}
section=this.contextMenuOptions[i];for(var j=0;j<section.length;++j){option=section[j];li=document.createElement('li');li.appendChild(document.createTextNode(option.text));li.text=option.text;li.idx=j;li.section=i;li.callback=option.callback;li.className='';li.style.position="relative";li.onmouseup=function(e){if(this.callback){this.callback(this.section,this.idx,this.text,_this.lonlat);}
_this.hide();};mouseover_handler=OpenLayers.Function.bind(this.selectItem,this,li);mouseout_hanlder=OpenLayers.Function.bind(this.unselectCurrentItem,this);OpenLayers.Event.observe(li,'mouseover',mouseover_handler);OpenLayers.Event.observe(li,'mouseout',mouseout_hanlder);options_list.appendChild(li);}}
contextMenu.appendChild(click_top);contextMenu.appendChild(optionsContainer);contextMenu.appendChild(click_bottom);optionsContainer.appendChild(options_list);},redraw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);this.generateHtml(this.contextMenuHtml);this.changed=false;return this.div;},draw:function(px){OpenLayers.Control.prototype.draw.apply(this,arguments);var contextMenu=document.createElement('div');this.generateHtml(contextMenu);this.contextMenuHtml=contextMenu;OpenLayers.Event.observe(contextMenu,"click",function(e){OpenLayers.Event.stop(e);});OpenLayers.Event.observe(contextMenu,"dbclick",function(e){OpenLayers.Event.stop(e);});OpenLayers.Event.observe(contextMenu,"mousedown",function(e){OpenLayers.Event.stop(e);});return this.div;},activate:function(){OpenLayers.Control.prototype.activate.apply(this,arguments);this.showContextMenu=OpenLayers.Function.bindAsEventListener(this.show,this);this.hideContextMenu=OpenLayers.Function.bindAsEventListener(this.hide,this);this.map.events.register('singlerightclick',this,this.showContextMenu);this.map.events.register('mouseup',this,this.hideContextMenu);OpenLayers.Event.observe(document.body,'click',this.hideContextMenu,false);},deactivate:function(){OpenLayers.Control.prototype.deactivate.apply(this,arguments);this.map.events.unregister('singlerightclick',this,this.showContextMenu);this.map.events.unregister('click',this,this.hideContextMenu);},destroy:function(){OpenLayers.Control.prototype.destroy.apply(this,arguments);},isOnMap:function(){return this.isOnTheMap;},show:function(evt){if(this.changed){this.redraw();}
this.px=evt.xy;this.lonlat=this.map.getLonLatFromContainerPixel(this.px);if(!this.isOnTheMap){this.contextMenuHtml.style.visibility="hidden";this.div.appendChild(this.contextMenuHtml);this.isOnTheMap=true;}
this.adjustPosition();this.setCopy2ClipBoard();this.contextMenuHtml.style.visibility="visible";},adjustPosition:function(){var mapSize=this.map.getSize();if(SAPO.Maps.Utils.checkIE6()){this.contextMenuHtml.childNodes[0].style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/ContextMenuControl/right_click_top_left.png',sizingMethod='crop')";this.contextMenuHtml.childNodes[2].style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/ContextMenuControl/right_click_bottom_clean.png',sizingMethod='crop')";}
else{this.contextMenuHtml.childNodes[0].style.background="transparent url(http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/ContextMenuControl/right_click_top_left.png) no-repeat";this.contextMenuHtml.childNodes[2].style.background="transparent url(http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/ContextMenuControl/right_click_bottom_clean.png) no-repeat";}
this.div.style.left=(this.px.x+1)+'px';this.div.style.top=(this.px.y+1)+'px';if((this.px.x+this.contextMenuHtml.clientWidth)>mapSize.w&&(this.px.y+this.contextMenuHtml.clientHeight)<mapSize.h){if(SAPO.Maps.Utils.checkIE6()){this.contextMenuHtml.childNodes[0].style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/ContextMenuControl/right_click_top_right.png',sizingMethod='crop')";this.contextMenuHtml.childNodes[2].style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/ContextMenuControl/right_click_bottom_clean.png',sizingMethod='crop')";}
else{this.contextMenuHtml.childNodes[0].style.background="transparent url(http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/ContextMenuControl/right_click_top_right.png) no-repeat";this.contextMenuHtml.childNodes[2].style.background="transparent url(http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/ContextMenuControl/right_click_bottom_clean.png) no-repeat";}
this.div.style.left=(this.px.x-this.contextMenuHtml.clientWidth-1)+'px';this.div.style.top=(this.px.y+1)+'px';}
if((this.px.x+this.contextMenuHtml.clientWidth)>mapSize.w&&(this.px.y+this.contextMenuHtml.clientHeight)>mapSize.h){if(SAPO.Maps.Utils.checkIE6()){this.contextMenuHtml.childNodes[0].style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/ContextMenuControl/right_click_top_clean.png',sizingMethod='crop')";this.contextMenuHtml.childNodes[2].style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/ContextMenuControl/right_click_bottom_right.png',sizingMethod='crop')";}
else{this.contextMenuHtml.childNodes[0].style.background="transparent url(http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/ContextMenuControl/right_click_top_clean.png) no-repeat 0 bottom";this.contextMenuHtml.childNodes[2].style.background="transparent url(http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/ContextMenuControl/right_click_bottom_right.png) no-repeat";}
this.div.style.left=(this.px.x-this.contextMenuHtml.clientWidth-1)+'px';this.div.style.top=(this.px.y-this.contextMenuHtml.clientHeight-1)+'px';}
if((this.px.x+this.contextMenuHtml.clientWidth)<mapSize.w&&(this.px.y+this.contextMenuHtml.clientHeight)>mapSize.h){if(SAPO.Maps.Utils.checkIE6()){this.contextMenuHtml.childNodes[0].style.height="17px";this.contextMenuHtml.childNodes[0].style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/ContextMenuControl/right_click_top_clean.png',sizingMethod='crop')";this.contextMenuHtml.childNodes[2].style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/ContextMenuControl/right_click_bottom_left.png',sizingMethod='crop')";}
else{this.contextMenuHtml.childNodes[0].style.background="transparent url(http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/ContextMenuControl/right_click_top_clean.png) no-repeat 0 bottom";this.contextMenuHtml.childNodes[2].style.background="transparent url(http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/ContextMenuControl/right_click_bottom_left.png) no-repeat";}
this.div.style.left=(this.px.x+1)+'px';this.div.style.top=(this.px.y-this.contextMenuHtml.clientHeight-1)+'px';}},hide:function(evt){if(!this.isOnTheMap){return;}
if(evt&&evt.type==='mousedown'&&!OpenLayers.Event.isLeftClick(evt)){return true;}
if(evt&&evt.type==='mouseup'&&!OpenLayers.Event.isLeftClick(evt)){return true;}
this.isOnTheMap=false;this.lonlat=null;this.px=null;this.unselectCurrentItem();this.div.removeChild(this.contextMenuHtml);if(this.copier){this.copier.destroy();}
return true;},clickOption:function(sectionIdx,selectedIdx,text){if(!this.map){return;}
switch(text){case'Centrar o mapa aqui':var size=this.map.getSize();var x_min=this.borders.left;var y_min=this.borders.top;var x_max=size.w-this.borders.right;var y_max=size.h-this.borders.bottom;var center_x=x_min+Math.floor((x_max-x_min)/2);var center_y=y_min+Math.floor((y_max-y_min)/2);var dx=this.px.x-center_x;var dy=this.px.y-center_y;this.map.pan(dx,dy);if(SAPO.Maps.Utils.checkUrl()){SapoMapsApp.Analytics.track("Funcionalidades","contextMenu","CentrarMapa");}
break;case'Zoom in':this.wheelChange(1);break;case'Zoom out':this.wheelChange(-1);break;case'Copiar coordenadas':var lat=this.lonlat.lat.toFixed(6);var lon=this.lonlat.lon.toFixed(6);SAPO.Maps.Utils.copy2Clipboard(lat+","+lon);if(SAPO.Maps.Utils.checkUrl()){SapoMapsApp.Analytics.track("Funcionalidades","contextMenu","CopiarClipboard");}
break;}},selectItem:function(item){if(this.selectedItem){this.unselectCurrentItem();}
SAPO.Maps.Utils.addClassName(item,'li_selected_item');this.selectedItem=item;},unselectCurrentItem:function(){if(!this.selectedItem){return;}
SAPO.Maps.Utils.removeClassName(this.selectedItem,'li_selected_item');this.selectedItem=null;},wheelChange:function(deltaZ){var newZoom=this.map.getZoom()+deltaZ;if(!this.map.isValidZoomLevel(newZoom)){return;}
var size=this.map.getSize();var deltaX=size.w/2-this.px.x;var deltaY=this.px.y-size.h/2;var newRes=this.map.baseLayer.getResolutionForZoom(newZoom);var zoomPoint=this.map.getLonLatFromPixel(this.px);var newCenter=new OpenLayers.LonLat(zoomPoint.lon+deltaX*newRes,zoomPoint.lat+deltaY*newRes);this.map.setCenter(newCenter,newZoom);},setCopy2ClipBoard:function(){var lis=this.div.childNodes[0].childNodes[1].childNodes[0];var elem=null;for(var i=0;i<lis.childNodes.length;++i){if(lis.childNodes[i].innerHTML==="Copiar coordenadas"){elem=lis.childNodes[i];}}
if(!elem){return;}
if(this.copier){this.copier.destroy();}
this.copier=SAPO.Maps.Utils.copy2ClipboardWhenClick(elem,function(){var lat=this.lonlat.lat.toFixed(6);var lon=this.lonlat.lon.toFixed(6);return lat+","+lon;}.bindObj(this));if(this.copier.zeroClipboard){this.copier.zeroClipboard.addEventListener('mouseOver',function(){this.selectItem(elem);}.bindObj(this));}},CLASS_NAME:'SAPO.Maps.Control.ContextMenu'});SAPO.Maps.Control.MousePosition=OpenLayers.Class(OpenLayers.Control,{element:null,prefix:'',separator:', ',suffix:'',numDigits:6,granularity:10,lastXy:null,displayProjection:null,isMinimized:true,minRightPosition:-135,nrSteps:5,initialize:function(options){this.displayProjection=new OpenLayers.Projection('EPSG:4326');OpenLayers.Control.prototype.initialize.apply(this,arguments);},toggle:function(minimize,animation){if(this.isMinimized===minimize){return;}
this.isMinimized=minimize;if(!animation){this.div.style.right=(minimize?this.minRightPosition:0)+'px';}else{var current_x=minimize?0:this.minRightPosition;var dx=this.minRightPosition/this.nrSteps;if(!minimize){dx*=-1;}
var _this=this;var interval=window.setInterval(function(){current_x+=dx;if((minimize&&current_x<=_this.minRightPosition)||(!minimize&&current_x>=0)){_this.div.style.right=(minimize?_this.minRightPosition:0)+'px';clearInterval(interval);}else{_this.div.style.right=current_x+'px';}},5);}
if(minimize){this.unregisterListeners();}else{this.registerListeners();}},isOpened:function(){return!this.isMinimized;},destroy:function(){if(this.map){this.unregisterListeners();}
OpenLayers.Event.stopObserving(this.div,'click',OpenLayers.Event.stop);OpenLayers.Event.stopObserving(this.div,'dblclick',OpenLayers.Event.stop);OpenLayers.Control.prototype.destroy.apply(this,arguments);},draw:function(px){OpenLayers.Control.prototype.draw.apply(this,arguments);var holder=document.createElement('div');this.element=document.createElement('p');OpenLayers.Event.observe(holder,'click',OpenLayers.Function.bindAsEventListener(this.toggleControl,this));OpenLayers.Event.observe(this.element,'click',OpenLayers.Function.bindAsEventListener(this.stopBublingEvent,this));holder.className='coordinates';if(SAPO.Maps.Utils.checkIE6()){holder.className+=' coordinates_ie6';}
holder.appendChild(this.element);this.div.appendChild(holder);this.redraw();if(!px){this.div.style.right=(this.isMinimized?this.minRightPosition:0)+'px';this.div.style.bottom='30px';}else{this.div.style.right=(this.isMinimized?this.minRightPosition:0)+'px';this.div.style.top=px.y+'px';}
OpenLayers.Event.observe(this.div,'click',OpenLayers.Event.stop);OpenLayers.Event.observe(this.div,'dblclick',OpenLayers.Event.stop);return this.div;},toggleControl:function(){this.toggle(!this.isMinimized,true);},stopBublingEvent:function(evt){OpenLayers.Event.stop(evt);},redraw:function(evt){var lonLat;if(!evt){lonLat=this.map.getMapCenter();}else{if(this.lastXy===null||Math.abs(evt.xy.x-this.lastXy.x)>this.granularity||Math.abs(evt.xy.y-this.lastXy.y)>this.granularity)
{this.lastXy=evt.xy;return;}
lonLat=this.map.getLonLatFromPixel(evt.xy);if(!lonLat){return;}
if(this.displayProjection){lonLat.transform(this.map.getProjectionObject(),this.displayProjection);}
this.lastXy=evt.xy;}
var newHtml=this.formatOutput(lonLat);if(newHtml!=this.element.innerHTML){this.element.innerHTML=newHtml;}},startMapDrag:function(){this.map.events.unregister('mousemove',this,this.redraw);},endMapDrag:function(){this.map.events.register('mousemove',this,this.redraw);},formatOutput:function(lonLat){var digits=parseInt(this.numDigits,10);var newHtml=this.prefix+
lonLat.lat.toFixed(digits)+
this.separator+
lonLat.lon.toFixed(digits)+
this.suffix;return newHtml;},setMap:function(){OpenLayers.Control.prototype.setMap.apply(this,arguments);if(!this.isMinimized){this.registerListeners();}},registerListeners:function(){this.map.events.register('mousemove',this,this.redraw);this.map.events.register('movestart',this,this.startMapDrag);this.map.events.register('moveend',this,this.endMapDrag);},unregisterListeners:function(){this.map.events.unregister('mousemove',this,this.redraw);this.map.events.unregister('movestart',this,this.startMapDrag);this.map.events.unregister('moveend',this,this.endMapDrag);},CLASS_NAME:"SAPO.Maps.Control.MousePosition"});SAPO.Maps.Control.MousePosition2=OpenLayers.Class(OpenLayers.Control,{decimalElement:null,dmsElement:null,prefix:'',separator:', ',suffix:'',numDigits:6,granularity:10,lastXy:null,displayProjection:null,isMinimized:true,minRightPosition:-160,nrSteps:5,initialize:function(options){this.displayProjection=new OpenLayers.Projection('EPSG:4326');OpenLayers.Control.prototype.initialize.apply(this,arguments);},toggle:function(minimize,animation){if(this.isMinimized===minimize){return;}
this.isMinimized=minimize;if(!animation){this.div.style.right=(minimize?this.minRightPosition:0)+'px';}else{var current_x=minimize?0:this.minRightPosition;var dx=this.minRightPosition/this.nrSteps;if(!minimize){dx*=-1;}
var _this=this;var interval=window.setInterval(function(){current_x+=dx;if((minimize&&current_x<=_this.minRightPosition)||(!minimize&&current_x>=0)){_this.div.style.right=(minimize?_this.minRightPosition:0)+'px';clearInterval(interval);}else{_this.div.style.right=current_x+'px';}},5);}
if(minimize){this.unregisterListeners();}else{this.registerListeners();}},isOpened:function(){return!this.isMinimized;},destroy:function(){if(this.map){this.unregisterListeners();}
OpenLayers.Event.stopObserving(this.div,'click',OpenLayers.Event.stop);OpenLayers.Event.stopObserving(this.div,'dblclick',OpenLayers.Event.stop);OpenLayers.Control.prototype.destroy.apply(this,arguments);},draw:function(px){OpenLayers.Control.prototype.draw.apply(this,arguments);var holder=document.createElement('div');var clickElem=document.createElement('div');var titleElement=document.createElement('p');this.decimalElement=document.createElement('p');this.dmsElement=document.createElement('p');OpenLayers.Event.observe(clickElem,'click',OpenLayers.Function.bindAsEventListener(this.toggleControl,this));OpenLayers.Event.observe(titleElement,'click',OpenLayers.Function.bindAsEventListener(this.stopBublingEvent,this));OpenLayers.Event.observe(this.decimalElement,'click',OpenLayers.Function.bindAsEventListener(this.stopBublingEvent,this));OpenLayers.Event.observe(this.dmsElement,'click',OpenLayers.Function.bindAsEventListener(this.stopBublingEvent,this));OpenLayers.Event.observe(this.decimalElement,'mousedown',OpenLayers.Function.bindAsEventListener(this.stopBublingEvent,this));OpenLayers.Event.observe(this.dmsElement,'mousedown',OpenLayers.Function.bindAsEventListener(this.stopBublingEvent,this));holder.className='smapi_mouseposition2_coordinates';this.decimalElement.className='smapi_mouseposition2_selectable';this.dmsElement.className='smapi_mouseposition2_selectable';if(SAPO.Maps.Utils.checkIE6()){holder.className+=' smapi_mouseposition2_coordinates_ie6';}
titleElement.innerHTML='Coordenadas';holder.appendChild(clickElem);holder.appendChild(titleElement);holder.appendChild(this.decimalElement);holder.appendChild(this.dmsElement);this.div.appendChild(holder);this.redraw();if(!px){this.div.style.right=(this.isMinimized?this.minRightPosition:0)+'px';this.div.style.bottom='30px';}else{this.div.style.right=(this.isMinimized?this.minRightPosition:0)+'px';this.div.style.top=px.y+'px';}
OpenLayers.Event.observe(this.div,'click',OpenLayers.Event.stop);OpenLayers.Event.observe(this.div,'dblclick',OpenLayers.Event.stop);return this.div;},toggleControl:function(){this.toggle(!this.isMinimized,true);},stopBublingEvent:function(evt){OpenLayers.Event.stop(evt);},redraw:function(evt){var lonLat;if(!evt){lonLat=this.map.getMapCenter();}else{if(this.lastXy===null||Math.abs(evt.xy.x-this.lastXy.x)>this.granularity||Math.abs(evt.xy.y-this.lastXy.y)>this.granularity)
{this.lastXy=evt.xy;return;}
lonLat=this.map.getLonLatFromPixel(evt.xy);if(!lonLat){return;}
if(this.displayProjection){lonLat.transform(this.map.getProjectionObject(),this.displayProjection);}
this.lastXy=evt.xy;}
var newHtml=this.formatOutput(lonLat);this.decimalElement.innerHTML=newHtml[0];this.dmsElement.innerHTML=newHtml[1];},startMapDrag:function(){this.map.events.unregister('mousemove',this,this.redraw);},endMapDrag:function(){this.map.events.register('mousemove',this,this.redraw);},formatOutput:function(lonLat){var digits=parseInt(this.numDigits,10);var lonlatDMS=SAPO.Maps.Utils.convertDecimalToDMS(lonLat.lat,lonLat.lon);var newHtml=[];newHtml[0]=this.prefix+
lonLat.lat.toFixed(digits)+
this.separator+
lonLat.lon.toFixed(digits)+
this.suffix;newHtml[1]=this.prefix+
lonlatDMS.lat+
this.separator+
lonlatDMS.lon+
this.suffix;return newHtml;},setMap:function(){OpenLayers.Control.prototype.setMap.apply(this,arguments);if(!this.isMinimized){this.registerListeners();}},registerListeners:function(){this.map.events.register('mousemove',this,this.redraw);this.map.events.register('movestart',this,this.startMapDrag);this.map.events.register('moveend',this,this.endMapDrag);},unregisterListeners:function(){this.map.events.unregister('mousemove',this,this.redraw);this.map.events.unregister('movestart',this,this.startMapDrag);this.map.events.unregister('moveend',this,this.endMapDrag);},CLASS_NAME:"SAPO.Maps.Control.MousePosition2"});SAPO.Maps.Control.Window=OpenLayers.Class(OpenLayers.Control,{title:null,content:null,footer:null,callbacks:null,size:null,movingWindow:false,minimumWindowSize:null,offsetFromOrigin:null,listeners:null,opacity:1,color:null,hidden:false,headerVisible:true,showMinimizedControl:false,minimizedControl:null,initialize:function(title,content,footer,callbacks,options){this.minimumWindowSize=new OpenLayers.Size(100,100);OpenLayers.Control.prototype.initialize.apply(this,[options]);this.title=title;this.content=content;this.footer=footer;this.callbacks=callbacks;this.size={w:0,h:0};this.offsetFromOrigin={x:0,y:0};},destroy:function(){var title=this.header.firstChild;var buttons=this.header.lastChild;var closeBtn=buttons.lastChild;var content=this.div.childNodes[1];var footer_content=this.footer.firstChild;var footer_resize=this.footer.lastChild;buttons.removeChild(closeBtn);this.header.removeChild(title);this.header.removeChild(buttons);content.removeChild(this.contentBackground);content.removeChild(this.contentUser);if(this.content){this.contentUser.removeChild(this.content);}
this.footer.removeChild(footer_content);this.footer.removeChild(footer_resize);this.div.removeChild(this.header);this.div.removeChild(content);this.div.removeChild(this.footer);OpenLayers.Event.stopObserving(this.div,'click',OpenLayers.Event.stop);OpenLayers.Event.stopObserving(this.header,'mousedown',this.listeners.header_mousedown);OpenLayers.Event.stopObserving(closeBtn,'click',this.listeners.closeWindow);OpenLayers.Event.stopObserving(footer_resize,'mousedown',this.listeners.resizeWindow);OpenLayers.Event.stopObserving(this.div,'mousedown',this.listeners.bringUp,true);OpenLayers.Event.stopObserving(this.content,'mousedown',this.listeners.bringUp,true);OpenLayers.Event.stopObserving(closeBtn,'mousedown',OpenLayers.Event.stop);OpenLayers.Event.stopObserving(this.div,'mousedown',OpenLayers.Event.stop);OpenLayers.Event.stopObserving(document.body,'mousemove',this.listeners.mouseMove);OpenLayers.Event.stopObserving(document.body,'mouseup',this.listeners.mouseUp);this.title=null;this.content=null;this.footer=null;this.callbacks=null;this.size=null;this.minimumWindowSize=null;this.offsetFromOrigin=null;this.listeners=null;this.hidden=false;this.movingWindow=false;if(this.minimizedControl){this.map.removeControl(this.minimizedControl);this.minimizedControl.destroy();this.minimizedControl=null;}
OpenLayers.Control.prototype.destroy.apply(this,arguments);},draw:function(px){OpenLayers.Control.prototype.draw.apply(this,arguments);var window=this.div;var header=document.createElement("div");var title=document.createElement("div");var buttons=document.createElement("div");var closeBtn=document.createElement("div");var content=document.createElement("div");var contentBackground=document.createElement("div");var contentUser=document.createElement("div");var footer=document.createElement('div');var footer_content=document.createElement('div');var footer_resize=document.createElement('div');window.appendChild(header);window.appendChild(content);window.appendChild(footer);header.appendChild(title);if(this.title){title.appendChild(document.createTextNode(this.title));}
header.appendChild(buttons);buttons.appendChild(closeBtn);footer.appendChild(footer_content);footer.appendChild(footer_resize);if(this.footer){footer_content.createTextNode(this.footer);}
content.appendChild(contentBackground);content.appendChild(contentUser);if(this.content){contentUser.appendChild(this.content);}
window.className="smaps_window";header.className="smaps_window_header smaps_window_header_draggable";title.className="smaps_window_header_title";buttons.className="smaps_window_header_buttons";closeBtn.className="smaps_window_header_buttons_close_btn";content.className="smaps_window_content";contentBackground.className="smaps_window_content_position smaps_window_content_background";contentUser.className="smaps_window_content_position";footer.className="smaps_footer";footer_content.className="smaps_footer_content";footer_resize.className="smaps_resize";this.listeners={header_mousedown:OpenLayers.Function.bind(this.headerMouseDown,this),mouseMove:OpenLayers.Function.bind(this.mouseMove,this),mouseUp:OpenLayers.Function.bind(this.mouseUp,this),closeWindow:OpenLayers.Function.bind(this.closeWindow,this),resizeWindow:OpenLayers.Function.bind(this.resize,this),bringUp:OpenLayers.Function.bind(this.bringUp,this)};OpenLayers.Event.observe(this.div,'click',OpenLayers.Event.stop);OpenLayers.Event.observe(header,'mousedown',this.listeners.header_mousedown);OpenLayers.Event.observe(closeBtn,'click',this.listeners.closeWindow);OpenLayers.Event.observe(footer_resize,'mousedown',this.listeners.resizeWindow);OpenLayers.Event.observe(window,'mousedown',this.listeners.bringUp,true);OpenLayers.Event.observe(this.content,'mousedown',this.listeners.bringUp,true);OpenLayers.Event.observe(closeBtn,'mousedown',OpenLayers.Event.stop);OpenLayers.Event.observe(window,'mousedown',OpenLayers.Event.stop);OpenLayers.Event.observe(document.body,'mousemove',this.listeners.mouseMove);OpenLayers.Event.observe(document.body,'mouseup',this.listeners.mouseUp);this.header=header;this.footer=footer;this.closeBtn=closeBtn;this.contentBackground=contentBackground;this.contentUser=contentUser;if(this.hidden){this.hide(true);}
this.div.style.left=px?px.x:0;this.div.style.top=px?px.y:0;var size=OpenLayers.Util.getRenderedDimensions(window);var width=size.w;var height=size.h;if(width<this.minimumWindowSize.w){size.w=this.minimumWindowSize.w;}else{this.minimumWindowSize.w=size.w;}
if(height<this.minimumWindowSize.h){size.h=this.minimumWindowSize.h;}else{this.minimumWindowSize.h=size.h;}
this.setWindowSize(size);this.setWindowOpacity(this.opacity);if(!this.headerVisible){this.hideHeaderAndFooter();}
if(this.color){this.setWindowColor(this.color);}
if(this.showMinimizedControl){if(!this.minimizedControl){this.minimizedControl=new SAPO.Maps.Control.MinimizedWindow(this.title,this);}
this.map.addControl(this.minimizedControl);}
return this.div;},getWindow:function(){return this.div;},setWindowSize:function(size){this.size.w=size.w<this.minimumWindowSize.w?this.minimumWindowSize.w:size.w;this.size.h=size.h<this.minimumWindowSize.h?this.minimumWindowSize.h:size.h;this.div.style.height=this.size.h+'px';this.div.style.width=this.size.w+'px';this.calculateContentDivDimensions(size.w,size.h);},setWindowPosition:function(pixel){this.div.style.left=pixel.x+'px';this.div.style.top=pixel.y+'px';},getWindowSize:function(){return this.size;},getWindowDefaultSize:function(){return new OpenLayers.Size(this.header.offsetWidth,this.header.offsetHeight+this.footer.offsetHeight);},show:function(silent){this.hidden=false;this.div.style.display="block";if(!silent&&this.minimizedControl){this.minimizedControl.hide();}
if(!silent&&this.callbacks&&this.callbacks.opened){var scope=this.callbacks.scope?this.callbacks.scope:this;this.callbacks.opened.apply(scope,[this]);}},hide:function(silent){this.hidden=true;this.div.style.display="none";if(!silent&&this.minimizedControl){this.minimizedControl.show();}
if(!silent&&this.callbacks&&this.callbacks.closed){var scope=this.callbacks.scope?this.callbacks.scope:this;this.callbacks.closed.apply(scope,[this]);}},hideMinimizedWindowControl:function(){if(this.minimizedControl){this.minimizedControl.hide();}},showMinimizedWindowControl:function(){if(this.minimizedControl){this.minimizedControl.show();}},isHidden:function(){return this.hidden;},getZIndex:function(){return Number(this.div.style.zIndex);},setZIndex:function(zIndex){this.div.style.zIndex=zIndex;},setWindowOpacity:function(opacity){this.opacity=opacity;var ie=OpenLayers.Util.getBrowserName()==='msie';var propName=ie?'filter':'opacity';var value=ie?"alpha(opacity="+opacity*100+")":opacity;this.contentBackground.style[propName]=value;this.footer.style[propName]=value;},setWindowColor:function(color){this.color=color;this.contentBackground.style.background=color;this.footer.style.background=color;},hideHeaderAndFooter:function(){this.headerVisible=false;this.div.style.border="none";this.header.style.display="none";this.footer.style.display="none";},showHeaderAndFooter:function(){this.headerVisible=true;this.div.style.border="solid 1px #F5F5F5";this.div.style.borderTop="none";this.header.style.display="block";this.footer.style.display="block";},isHeaderVisible:function(){return this.header.style.display==="block"||this.header.style.display==="";},getWindowColor:function(){if(!this.color){return this.contentBackground.style.background.replace("#","");}
return this.color.replace("#","");},getWindowOpacity:function(){return this.opacity;},calculateTopAndLeftDistances:function(){var topDistance=0;var leftDistance=0;var element=this.map.div;while(element){topDistance+=element.offsetTop;leftDistance+=element.offsetLeft;element=element.offsetParent;}
return{top:topDistance,left:leftDistance};},calculateContentDivDimensions:function(width,height){var h=height-this.header.offsetHeight-this.footer.offsetHeight;var w=width;this.contentBackground.style.height=h+"px";this.contentBackground.style.width=w+"px";this.contentUser.style.height="85%";this.contentUser.style.width=w+"px";},headerMouseDown:function(evt){this.movingWindow=true;var distances=this.calculateTopAndLeftDistances();var x=evt.layerX?evt.layerX:(evt.clientX-distances.left)-this.div.offsetLeft;var y=evt.layerY?evt.layerY:(evt.clientY-distances.top)-this.div.offsetTop;this.offsetFromOrigin.x=x;this.offsetFromOrigin.y=y;this.offsetFromOrigin.offsetTop=distances.top;this.offsetFromOrigin.offsetLeft=distances.left;},mouseMove:function(evt){if(!this.movingWindow&&!this.resizeWindow){return;}
var scrollTop=document.body.scrollTop|window.scrollY;var scrollLeft=document.body.scrollLeft|window.scrollX;var x=(scrollLeft+evt.clientX)-this.offsetFromOrigin.offsetLeft;var y=(scrollTop+evt.clientY)-this.offsetFromOrigin.offsetTop;if(this.movingWindow){this.div.style.left=x-this.offsetFromOrigin.x+"px";this.div.style.top=y-this.offsetFromOrigin.y+"px";}else{if(this.resizeWindow){var height=y-this.div.offsetTop;var width=x-this.div.offsetLeft;height=height>this.minimumWindowSize.h?height:this.minimumWindowSize.h;width=width>this.minimumWindowSize.w?width:this.minimumWindowSize.w;this.div.style.width=width+"px";this.div.style.height=height+"px";this.calculateContentDivDimensions(width,height);}}},mouseUp:function(){var scope=this.callbacks&&this.callbacks.scope?this.callbacks.scope:this;if(this.movingWindow&&this.callbacks&&this.callbacks.endMove){var params={left:this.div.offsetLeft,top:this.div.offsetTop};this.callbacks.endMove.apply(scope,[this,params]);}
if(this.resizeWindow&&this.callbacks&&this.callbacks.endResize){var params2={w:this.div.offsetWidth,h:this.div.offsetHeight};this.callbacks.endResize.apply(this,[this,params2]);}
this.movingWindow=false;this.resizeWindow=false;},bringUp:function(){var windows=this.map.getControlsByClass(this.CLASS_NAME);var sortedByZIndex=[];function windowSort(w1,w2){return w1.getZIndex()-w2.getZIndex();}
sortedByZIndex=windows.sort(windowSort);var topWindow=false,bottomWindow=false,topMostZIndex=sortedByZIndex.length>0?sortedByZIndex[sortedByZIndex.length-1].getZIndex():0;for(var k=sortedByZIndex.length-2;k>=0;--k){topWindow=sortedByZIndex[k+1];bottomWindow=sortedByZIndex[k];if(topWindow===this){break;}
topWindow.setZIndex(bottomWindow.getZIndex());if(bottomWindow===this){bottomWindow.setZIndex(topMostZIndex);break;}}},resize:function(){this.resizeWindow=true;var distances=this.calculateTopAndLeftDistances();this.offsetFromOrigin.offsetTop=distances.top;this.offsetFromOrigin.offsetLeft=distances.left;},closeWindow:function(){this.hide(false);},CLASS_NAME:'SAPO.Maps.Control.Window'});SAPO.Maps.Control.MinimizedWindow=OpenLayers.Class(OpenLayers.Control,{headerName:null,windowControl:null,visible:false,clickFunction:null,initialize:function(headerName,windowControl,options){OpenLayers.Control.prototype.initialize.apply(this,[options]);this.headerName=headerName;this.windowControl=windowControl;},destroy:function(){OpenLayers.Event.stopObserving(this.div,'click',this.clickFunction);OpenLayers.Event.stopObserving(this.div,'mousedown',OpenLayers.Event.stop);OpenLayers.Event.stopObserving(this.div,'click',OpenLayers.Event.stop);OpenLayers.Event.stopObserving(this.div,'dblclick',OpenLayers.Event.stop);this.clickFunction=null;this.windowControl=null;OpenLayers.Control.prototype.destroy.apply(this,arguments);},draw:function(px){OpenLayers.Control.prototype.draw.apply(this,arguments);var header=document.createElement('div');header.innerHTML=this.headerName;this.div.appendChild(header);this.div.className="smaps_window smaps_window_minimized";header.className="smaps_window_header";this.div.style.bottom="9px";this.div.style.right="27px";if(!this.visible){this.hide();}
this.clickFunction=OpenLayers.Function.bind(this.clickHandler,this);OpenLayers.Event.observe(this.div,'click',this.clickFunction);OpenLayers.Event.observe(this.div,'mousedown',OpenLayers.Event.stop);OpenLayers.Event.observe(this.div,'click',OpenLayers.Event.stop);OpenLayers.Event.observe(this.div,'dblclick',OpenLayers.Event.stop);return this.div;},show:function(){this.visible=true;this.div.style.display='block';},hide:function(){this.visible=false;this.div.style.display='none';},isVisible:function(){return this.visible;},getControlSize:function(){return new OpenLayers.Size(this.div.offsetWidth,this.div.offsetHeight);},clickHandler:function(){this.hide();this.windowControl.show();},CLASS_NAME:'SAPO.Maps.Control.MinimizedWindow'});SAPO.Maps.Control.SliderControl=OpenLayers.Class(OpenLayers.Control,{minValue:0,maxValue:100,step:1,value:0,skin:'ball',vertical:false,slider:null,controlSize:250,sliderPath:'http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Slider/',tooltipEnabled:false,initialized:false,heperDiv:null,sliderDiv:null,callbacks:null,onChange:null,onSlideEnd:null,disabled:false,initialize:function(callbacks,options){OpenLayers.Control.prototype.initialize.apply(this,[options]);this.callbacks=callbacks;},destroy:function(){this.onChange=null;this.onSlideEnd=null;OpenLayers.Event.stopObserving(this.div,'mousedown',OpenLayers.Event.stop);OpenLayers.Control.prototype.destroy.apply(this,arguments);},createAndInitialize:function(id){this.slider=new dhtmlxSlider(id,{skin:this.skin,min:this.minValue,max:this.maxValue,step:this.step,size:this.controlSize,vertical:this.vertical});this.slider.setValue(this.value);this.slider.setImagePath(this.sliderPath);this.slider.init();this.onChange=OpenLayers.Function.bind(this.slideChanged,this);this.onSlideEnd=OpenLayers.Function.bind(this.slideEnded,this);this.slider.attachEvent('onChange',this.onChange);this.slider.attachEvent('onSlideEnd',this.onSlideEnd);if(!this.tooltipEnabled){this.disableTooltip();}else{this.enableTooltip();}
window.clearTimeout(this.timerId);this.timerId=null;this.initialized=true;this.helperDiv.removeChild(this.sliderDiv);document.body.removeChild(this.helperDiv);this.div.appendChild(this.sliderDiv);},draw:function(px){OpenLayers.Control.prototype.draw.apply(this,arguments);var div=document.createElement('div');div.id=OpenLayers.Util.createUniqueID(this.CLASS_NAME);this.timerId=window.setTimeout(OpenLayers.Function.bind(this.createAndInitialize,this,div.id),0);OpenLayers.Event.observe(this.div,"mousedown",OpenLayers.Event.stop);this.helperDiv=document.createElement('div');this.helperDiv.style.position='absolute';this.helperDiv.style.left='-100px';this.helperDiv.appendChild(div);document.body.appendChild(this.helperDiv);this.sliderDiv=div;return this.div;},slideChanged:function(){if(this.disabled){this.slider.setValue(this.value);return;}
this.value=this.slider.getValue();this.notify('slideChanged',[this.value]);},slideEnded:function(){if(this.disabled){return;}
this.value=this.slider.getValue();this.notify('slideEnded',[this.value]);},notify:function(event,params){if(this.callbacks&&this.callbacks[event]){var scope=this.callbacks.scope?this.callbacks.scope:this;var func=this.callbacks[event];func.apply(scope,params);}},getValue:function(){return this.value;},setValue:function(value,silent){if(!this.initialized){var setValueFunc=OpenLayers.Function.bind(this.setValue,this,value);this.timerSetValueId=window.setTimeout(setValueFunc,0);return;}
this.value=value;this.slider.setValue(value);if(!silent){this.notify('slideChanged',[this.value]);}},enableTooltip:function(){this.tooltipEnabled=true;this.slider.enableTooltip(true);},disableTooltip:function(){this.tooltipEnabled=false;this.slider.enableTooltip(false);},isTooltipEnable:function(){return this.tooltipEnabled;},getMaxValue:function(){return this.maxValue;},setMaxValue:function(value){this.maxValue=value;this.slider.setMax(value);},getMinValue:function(){return this.minValue;},setMinValue:function(value){this.minValue=value;this.slider.setMin(value);},getStep:function(){return this.step;},setStep:function(step){this.step=step;this.slider.setStep(step);},getControlSize:function(){return this.controlSize;},disableControl:function(){this.disabled=true;},enableControl:function(){this.disabled=false;},CLASS_NAME:'SAPO.Maps.Control.SliderControl'});SAPO.Maps.Control.Tooltip=OpenLayers.Class(OpenLayers.Control,{message:null,messageTextNode:null,visible:true,initialize:function(message,style,options){OpenLayers.Control.prototype.initialize.apply(this,[options]);OpenLayers.Util.extend(this,options);this.message=message!==null?message:'';},draw:function(px){OpenLayers.Control.prototype.draw.apply(this,arguments);SAPO.Maps.Utils.addClassName(this.div,'smapi_tooltip_control');this.messageTextNode=document.createElement('span');this.messageTextNode.innerHTML=this.message;this.div.appendChild(this.messageTextNode);if(this.arrow&&this.arrowDirection){arrowImageNode=document.createElement('img');arrowImageNode.className='smapi_tooltip_arrow';arrowImageNode.style.left=this.arrowLeft+'px';if(this.arrowDirection=='up'){arrowImageNode.src='https://imgs.sapo.pt/fotos_gis//mapas_api/v1.1/Tooltip/arrowup.png';arrowImageNode.style.top='-5px';}
else if(this.arrowDirection=='down'){arrowImageNode.src='https://imgs.sapo.pt/fotos_gis//mapas_api/v1.1/Tooltip/arrowdown.png';arrowImageNode.style.bottom='-5px';}
this.div.appendChild(arrowImageNode);}
this.div.style.display=this.visible===true?'block':'none';if(px){this.div.style.left=px.x+'px';this.div.style.top=px.y+'px';}
return this.div;},setPosition:function(px){this.div.style.left='-9999px';this.div.style.top='-9999px';if(!this.visible){this.div.style.display='block';}
var width=this.div.offsetWidth;var height=this.div.offsetHeight;if(!this.visible){this.div.style.display='none';}
if(width>(this.map.div.offsetWidth-px.x)){px.x-=width+25;}
this.div.style.left=px.x+'px';this.div.style.top=px.y+'px';},show:function(message,px){if(this.div){if(message){this.setMessage(message);}
if(px){this.setPosition(px);}
this.div.style.display='block';this.visible=true;}},hide:function(){if(this.div){this.div.style.display='none';this.visible=false;}},setMessage:function(message){this.message=message;this.messageTextNode.innerHTML=this.message;},CLASS_NAME:'SAPO.Maps.Control.Tooltip'});SAPO.Maps.Control.MessageBoardControl=OpenLayers.Class(OpenLayers.Control,{messageBoard:null,closeBtn:null,anchor:null,anchorCallback:null,functions:null,timerId:null,borders:null,SUPPORTED_EVENTS:['closed'],visible:false,initialize:function(borders){OpenLayers.Control.prototype.initialize.apply(this,[]);this.borders=OpenLayers.Util.extend({left:0,right:0,top:0,bottom:0},borders);for(var i=0,len=this.SUPPORTED_EVENTS.length;i<len;++i){this.events.addEventType(this.SUPPORTED_EVENTS[i]);}
this.functions={windowResizedFunc:OpenLayers.Function.bind(this.windowResized,this)};OpenLayers.Event.observe(window,"resize",this.functions.windowResizedFunc);},destroy:function(){if(this.timerId){window.clearTimeout(this.timerId);}
OpenLayers.Event.stopObserving(this.div,'dblclick',OpenLayers.stop);OpenLayers.Event.stopObserving(this.div,'click',OpenLayers.stop);OpenLayers.Event.stopObserving(window,"resize",this.functions.windowResizedFunc);OpenLayers.Event.stopObserving(this.closeBtn,'click',this.functions.closeBtnFunc);this.closeBtn=null;this.timerId=null;this.messageBoard=null;this.functions=null;OpenLayers.Control.prototype.destroy.apply(this,arguments);},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);this.messageBoard=document.createElement('div');this.messageBoard.className='smapi_messageBoard';this.div.appendChild(this.messageBoard);this.closeBtn=document.createElement('div');this.closeBtn.className='closebtn';this.div.appendChild(this.closeBtn);this.functions.closeBtnFunc=OpenLayers.Function.bind(this.hideMessage,this);OpenLayers.Event.observe(this.closeBtn,'click',this.functions.closeBtnFunc);this.anchor=document.createElement('a');this.anchor.href="#";this.functions.anchorClickedFunc=OpenLayers.Function.bind(this.anchorClicked,this);OpenLayers.Event.observe(this.anchor,'click',this.functions.anchorClickedFunc);OpenLayers.Event.observe(this.div,'dblclick',OpenLayers.Event.stop);OpenLayers.Event.observe(this.div,'click',OpenLayers.Event.stop);this.setBorders(this.borders);return this.div;},showMessage:function(message,options){if(this.visible){this.events.triggerEvent('closed');}
this.messageBoard.innerHTML=message;this.div.style.display='block';this.visible=true;this.showAnchor(options);},hideMessage:function(){this.messageBoard.innerHTML='';this.div.style.display='none';this.visible=false;this.anchorCallback=null;this.anchor.style.display='none';if(this.anchor.parentNode||this.anchor.parent){this.messageBoard.removeChild(this.anchor);}
this.events.triggerEvent('closed');},showMessageDelay:function(message,delay,options){if(!this.hideMessageFunc){this.functions.hideMessageFunc=OpenLayers.Function.bind(this.hideMessageTimeoutHandler,this);}
this.messageBoard.innerHTML=message;this.div.style.display='block';this.visible=true;this.timerId=window.setTimeout(this.functions.hideMessageFunc,delay);this.showAnchor(options);},setBorders:function(borders){this.borders=borders;var width=this.map.getSize().w-borders.left-borders.right;this.div.style.top=borders.top+'px';this.div.style.left=borders.left+'px';this.div.style.width=width+'px';},windowResized:function(){this.setBorders(this.borders);},hideMessageTimeoutHandler:function(){if(this.timerId){window.clearTimeout(this.timerId);this.timerId=null;}
this.hideMessage();},anchorClicked:function(evt){if(this.anchorCallback){this.anchorCallback.callback.apply(this.anchorCallback.scope,[]);}
if(evt&&evt.preventDefault){evt.preventDefault();}
return false;},showAnchor:function(options){if(options){this.anchor.innerHTML=options.anchorText;this.anchorCallback=options.anchorCallback;this.anchor.style.display='block';this.messageBoard.appendChild(this.anchor);}},CLASS_NAME:'SAPO.Maps.Control.MessageBoardControl'});SAPO.Maps.Popup.SapoPopup=OpenLayers.Class(OpenLayers.Popup,{displayClass:null,contentDisplayClass:null,_closeBox:false,_closeBoxCallback:null,_popupAnchor:null,_popupSize:null,_borders:null,_pan:null,_maxSize:null,initialize:function(id,lonlat,contentSize,contentHTML,closeBox,closeBoxCallback,popupAnchor,borders,pan,maxSize){OpenLayers.Popup.prototype.initialize.apply(this,arguments);this._closeBox=closeBox||this._closeBox;this._closeBoxCallback=closeBoxCallback;this._popupAnchor=popupAnchor;if(borders&&borders.left!==null&&borders.bottom!==null&&borders.right!==null&&borders.top!==null){this._borders=borders;}
else{this._borders={left:62,bottom:25,right:0,top:43};}
this._pan=pan===false?false:true;this._maxSize=maxSize;},draw:function(px){if(!px){if((this.lonlat)&&(this.map)){px=this.map.getLayerPxFromLonLat(this.lonlat);}}
this.px=px;while(this.div.hasChildNodes()){this.div.removeChild(this.div.childNodes[0]);}
var div_smapi_popup_wrapper=document.createElement("div");var div_close_btn_smapi=document.createElement("div");var div_smapi_popup_top_left_corner=document.createElement("div");var div_smapi_popup_top_center=document.createElement("div");var div_smapi_popup_top_right_corner=document.createElement("div");var div_smapi_popup_middle_left=document.createElement("div");var div_smapi_popup_middle_center=document.createElement("div");var div_smapi_popup_content=document.createElement("div");var div_smapi_popup_bgi=document.createElement("div");var div_smapi_popup_middle_right=document.createElement("div");var div_smapi_popup_bottom_left_corner=document.createElement("div");var div_smapi_popup_bottom_center=document.createElement("div");var div_smapi_popup_bottom_right_corner=document.createElement("div");var img_sprite=document.createElement("img");div_smapi_popup_wrapper.className="smapi_popup_wrapper";div_close_btn_smapi.className="close_btn_smapi";div_smapi_popup_top_left_corner.className="smapi_popup_top_left_corner";div_smapi_popup_top_center.className="smapi_popup_top_center";div_smapi_popup_top_right_corner.className="smapi_popup_top_right_corner";div_smapi_popup_middle_left.className="smapi_popup_middle_left";div_smapi_popup_middle_center.className="smapi_popup_middle_center";div_smapi_popup_content.className="smapi_popup_content";div_smapi_popup_bgi.className="smapi_popup_bgi";div_smapi_popup_middle_right.className="smapi_popup_middle_right";div_smapi_popup_bottom_left_corner.className="smapi_popup_bottom_left_corner";div_smapi_popup_bottom_center.className="smapi_popup_bottom_center";div_smapi_popup_bottom_right_corner.className="smapi_popup_bottom_right_corner";img_sprite.width="1000";img_sprite.height="1009";img_sprite.src="http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Popup/sprite2.png";if(OpenLayers.Util.getBrowserName()==='msie'){var ie_version=parseFloat(navigator.appVersion.split("MSIE")[1]);if(ie_version<7){img_sprite.src="http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Popup/sprite2.gif";div_smapi_popup_middle_center.className+=" smapi_popup_middle_center_ie6";div_smapi_popup_bgi.className+=" smapi_popup_bgi_ie6";div_smapi_popup_top_center.className+=" popup_ie6_width";div_smapi_popup_middle_left.className+=" popup_ie6_height";div_smapi_popup_bgi.className+=" popup_ie6_width popup_ie6_height";div_smapi_popup_middle_right.className+=" popup_ie6_height";}}
div_smapi_popup_top_left_corner.appendChild(img_sprite);div_smapi_popup_top_center.appendChild(img_sprite.cloneNode(false));div_smapi_popup_top_right_corner.appendChild(img_sprite.cloneNode(false));div_smapi_popup_middle_left.appendChild(img_sprite.cloneNode(false));div_smapi_popup_bgi.appendChild(img_sprite.cloneNode(false));div_smapi_popup_middle_right.appendChild(img_sprite.cloneNode(false));div_smapi_popup_bottom_left_corner.appendChild(img_sprite.cloneNode(false));div_smapi_popup_bottom_center.appendChild(img_sprite.cloneNode(false));div_smapi_popup_bottom_right_corner.appendChild(img_sprite.cloneNode(false));div_smapi_popup_middle_center.appendChild(div_smapi_popup_content);if(this._closeBox){this.closeDiv=div_close_btn_smapi;div_smapi_popup_wrapper.appendChild(div_close_btn_smapi);var closePopup=this._closeBoxCallback||function(e){this.hide();OpenLayers.Event.stop(e);};OpenLayers.Event.observe(this.closeDiv,"click",OpenLayers.Function.bindAsEventListener(closePopup,this));}
div_smapi_popup_wrapper.appendChild(div_smapi_popup_top_left_corner);div_smapi_popup_wrapper.appendChild(div_smapi_popup_top_center);div_smapi_popup_wrapper.appendChild(div_smapi_popup_top_right_corner);div_smapi_popup_wrapper.appendChild(div_smapi_popup_middle_left);div_smapi_popup_wrapper.appendChild(div_smapi_popup_middle_center);div_smapi_popup_wrapper.appendChild(div_smapi_popup_bgi);div_smapi_popup_wrapper.appendChild(div_smapi_popup_middle_right);div_smapi_popup_wrapper.appendChild(div_smapi_popup_bottom_left_corner);div_smapi_popup_wrapper.appendChild(div_smapi_popup_bottom_center);div_smapi_popup_wrapper.appendChild(div_smapi_popup_bottom_right_corner);this.div.appendChild(div_smapi_popup_wrapper);this.contentDiv=div_smapi_popup_content;this.setContentHTML();this.updateSize();this.moveTo(px,this._pan);return this.div;},setContentHTML:function(contentHTML){if(contentHTML){this.contentHTML=contentHTML;}
this.contentDiv.innerHTML="";if(typeof(this.contentHTML)==='string'){this.contentDiv.innerHTML=this.contentHTML;}
else{this.contentDiv.appendChild(this.contentHTML);}
this.registerImageListeners();this.contentUpdated();},setSize:function(contentSize){this.div.style.width=contentSize.w+"px";this.div.style.height=contentSize.h+"px";if(OpenLayers.Util.getBrowserName()==='msie'){var ie_version=parseFloat(navigator.appVersion.split("MSIE")[1]);if(ie_version<7){this.div.getElementsByClassName=function(cl){var retnode=[];var myclass=new RegExp('\\b'+cl+'\\b');var elem=this.getElementsByTagName('*');for(var i=0;i<elem.length;i++){var classes=elem[i].className;if(myclass.test(classes)){retnode.push(elem[i]);}}
return retnode;};var elementsWidth=this.div.getElementsByClassName("popup_ie6_width");var elementsHeight=this.div.getElementsByClassName("popup_ie6_height");for(var i=0;i<elementsWidth.length;++i){elementsWidth[i].style.width=(contentSize.w-34)+"px";}
for(var j=0;j<elementsHeight.length;++j){elementsHeight[j].style.height=(contentSize.h-46)+"px";}}}},updateSize:function(){var realSize=this.getPopupDimensions();this._popupSize=realSize;this.setSize(this._popupSize);},moveTo:function(px,pan){if(this._popupAnchor){px=px.add(this._popupAnchor.x,this._popupAnchor.y);}
this.div.style.top=(px.y-this._popupSize.h+5)+"px";this.div.style.left=(px.x-(this._popupSize.w/2)-9)+"px";if(pan){this.panIntoView(this._popupSize);}},contentUpdated:function(){this.registerImageListeners();this.updateSize();this.px=this.map.getLayerPxFromLonLat(this.lonlat);this.moveTo(this.px,this._pan);},registerImageListeners:function(){var onImgLoad=function(){this.popup.updateSize();if((this.popup.lonlat)&&(this.popup.map)){var px=this.popup.map.getLayerPxFromLonLat(this.popup.lonlat);this.popup.moveTo(px,this.popup._pan);}
OpenLayers.Event.stopObserving(this.img,"load",this.img._onImgLoad);};var images=this.contentDiv.getElementsByTagName("img");for(var i=0;i<images.length;i++){var img=images[i];var context={'popup':this,'img':img};if(!img._onImgLoad&&img.width===0&&img.height===0){img._onImgLoad=OpenLayers.Function.bind(onImgLoad,context);OpenLayers.Event.observe(img,'load',img._onImgLoad);}}},panIntoView:function(size){var mapSize=this.map.getSize();var origTL=this.map.getViewPortPxFromLayerPx(new OpenLayers.Pixel(parseInt(this.div.style.left,10),parseInt(this.div.style.top,10)));var dx=0,dy=0;if(origTL.x<0+this._borders.left){dx=origTL.x-this._borders.left;}
if((origTL.x+size.w)>mapSize.w){dx=this._popupSize.w-(mapSize.w-origTL.x);}
if(origTL.y<0+this._borders.top){dy=origTL.y-this._borders.top;}
if((origTL.y+size.h)>mapSize.h-this._borders.bottom){dy=this._popupSize.h-(mapSize.h-origTL.y)+this._borders.bottom;}
if(dx!==0||dy!==0){this.map.pan(dx,dy);}},getRenderedDimensions:function(contentHTML){var w,h;var container=document.createElement("div");container.style.overflow="";container.style.position="absolute";container.style.left="-9999px";var content=document.createElement("div");content.innerHTML=contentHTML;container.appendChild(content);document.body.appendChild(container);w=container.childNodes[0].childNodes[0].childNodes[0].clientWidth;h=container.childNodes[0].childNodes[0].childNodes[0].clientHeight;container.removeChild(content);document.body.removeChild(container);return new OpenLayers.Size(w,h);},getPopupDimensions:function(){if(OpenLayers.Util.getBrowserName()!=='msie'){var images=this.contentDiv.getElementsByTagName("img");var image=null;for(var i=0;i<images.length;++i){image=images[i];if(image.width===0&&image.height===0){image.width=image.naturalWidth?image.naturalWidth:image.width;image.height=image.naturalHeight?image.naturalHeight:image.height;}}}
var copy=this.div.childNodes[0].cloneNode(true);copy.style.position="absolute";copy.style.left="-9999px";var size=this.getPopupDimensionsHelper(copy);if(this._maxSize&&(size.w>this._maxSize.w||size.h>this._maxSize.h)){if(size.w>this._maxSize.w){copy.style.width=this._maxSize.w+"px";}
if(size.h>this._maxSize.h){copy.style.height=this._maxSize.h+"px";}
size=this.getPopupDimensionsHelper(copy);}
return size;},getPopupDimensionsHelper:function(popupDiv){if(this.map&&this.map.div){this.map.div.appendChild(popupDiv);}
else{document.body.appendChild(popupDiv);}
var size=new OpenLayers.Size(popupDiv.clientWidth,popupDiv.clientHeight);if(this.map&&this.map.div){this.map.div.removeChild(popupDiv);}
else{document.body.removeChild(popupDiv);}
return size;},CLASS_NAME:"SAPO.Maps.Popup.SapoPopup"});SAPO.Maps.PoiInfoRenderer={getHTML:function(poi,marker,search,options){var holder=document.createElement('div');var header=document.createElement('div');var content=document.createElement('div');holder.className='content_smapi';header.className='search_pop_header_smapi';content.className='search_pop_content_smapi';holder.appendChild(header);holder.appendChild(content);if(SAPO.Maps.Utils.checkQuery(poi.Name)===false){switch(poi.CategoryId){case'213':holder.className+=' district_pop-up';this.getLocalityHTML(poi,header);break;case'214':holder.className+=' district_pop-up';this.getStreetHTML(poi,header);break;default:this.getCommonHTML(poi,header,content,marker,holder);break;}}else{var coordsStr=poi.Latitude+', '+poi.Longitude;var coords=document.createElement('h1');var category=document.createElement('h2');coords.innerHTML=coordsStr;category.innerHTML='Coordenadas';header.appendChild(coords);header.appendChild(category);}
this.getExtraOptionsHTML(poi,content,marker,search,options);if(OpenLayers.Util.getRenderedDimensions(holder.innerHTML).w>500){holder.style.width='500px';}
return holder;},getLocalityHTML:function(poi,header){var name=document.createElement('h1');name.appendChild(document.createTextNode(poi.Name));header.appendChild(name);var municipalityElement=null;if(poi.Municipality&&poi.Municipality.length>0){municipalityElement=document.createElement('h2');var municipalityName=document.createElement('span');municipalityName.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(poi.Municipality)));municipalityElement.appendChild(document.createTextNode('Concelho: '));municipalityElement.appendChild(municipalityName);}
var districtElement=null;if(poi.District&&poi.District.length>0){districtElement=document.createElement('h2');var districtName=document.createElement('span');districtName.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(poi.District)));districtElement.appendChild(document.createTextNode('Distrito: '));districtElement.appendChild(districtName);header.appendChild(districtElement);}
if(poi.Name!==poi.Municipality&&poi.Name!==poi.District&&municipalityElement!==null){header.insertBefore(municipalityElement,header.childNodes[header.childNodes.length-1]);}},getStreetHTML:function(poi,header){var name=document.createElement('h1');name.appendChild(document.createTextNode(poi.Name));header.appendChild(name);if(poi.Category&&poi.Category.length>0){var h2=document.createElement('h2');var categoryStr=poi.Category;h2.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(categoryStr)));header.appendChild(h2);}
var parishElement=null;if(poi.Parish&&poi.Parish.length>0){parishElement=document.createElement('h2');var parishName=document.createElement('span');parishName.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(poi.Parish)));parishElement.appendChild(document.createTextNode('Freguesia: '));parishElement.appendChild(parishName);header.appendChild(parishElement);}
var municipalityElement=null;if(poi.Municipality&&poi.Municipality.length>0){municipalityElement=document.createElement('h2');var municipalityName=document.createElement('span');municipalityName.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(poi.Municipality)));municipalityElement.appendChild(document.createTextNode('Concelho: '));municipalityElement.appendChild(municipalityName);header.appendChild(municipalityElement);}
var districtElement=null;if(poi.District&&poi.District.length>0){districtElement=document.createElement('h2');var districtName=document.createElement('span');districtName.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(poi.District)));districtElement.appendChild(document.createTextNode('Distrito: '));districtElement.appendChild(districtName);header.appendChild(districtElement);}
var postalCodeElement=null;if(poi.ZipCode&&poi.ZipCode.length>0){var zc=poi.ZipCode;if(poi.ZipCode.length>4){zc=(poi.ZipCode.substring(0,4)+"-"+poi.ZipCode.substring(4));}
postalCodeElement=document.createElement('h2');var postalCode=document.createElement('span');postalCode.appendChild(document.createTextNode(zc));postalCodeElement.appendChild(document.createTextNode('Cód Postal: '));postalCodeElement.appendChild(postalCode);header.appendChild(postalCodeElement);}},getCommonHTML:function(poi,header,content,marker,holder){var name=document.createElement('h1');name.appendChild(document.createTextNode(poi.Name));header.appendChild(name);if(poi.Category&&poi.Category.length>0){var h2=document.createElement('h2');var categoryStr=poi.Category;h2.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(categoryStr)));header.appendChild(h2);}
if(poi.DetailXml&&poi.DetailXml.Details&&poi.DetailXml.Details.Pictures&&poi.DetailXml.Details.Pictures.Picture){var image=null;var images=poi.DetailXml.Details.Pictures.Picture.length?poi.DetailXml.Details.Pictures.Picture:[poi.DetailXml.Details.Pictures.Picture];if(!(images instanceof Array)){images=[images];}
for(var i=0;i<images.length;++i){if(images[i].primary==="true"){image=images[i];break;}}
if(!image){image=images[0];}
var div_img=document.createElement('div');div_img.className='search_photo';div_img.style.width='0px';div_img.style.height='0px';div_img.style.display='none';var img=document.createElement('img');var a_img=document.createElement('a');a_img.target='_blank';a_img.href=image.value?image.value:image;img.style.width='150px';img.style.height='auto';var imgLoaded=function(){OpenLayers.Event.stopObservingElement(img);div_img.style.width='150px';div_img.style.height='auto';div_img.style.display='block';if(OpenLayers.Util.getRenderedDimensions(holder.innerHTML).w>500){holder.style.width='500px';}
if(marker&&marker.hasOpenedPopup()){marker.popup.contentUpdated();}};OpenLayers.Event.observe(img,'load',imgLoaded);var src=image.value?image.value:image;if(window.location.protocol.indexOf('https')!==-1){src=src.replace(/http:\/\/map/,'https://imgs');if(src.indexOf('https://')===-1){src='';}}
img.src=src;a_img.appendChild(img);div_img.appendChild(a_img);content.appendChild(div_img);}
var addressAndContacts=document.createElement('div');addressAndContacts.className='search_text';var address1=document.createElement('span');var address2=document.createElement('span');address1.className='address_pop_content_smapi';address2.className='address_pop_content_smapi';if(poi.Street&&poi.Street.length>0){address1.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(poi.Street)));}
if(poi.Parish&&poi.Parish.length>0){if(address1.innerHTML.length>0){address1.appendChild(document.createTextNode(', '));}
address1.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(poi.Parish)));}
if(poi.Municipality&&poi.Municipality.length>0&&poi.Municipality!==poi.Parish){if(address1.innerHTML.length>0){address1.appendChild(document.createTextNode(', '));}
address2.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(poi.Municipality)));}
if(poi.District&&poi.District.length>0&&poi.District!==poi.Municipality){if(address2.innerHTML.length>0){address2.appendChild(document.createTextNode(', '));}
address2.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(poi.District)));}
addressAndContacts.appendChild(address1);addressAndContacts.appendChild(address2);if(poi.ZipCode&&poi.ZipCode.length>0){var zc=poi.ZipCode;if(poi.ZipCode.length>4){zc=(poi.ZipCode.substring(0,4)+'-'+poi.ZipCode.substring(4));}
var postalCodeElement=document.createElement('span');postalCodeElement.className='address_pop_content_smapi zipcode_address_pop_content_smapi';postalCodeElement.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(zc)));addressAndContacts.appendChild(postalCodeElement);}
if(poi.Phone&&poi.Phone.length>0){var phoneElement=document.createElement('span');phoneElement.className='phone_pop_content_smapi';var phoneNumber=poi.Phone.substring(0,3)+' '+poi.Phone.substring(3,6)+' '+poi.Phone.substring(6,9);phoneElement.appendChild(document.createTextNode(phoneNumber));addressAndContacts.appendChild(phoneElement);}
if(poi.Fax&&poi.Fax.length>0){var faxElement=document.createElement('span');faxElement.className='fax_pop_content_smapi';var faxNumber=poi.Fax.substring(0,3)+' '+poi.Fax.substring(3,6)+' '+poi.Fax.substring(6,9);faxElement.appendChild(document.createTextNode(faxNumber));addressAndContacts.appendChild(faxElement);}
if(poi.URL&&poi.URL.length>0){var siteElement=document.createElement('span');var site=document.createElement('a');siteElement.className='url_pop_content_smapi';site.href=poi.URL;site.target='_blank';site.innerHTML='Ver Site';siteElement.appendChild(site);addressAndContacts.appendChild(siteElement);}
if(poi.EMail&&poi.EMail.length>0){var mailElement=document.createElement('span');var mail=document.createElement('a');mailElement.className='mail_pop_content_smapi';mail.href='mailto:'+poi.EMail;mail.innerHTML=poi.EMail;mailElement.appendChild(mail);addressAndContacts.appendChild(mailElement);}
if(poi.DetailXml&&poi.DetailXml!=='null'){var moreInfoElement=document.createElement('span');var moreInfoLink=document.createElement('a');moreInfoElement.className='moreinfo_pop_content_smapi';moreInfoLink.id='moreInfoId';moreInfoLink.href='http://mapas.sapo.pt/POIDetails.aspx?poiid='+poi.POIId;moreInfoLink.innerHTML='Mais informa&ccedil;&otilde;es';moreInfoLink.target='_blank';moreInfoElement.appendChild(moreInfoLink);addressAndContacts.appendChild(moreInfoElement);}
content.appendChild(addressAndContacts);var sourceElement=document.createElement('p');var sourceLink=document.createElement('a');sourceElement.className='smapi_popup_content_datasource';sourceLink.innerHTML=poi.Source;sourceLink.href='#';sourceLink.target='_blank';sourceElement.innerHTML+='Fonte: ';sourceElement.appendChild(sourceLink);content.parentNode.appendChild(sourceElement);},getExtraOptionsHTML:function(poi,content,marker,search,options){var wrapperOptions=document.createElement('div');var wrapperDetails=document.createElement('div');var coordinates=document.createElement('a');var whatsHere=document.createElement('a');wrapperOptions.className='smapi_popup_content_extra_actions';wrapperDetails.className='smapi_popup_content_extra_actions_details';wrapperDetails.style.display='none';if(options instanceof Array){var option,a_option;for(var i=0;i<options.length;++i){option=options[i];a_option=document.createElement('a');a_option.href='#';a_option.innerHTML=option.name;a_option._option=option;OpenLayers.Event.observe(a_option,'click',function(evt){wrapperDetails.innerHTML='';marker.popup.contentUpdated();var context=this._option?this._option:evt.srcElement._option;context.func.apply(context.context?context.context:this,[poi]);OpenLayers.Event.stop(evt);});wrapperOptions.appendChild(a_option);}}
coordinates.href='#';whatsHere.href='#';coordinates.innerHTML='Coordenadas';whatsHere.innerHTML='Pesquisar nas imedia&ccedil;&otilde;es';if(search instanceof SAPO.Maps.Search){wrapperOptions.appendChild(whatsHere);}
wrapperOptions.appendChild(coordinates);content.appendChild(wrapperOptions);content.appendChild(wrapperDetails);OpenLayers.Event.observe(coordinates,'click',function(evt){wrapperDetails.innerHTML='';var decTitle=document.createElement('span');var dmsTitle=document.createElement('span');var decCoords=document.createElement('span');var dmsCoords=document.createElement('span');decCoords.className='smapi_popup_selectable_text';dmsCoords.className='smapi_popup_selectable_text';var latlonDMS=SAPO.Maps.Utils.convertDecimalToDMS(Number(poi.Latitude),Number(poi.Longitude));decTitle.innerHTML='Coordenadas decimais: ';dmsTitle.innerHTML='Coordenadas DMS: ';decCoords.innerHTML=SAPO.Maps.Utils.htmlEntityDecode(poi.Latitude+', '+poi.Longitude);dmsCoords.innerHTML=SAPO.Maps.Utils.htmlEntityDecode(latlonDMS.lat+' '+latlonDMS.lon);wrapperDetails.appendChild(decTitle);wrapperDetails.appendChild(decCoords);wrapperDetails.appendChild(document.createElement('br'));wrapperDetails.appendChild(dmsTitle);wrapperDetails.appendChild(dmsCoords);wrapperDetails.style.display='block';marker.popup.contentUpdated();OpenLayers.Event.stop(evt);}.bindObj(this));if(search instanceof SAPO.Maps.Search){whatsHere.marker=marker;OpenLayers.Event.observe(whatsHere,'click',function(evt){wrapperDetails.innerHTML='';var wrapper=document.createElement('div');var textBox_part1=document.createElement('label');var textBox_part2=document.createElement('input');var button_part1=document.createElement('p');var button_part2=document.createElement('span');var button_part3=document.createElement('input');var div_clear=document.createElement('div');wrapper.className='smapi_popup_content_extra_actions_details_whats_here';textBox_part2.type='text';button_part1.className='submit_btn';button_part2.className='rimg_button';button_part3.type='button';button_part3.value='Pesquisar';var doSearchFn=function(evt){search.searchNearLonLat(textBox_part2.value,new OpenLayers.LonLat(Number(poi.Longitude),Number(poi.Latitude)));}.bindObj(this);OpenLayers.Event.observe(textBox_part2,'keydown',function(evt){if(evt.keyCode===Event.KEY_RETURN){doSearchFn();}});OpenLayers.Event.observe(button_part3,'click',doSearchFn);button_part1.appendChild(document.createElement('span'));button_part1.appendChild(button_part2);button_part2.appendChild(button_part3);wrapper.appendChild(textBox_part1);wrapper.appendChild(textBox_part2);wrapper.appendChild(button_part1);wrapperDetails.appendChild(wrapper);wrapperDetails.appendChild(document.createElement('hr'));wrapperDetails.style.display='block';textBox_part2.focus();marker.popup.contentUpdated();OpenLayers.Event.stop(evt);}.bindObj(this));}}};SAPO.Maps.Overlay=OpenLayers.Class({layer:null,draggable:false,popup:null,tooltip:null,events:null,dragRegistered:false,options:null,initialize:function(options){this.options=OpenLayers.Util.extend({popupAnchor:new OpenLayers.Pixel(0,0),tooltipAnchor:new OpenLayers.Pixel(0,0)},options);this.events={};},destroy:function(){},getFeature:function(){},removed:function(){if(this.popup){this.layer.map.removePopup(this.popup);}
if(this.tooltip){this.layer.map.removeControl(this.tooltip);}
var listeners=false;for(var e in this.events){listeners=this.events[e];if(listeners){for(var i=listeners.length-1;i>=0;--i){this.unRegisterFromMapHandler(e,listeners[i].context,listeners[i].func);}}}
if(this.draggingEnabled()){this.layer.map.dragControl.removeFeature(this.getFeature());if(!this.dragRegistered&&this.hasOpenedPopup()){this.dragRegistered=this.unRegisterFromMapHandler('dragstart',this,this.closePopup);}
if(!this.dragRegistered&&this.hasOpenedTooltip()){this.dragRegistered=this.unRegisterFromMapHandler('dragstart',this,this.closeTooltip);}}
this.layer=null;},setLayer:function(layer){this.layer=layer;if(this.popup){this.layer.map.addPopup(this.popup,false);}
if(this.tooltip){this.layer.map.addControl(this.tooltip);this.tooltip.show();}
var listeners=false;for(var e in this.events){listeners=this.events[e];if(listeners){for(var i=listeners.length-1;i>=0;--i){this.registerOnMapHandler(e,listeners[i].context,listeners[i].func);}}}
if(this.draggingEnabled()){this.layer.map.dragControl.addFeature(this.getFeature());if(this.dragRegistered){this.dragRegistered=this.registerOnMapHandler('dragstart',this,this.closePopup);this.dragRegistered=this.registerOnMapHandler('dragstart',this,this.closeTooltip);}}},openPopup:function(content,options){if(this.popup){return;}
popupAnchor=this.getPopupAnchor().transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));if(!popupAnchor){return;}
var _this=this;this.popup=new SAPO.Maps.Popup.SapoPopup(popupAnchor.toShortString(),popupAnchor,null,content,true,function(){_this.closePopup.apply(_this,[]);},this.options.popupAnchor,options?options.borders:null,options?options.pan:null);if(this.layer){this.layer.map.addPopup(this.popup,false);this.dragRegistered=this.registerOnMapHandler('dragstart',this,this.closePopup);}
this.notifyListeners('popupopened',[]);},closePopup:function(){if(!this.popup){return;}
this.popup.div.style.visibility="hidden";if(this.layer){this.layer.map.removePopup(this.popup);this.dragRegistered=this.unRegisterFromMapHandler('dragstart',this,this.closePopup);}
this.popup=null;this.notifyListeners('popupclosed',[]);},hasOpenedPopup:function(){if(this.popup){return true;}
return false;},hidePopup:function(){if(this.popup){this.popup.hide();}},showPopup:function(){if(this.popup){this.popup.show();}},openTooltip:function(message,options){if(this.tooltip){return;}
lonlat=this.getTooltipAnchor();if(!lonlat){return;}
var _this=this;if(options&&options.arrow){x=(this.options.tooltipAnchor.x*-1)-5;if(x<0){x=0;}
var direction='up';if(this.options.tooltipAnchor.y<0){direction='down';}
OpenLayers.Util.extend(options,{arrowLeft:x,arrowDirection:direction});}
this.tooltip=new SAPO.Maps.Control.Tooltip(message,null,options);if(this.layer){px=this.layer.map.getContainerPixelFromLonLat(lonlat).offset(this.options.tooltipAnchor);this.layer.map.addControl(this.tooltip,px);this.tooltip.show();this.dragRegistered=this.registerOnMapHandler('dragstart',this,this.closeTooltip);}
this.notifyListeners('tooltipopened',[]);},closeTooltip:function(){if(!this.tooltip){return;}
if(this.layer){this.tooltip.hide();this.layer.map.removeControl(this.tooltip);this.dragRegistered=this.unRegisterFromMapHandler('dragstart',this,this.closeTooltip);}
this.tooltip=null;this.notifyListeners('tooltipclosed',[]);},hasOpenedTooltip:function(){if(this.tooltip){return true;}
return false;},hideTooltip:function(){if(this.tooltip){this.tooltip.hide();}},showTooltip:function(){if(this.tooltip){this.tooltip.show();}},enableDragging:function(){if(this.draggable){return;}
this.draggable=true;if(this.layer&&this.layer.map){this.layer.map.dragControl.addFeature(this.getFeature());}
this.notifyListeners('enabledragging',[this]);},disableDragging:function(){if(!this.draggable){return;}
this.draggable=false;if(this.layer&&this.layer.map){this.layer.map.dragControl.removeFeature(this.getFeature());}
this.notifyListeners('disabledragging',[this]);},draggingEnabled:function(){return this.draggable;},getPopupAnchor:function(){return null;},getTooltipAnchor:function(){return null;},clone:function(){return null;},registerEvent:function(eventType,context,func){this.registerOnMapHandler(eventType,context,func);if(!this.events[eventType]){this.events[eventType]=[];}
var obj={func:func,context:context};this.events[eventType].push(obj);},unRegisterEvent:function(eventType,context,func){this.unRegisterFromMapHandler(eventType,context,func);var evts=this.events[eventType]?this.events[eventType]:[];for(var i=0;i<evts.length;++i){if(context==evts[i].context&&func==evts[i].func){evts.splice(i,1);return true;}}
return false;},registerOnMapHandler:function(eventType,context,func){if(this.layer&&this.layer.map){var map=this.layer.map;if(map.dragControl.supportEvent(eventType)===true){map.dragControl.registerEvent(this.getFeature(),eventType,context,func,[this]);}
else{if(map.featureEventHandler.supportEvent(eventType)===true){map.featureEventHandler.registerEvent(this.getFeature(),eventType,context,func,[this]);}}
return true;}
return false;},unRegisterFromMapHandler:function(eventType,context,func){if(this.layer&&this.layer.map){var map=this.layer.map;if(map.dragControl.supportEvent(eventType)===true){map.dragControl.unRegisterEvent(this.getFeature(),eventType,context,func,[this]);}
else{if(map.featureEventHandler.supportEvent(eventType)===true){map.featureEventHandler.unRegisterEvent(this.getFeature(),eventType,context,func,[this]);}}
return true;}
return false;},notifyListeners:function(eventType,args){var evts=this.events[eventType]?this.events[eventType]:[];args=args?args:[];var func,context;for(var i=0;i<evts.length;++i){func=evts[i].func;context=evts[i].context;func.apply(context,args);}},updatePopupPosition:function(){if(!this.hasOpenedPopup()){return;}
var lonlat=this.getPopupAnchor();var px=this.layer.map.getContainerPixelFromLonLat(lonlat);this.popup.moveTo(px);},updateTooltipPosition:function(){if(!this.hasOpenedTooltip()){return;}
var lonlat=this.getTooltipAnchor();if(!lonlat){return;}
var px=this.layer.map.getContainerPixelFromLonLat(lonlat).offset(this.options.popupAnchor);this.tooltip.setPosition(px);},EVENT_TYPES:['popupopened','popupclosed','click','rightclick','dblclick','mousedown','mouseup','mouseover','mouseout','dragstart','drag','dragend','enabledragging','disabledragging','tooltipopened','tooltipclosed'],CLASS_NAME:'SAPO.Maps.Overlay'});SAPO.Maps.Overlay.fromFeature=function(feature){if(feature.geometry instanceof OpenLayers.Geometry.Polygon){var polygon=new SAPO.Maps.Polygon([]);polygon.feature=feature;return polygon;}
if(feature.geometry instanceof OpenLayers.Geometry.LineString){var polyline=new SAPO.Maps.Polyline([]);polyline.feature=feature;return polyline;}
if(feature.geometry instanceof OpenLayers.Geometry.Point){var marker=new SAPO.Maps.Marker(new OpenLayers.LonLat(0,0));feature.style=marker.feature.style;marker.feature=feature;return marker;}
return null;};SAPO.Maps.Markers=OpenLayers.Class({markers:null,map:null,zIndexToSet:null,initialize:function(markersLayerName){markersLayerName=markersLayerName?markersLayerName:"Markers Layer";this.markers=[];},addMarker:function(marker){this.markers.push(marker);marker.feature.overlay=marker;if(this.map){var vectorLayer=this.map.getOverlaysContainer();vectorLayer.addFeatures([marker.feature]);marker.setLayer(vectorLayer);}},addMarkers:function(markersArray){for(var i=0;i<markersArray.length;++i){this.addMarker(markersArray[i]);}},getBounds:function(){var markers=this.getMarkers();if(markers.length===0){return null;}
var left=null;var right=null;var top=null;var bottom=null;var lonlat;for(var i=0;i<markers.length;++i){lonlat=markers[i].getLonLat();if(!left&&!right&&!top&&!bottom){left=right=lonlat.lon;bottom=top=lonlat.lat;}
else{if(lonlat.lon<left){left=lonlat.lon;}
if(lonlat.lat<bottom){bottom=lonlat.lat;}
if(lonlat.lon>right){right=lonlat.lon;}
if(lonlat.lat>top){top=lonlat.lat;}}}
return new OpenLayers.Bounds(left,bottom,right,top);},removeMarker:function(marker){if(this.map){var vectorLayer=this.map.getOverlaysContainer();vectorLayer.removeFeatures([marker.feature]);}
for(var i=0;i<this.markers.length;++i){if(marker===this.markers[i]){this.markers.splice(i,1);break;}}
marker.overlay=null;marker.removed();},getMarkers:function(){return this.markers;},removeMarkers:function(){while(this.markers.length>0){this.removeMarker(this.markers[0]);}},getZIndex:function(){if(this.map){return this.map.getOverlaysContainer().getZIndex();}
return-1;},setZIndex:function(zIndex){if(this.map){this.map.getOverlaysContainer().setZIndex(zIndex);}
else{this.zIndexToSet=zIndex;}},setMap:function(map){this.map=map;if(this.zIndexToSet!==null){this.setZIndex(this.zIndexToSet);}
var vectorLayer=this.map.getOverlaysContainer();var marker;for(var i=0;i<this.markers.length;++i){marker=this.markers[i];vectorLayer.addFeatures([marker.feature]);marker.setLayer(vectorLayer);}},unloadLayer:function(){var vectorLayer=this.map.getOverlaysContainer();for(var i=0;i<this.markers.length;++i){this.markers[i].removed();vectorLayer.removeFeatures([this.markers[i].feature]);}},CLASS_NAME:'SAPO.Maps.Markers'});SAPO.Maps.Marker=OpenLayers.Class(SAPO.Maps.Overlay,{style:null,feature:null,ishidden:false,initialize:function(lonlat,options,style){var pA=(options&&options.popupAnchor)?options.popupAnchor:new OpenLayers.Pixel(0,-28);var tA=(options&&options.tooltipAnchor)?options.tooltipAnchor:new OpenLayers.Pixel(-14,5);SAPO.Maps.Overlay.prototype.initialize.apply(this,[{popupAnchor:pA,tooltipAnchor:tA}]);this.style={markerImage:'http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Markers/new/pin.png',markerShadow:'',markerOpacity:1,size:new OpenLayers.Size(22,28),markerAnchor:new OpenLayers.Pixel(-11,-28),shadowAnchor:new OpenLayers.Pixel(0,0),radius:15,display:'',fillColor:null,fillOpacity:1,strokeColor:null,strokeWidth:null,strokeOpacity:1,label:'',labelOpacity:1,labelColor:'black',labelSize:'12px',labelFont:'Courier New, monospace',labelWeight:'normal',labelAnchor:new OpenLayers.Pixel(0,0),zIndex:10};OpenLayers.Util.extend(this,options);if(style){this.style=OpenLayers.Util.extend(this.style,style);}
var coords=lonlat.clone().transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));this.feature=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(coords.lon,coords.lat),null,this._getStyle());this.feature.overlay=this;},destroy:function(){this.feature.destroy();this.feature=null;},getFeature:function(){return this.feature;},getPopupAnchor:function(){return this.getLonLat();},getTooltipAnchor:function(){return this.getLonLat();},clone:function(){var newStyle=OpenLayers.Util.extend({},this.style);var m=new SAPO.Maps.Marker(this.getLonLat(),{draggable:this.draggingEnabled()},newStyle);return m;},getLonLat:function(){var lon=this.feature.geometry.x;var lat=this.feature.geometry.y;return new OpenLayers.LonLat(lon,lat).transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));},setLonLat:function(lonlat){var coords=lonlat.clone().transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));var deltax=coords.lon-this.feature.geometry.x;var deltay=coords.lat-this.feature.geometry.y;this.feature.geometry.move(deltax,deltay);if(this.hasOpenedPopup()){this.popup.lonlat=lonlat.transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));this.popup.updatePosition();}
this.updateTooltipPosition();this.feature.style=this._getStyle();this.layer.drawFeature(this.feature);},setStyle:function(style){if(!style){return;}
this.style=OpenLayers.Util.extend(this.style,style);this.feature.style=this._getStyle();if(this.layer){this.layer.drawFeature(this.feature);}},getStyle:function(){return this.style;},show:function(){if(!this.isHidden()){return;}
this.ishidden=false;this.style.display='';if(this.hasOpenedPopup()){this.showPopup();}
if(this.hasOpenedTooltip()){this.showTooltip();}
this.layer.drawFeature(this.feature,this._getStyle());this.notifyListeners('visibilitychange');},hide:function(){if(this.isHidden()){return;}
this.ishidden=true;this.style.display='none';if(this.hasOpenedPopup()){this.hidePopup();}
if(this.hasOpenedTooltip()){this.hideTooltip();}
this.layer.drawFeature(this.feature,this._getStyle());this.notifyListeners('visibilitychange');},isHidden:function(){return this.ishidden;},_getStyle:function(){return{externalGraphic:this.style.markerImage,graphicOpacity:this.style.markerOpacity,backgroundGraphic:this.style.markerShadow,graphicXOffset:this.style.markerAnchor.x,graphicYOffset:this.style.markerAnchor.y,backgroundXOffset:this.style.shadowAnchor.x,backgroundYOffset:this.style.shadowAnchor.y,graphicZIndex:this.style.zIndex,backgroundGraphicZIndex:this.style.zIndex-1,pointRadius:this.style.radius,graphicWidth:this.style.size.w,graphicHeight:this.style.size.h,display:this.style.display,label:this.style.label,labelOpacity:this.style.labelOpacity,labelXOffset:this.style.labelAnchor.x,labelYOffset:this.style.labelAnchor.y,fontColor:this.style.labelColor,fontSize:this.style.labelSize,fontFamily:this.style.labelFont,fontWeight:this.style.labelWeight,fillColor:this.style.fillColor,fillOpacity:this.style.fillOpacity,strokeColor:this.style.strokeColor,strokeWidth:this.style.strokeWidth,strokeOpacity:this.style.strokeOpacity};},EVENT_TYPES:['click','dblclick','mousedown','mouseup','mouseover','mouseout','popupopened','popupclosed','dragstart','drag','dragend','visibilitychange','enabledragging','disabledragging','tooltipopened','tooltipclosed'],CLASS_NAME:'SAPO.Maps.Marker'});SAPO.Maps.Polyline=OpenLayers.Class(SAPO.Maps.Overlay,{style:null,feature:null,ishidden:false,initialize:function(lonlats,style){SAPO.Maps.Overlay.prototype.initialize.apply(this,[]);this.style={strokeColor:'#ee9900',strokeOpacity:1,strokeWidth:2,strokeLinecap:'round',strokeDashstyle:'solid',pointRadius:6,cursor:'',display:''};if(style){this.style=OpenLayers.Util.extend(this.style,style);}
var points=[];var lonlat;for(var i=0;i<lonlats.length;++i){lonlat=lonlats[i].clone().transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));points.push(new OpenLayers.Geometry.Point(lonlat.lon,lonlat.lat));}
this.feature=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(points),null,this.style);},destroy:function(){this.feature.destroy();this.feature=null;},getFeature:function(){return this.feature;},getPopupAnchor:function(){var centroid=this.feature.geometry.getCentroid();var centroidLonLat=new OpenLayers.LonLat(centroid.x,centroid.y);centroidLonLat.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));return centroidLonLat;},clone:function(){var newStyle=OpenLayers.Util.extend({},this.style);var cloned=new SAPO.Maps.Polyline([],newStyle);cloned.feature=this.feature.clone();return cloned;},getVertexCount:function(){return this.feature.geometry.components.length;},getVertex:function(index){if(index<0||index>=this.feature.geometry.components.length){return null;}
var point=this.feature.geometry.components[index];var lonlat=new OpenLayers.LonLat(point.x,point.y);lonlat.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));return lonlat;},getLonLats:function(){var arr=[];var length=this.getVertexCount();var lonlat=false;for(var i=0;i<length;++i){arr.push(this.getVertex(i));}
return arr;},getLength:function(){return this.feature.geometry.getLength();},getBounds:function(){var bounds=this.feature.geometry.getBounds().clone();bounds.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));return bounds;},hide:function(){if(this.ishidden){return;}
this.style.display='none';this.ishidden=true;if(!this.layer){return;}
this.layer.drawFeature(this.feature,this.style);this.notifyListeners('visibilitychange',[false]);},insertVertex:function(index,lonlat){var coords=lonlat.clone().transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));var point=new OpenLayers.Geometry.Point(coords.lon,coords.lat);this.feature.geometry.addPoint(point,index);if(this.layer){this.layer.drawFeature(this.feature,this.style);}},isHidden:function(){return this.ishidden;},show:function(){if(!this.ishidden){return;}
this.style.display='';this.ishidden=false;if(!this.layer){return;}
this.layer.drawFeature(this.feature,this.style);this.notifyListeners('visibilitychange',[true]);},setStyle:function(style){if(!style){return;}
this.style=OpenLayers.Util.extend(this.style,style);this.feature.style=this.style;if(this.layer){this.layer.drawFeature(this.feature,this.style);}},getStyle:function(){return this.style;},EVENT_TYPES:['click','dbclick','mousedown','mouseup','mouseover','mouseout','visibilitychange'],CLASS_NAME:'SAPO.Maps.Polyline'});SAPO.Maps.Polygon=OpenLayers.Class(SAPO.Maps.Overlay,{style:null,ishidden:false,feature:null,initialize:function(lonlats,style){SAPO.Maps.Overlay.prototype.initialize.apply(this,[]);this.style={fillColor:'#ee9900',fillOpacity:0.8,strokeColor:'#ee9900',strokeOpacity:0.8,strokeWidth:2,strokeLinecap:'round',strokeDashstyle:'solid',pointRadius:6,cursor:'',display:''};if(style){this.style=OpenLayers.Util.extend(this.style,style);}
var points=[];var lonlat;for(var i=0;i<lonlats.length;++i){lonlat=lonlats[i].clone().transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));points.push(new OpenLayers.Geometry.Point(lonlat.lon,lonlat.lat));}
var ring=new OpenLayers.Geometry.LinearRing(points);var polygon=new OpenLayers.Geometry.Polygon([ring]);this.feature=new OpenLayers.Feature.Vector(polygon,null,this.style);},destroy:function(){this.feature.destroy();this.feature=null;},getFeature:function(){return this.feature;},getPopupAnchor:function(){var centroid=this.feature.geometry.getCentroid();var centroidLonLat=new OpenLayers.LonLat(centroid.x,centroid.y);centroidLonLat.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));return centroidLonLat;},getTooltipAnchor:function(){var centroid=this.feature.geometry.getCentroid();var centroidLonLat=new OpenLayers.LonLat(centroid.x,centroid.y);centroidLonLat.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));return centroidLonLat;},clone:function(){var newStyle=OpenLayers.Util.extend({},this.style);var cloned=new SAPO.Maps.Polygon(this.getLonLats(),newStyle);return cloned;},getVertexCount:function(){return this.feature.geometry.components[0].components.length-1;},getVertex:function(index){if(index<0||index>=this.feature.geometry.components[0].components.length){return null;}
var point=this.feature.geometry.components[0].components[index];var lonlat=new OpenLayers.LonLat(point.x,point.y);return lonlat.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));},getLonLats:function(){var arr=[];var length=this.getVertexCount();var lonlat=false;for(var i=0;i<length;++i){arr.push(this.getVertex(i));}
return arr;},getArea:function(){return this.feature.geometry.getArea();},getBounds:function(){var bounds=this.feature.geometry.getBounds().clone();bounds.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));return bounds;},hide:function(){if(this.ishidden){return;}
this.style.display='none';this.ishidden=true;if(!this.layer){return;}
this.layer.drawFeature(this.feature,this.style);this.notifyListeners('visibilitychange',[false]);},insertVertex:function(index,lonlat){var ring=this.feature.geometry.components[0];var coords=lonlat.clone().transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));var point=new OpenLayers.Geometry.Point(coords.lon,coords.lat);ring.addComponent(point,index);if(this.layer){this.layer.drawFeature(this.feature,this.style);}},isHidden:function(){return this.ishidden;},show:function(){if(!this.ishidden){return;}
this.style.display='';this.ishidden=false;if(!this.layer){return;}
this.layer.drawFeature(this.feature,this.style);this.notifyListeners('visibilitychange',[true]);},setStyle:function(style){if(!style){return;}
this.style=OpenLayers.Util.extend(this.style,style);this.feature.style=this.style;if(this.layer){this.layer.drawFeature(this.feature,this.style);}},getStyle:function(){return this.style;},EVENT_TYPES:['click','dbclick','mousedown','mouseup','mouseover','mouseout','visibilitychange'],CLASS_NAME:'SAPO.Maps.Polygon'});SAPO.Maps.Circle=OpenLayers.Class(SAPO.Maps.Polygon,{centroid:null,radius:null,sides:null,initialize:function(centroid,radius,sides,style){if(!sides){this.sides=40;}
OpenLayers.Util.extend(this,{centroid:centroid,radius:radius});SAPO.Maps.Polygon.prototype.initialize.apply(this,[this._getCircleLonLats(),style]);this.registerEvent('dragend',this,this._dragEndHandler);},destroy:function(){this.unRegisterEvent('dragend',this,this._dragEndHandler);SAPO.Maps.Polygon.prototype.destroy.apply(this,[]);},clone:function(){var newStyle=OpenLayers.Util.extend({},this.style);var cloned=new SAPO.Maps.Circle(this.centroid.clone(),this.radius,this.sides,newStyle);return cloned;},getCentroid:function(){return this.feature.geometry.getCentroid().transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));},setCentroid:function(centroid){if(!centroid){return;}
this.centroid=OpenLayers.Util.extend({},centroid);this.feature.move(new OpenLayers.LonLat(this.centroid.x,this.centroid.y).transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913")));},getRadius:function(){return this.radius;},setRadius:function(radius){if(!radius){return;}
this.radius=radius;this._recreate();},getSides:function(){return this.sides;},setSides:function(sides){if(!sides){return;}
this.sides=sides;this._recreate();},_getCircleLonLats:function(){var angle=Math.PI*((1/this.sides)-(1/2));var rotatedAngle,x,y;var lonlats=[];var transformedCentroid=this.centroid.clone().transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));for(var i=0;i<this.sides;++i){rotatedAngle=angle+(i*2*Math.PI/this.sides);x=transformedCentroid.x+(this.radius*Math.cos(rotatedAngle));y=transformedCentroid.y+(this.radius*Math.sin(rotatedAngle));lonlats.push(new OpenLayers.LonLat(x,y).transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326")));}
return lonlats;},_recreate:function(){if(this.layer){this.layer.removeFeatures([this.feature]);}
var points=[];var lonlats=this._getCircleLonLats();var lonlat;for(var i=0;i<lonlats.length;++i){lonlat=lonlats[i].clone().transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));points.push(new OpenLayers.Geometry.Point(lonlat.lon,lonlat.lat));}
var ring=new OpenLayers.Geometry.LinearRing(points);var polygon=new OpenLayers.Geometry.Polygon([ring]);this.feature.geometry=polygon;if(this.layer){this.layer.addFeatures([this.feature]);}},_dragEndHandler:function(e){var centroid=this.feature.geometry.getCentroid();this.centroid=centroid.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));},CLASS_NAME:'SAPO.Maps.Circle'});SAPO.Maps.Poi=OpenLayers.Class({POIId:null,Name:null,CountryId:null,Country:null,DistrictId:null,District:null,MunicipalityId:null,Municipality:null,ParishId:null,Parish:null,Address:null,Latitude:null,Longitude:null,CategoryId:null,Category:null,initialize:function(info){OpenLayers.Util.extend(this,info);},loadPOI:function(namespace,GISpoi){this.POIId=GISpoi[namespace+':'+'POIId'];this.Name=GISpoi[namespace+':'+'Name'];this.CountryId=GISpoi[namespace+':'+'CountryId'];this.Country=GISpoi[namespace+':'+'Country'];this.DistrictId=GISpoi[namespace+':'+'DistrictId'];this.District=GISpoi[namespace+':'+'District'];this.MunicipalityId=GISpoi[namespace+':'+'MunicipalityId'];this.Municipality=GISpoi[namespace+':'+'Municipality'];this.ParishId=GISpoi[namespace+':'+'ParishId'];this.Parish=GISpoi[namespace+':'+'Parish'];this.Address=GISpoi[namespace+':'+'Address'];this.ZipCode=GISpoi[namespace+':'+'ZipCode'];this.Phone=GISpoi[namespace+':'+'Phone'];this.Fax=GISpoi[namespace+':'+'Fax'];this.LocalityId=GISpoi[namespace+':'+'LocalityId'];this.Locality=GISpoi[namespace+':'+'Locality'];this.StreetId=GISpoi[namespace+':'+'StreetId'];this.Street=GISpoi[namespace+':'+'Street'];this.HouseNumber=GISpoi[namespace+':'+'HouseNumber'];this.Latitude=GISpoi[namespace+':'+'Latitude'];this.Longitude=GISpoi[namespace+':'+'Longitude'];this.Distance=GISpoi[namespace+':'+'Distance'];this.CategoryId=GISpoi[namespace+':'+'CategoryId'];this.Category=GISpoi[namespace+':'+'Category'];this.MimeType=GISpoi[namespace+':'+'MimeType'];this.SourceId=GISpoi[namespace+':'+'SourceId'];this.Source=GISpoi[namespace+':'+'Source'];this.POISourceId=GISpoi[namespace+':'+'POISourceId'];this.URL=GISpoi[namespace+':'+'URL'];this.EMail=GISpoi[namespace+':'+'EMail'];this.PublicationDate=GISpoi[namespace+':'+'PublicationDate'];this.RegistrationDate=GISpoi[namespace+':'+'RegistrationDate'];this.ExpirationDate=GISpoi[namespace+':'+'ExpirationDate'];this.Description=GISpoi[namespace+':'+'Description'];this.Detail=GISpoi[namespace+':'+'Detail'];this.Tags=GISpoi[namespace+':'+'Tags'];this.MatchLevelId=GISpoi[namespace+':'+'MatchLevelId'];this.MatchLevel=GISpoi[namespace+':'+'MatchLevel'];this.TrustLevelId=GISpoi[namespace+':'+'TrustLevelId'];this.TrustLevel=GISpoi[namespace+':'+'TrustLevel'];this.LastModified=GISpoi[namespace+':'+'LastModified'];this.Revision=GISpoi[namespace+':'+'Revision'];this.DetailXml=GISpoi[namespace+':'+'DetailXml'];},CLASS_NAME:"SAPO.Maps.Poi"});SAPO.Maps.GenericSearcher=OpenLayers.Class({requester:null,cancelLastRequest:false,requestId:null,initialize:function(options){OpenLayers.Util.extend(this,options);this.requester=SAPO.Maps.Request.prototype.getRequester();},request:function(url,callbacks,memorizeReqId){this.cancelRequest(this.requestId);var id=this.requester.request(url,{timeout:4,onComplete:this.onComplete.bindObj(this),onTimeout:function(){this.onTimeout(callbacks);}.bindObj(this),optOnComplete:callbacks});if(memorizeReqId){this.requestId=id;}
return id;},cancelRequest:function(requestId){if(requestId&&this.cancelLastRequest){this.requester.cancel(requestId);}},onComplete:function(obj,callbacks){this.requestId=null;if(callbacks&&callbacks.onComplete){var scope=callbacks.scope?callbacks.scope:this;callbacks.onComplete.apply(scope,[obj,callbacks.optOnComplete]);}},onTimeout:function(callbacks){this.requestId=null;if(callbacks&&callbacks.onTimeout){var scope=callbacks.scope?callbacks.scope:this;callbacks.onTimeout.apply(scope,[callbacks.optOnComplete]);}},CLASS_NAME:'SAPO.Maps.GenericSearcher'});SAPO.Maps.Layer={};SAPO.Maps.Layer.Custom=OpenLayers.Class({map:null,nrPixelsToRequest:50,inactivityTime:500,inactivityTimer:null,requester:null,requestId:null,timeout:4,lastRequestCoords:null,_isActive:false,initialize:function(map,options){this.map=map;this.requester=SAPO.Maps.Request.prototype.getRequester();OpenLayers.Util.extend(this,options);},destroy:function(){this.deactivate();this.requester.destroy();this.requester=null;this.map=null;},getURL:function(){return"";},onComplete:function(obj,opts){this.requestId=null;},onTimeout:function(){this.requestId=null;},startRequest:function(){},activate:function(){if(this._isActive){return;}
this._isActive=true;this.map.events.register("movestart",this,this.clearTimer);this.map.events.register("moveend",this,this.setTimer);this.refresh();},deactivate:function(){if(!this._isActive){return;}
this._isActive=false;this.lastRequestCoords=null;this.map.events.unregister("movestart",this,this.clearTimer);this.map.events.unregister("moveend",this,this.setTimer);},isActive:function(){return this._isActive;},setTimer:function(){this.inactivityTimer=window.setTimeout(function(){this.refresh();}.bindObj(this),this.inactivityTime);},clearTimer:function(){if(this.inactivityTimer){this.cancelCurrentRequest();window.clearTimeout(this.inactivityTimer);this.inactivityTimer=null;}},shouldRequest:function(){var bounds=this.map.getBounds();var currentCoords=new OpenLayers.LonLat(bounds.right,bounds.top);if(!this.lastRequestCoords){this.lastRequestCoords=currentCoords;return true;}
var lastpx=this.map.getContainerPixelFromLonLat(this.lastRequestCoords);var px=this.map.getContainerPixelFromLonLat(currentCoords);var deltax=lastpx.x-px.x;var deltay=lastpx.y-px.y;if(deltax<0){deltax*=-1;}
if(deltay<0){deltay*=-1;}
if(deltax<this.nrPixelsToRequest&&deltay<this.nrPixelsToRequest){return false;}
this.lastRequestCoords=currentCoords;return true;},cancelCurrentRequest:function(){if(this.requestId){this.requester.cancel(this.requestId);this.requestId=null;}},refresh:function(force){if(!force&&!this.shouldRequest()){return;}
var url=this.getURL();if(url.length===0){return;}
this.startRequest();this.cancelCurrentRequest();this.requestId=this.requester.request(url,{onComplete:this.onComplete.bindObj(this),onTimeout:this.onTimeout.bindObj(this),timeout:this.timeout,optOnComplete:{forced:force}});},setMap:function(map){this.map=map;},CLASS_NAME:"SAPO.Maps.Layer.Custom"});SAPO.Maps.Layer.Territory=OpenLayers.Class(OpenLayers.Layer.WMS,{defaultParams:null,parameters:null,territoryLayers:null,initialize:function(name,url,params,options){this.parameters={shape:'Municipality',color:'232,245,152',showLabels:false,outlineColor:'0,0,0',showIcons:false,iconUrl:null,hideArchipelagos:false,showOnlyArchipelagos:false,showLabelsInCentroid:false,customColors:null,customColorsGuid:null,layers:'dummy'};this.defaultParams=OpenLayers.Util.extend({},this.parameters);this.parameters=OpenLayers.Util.extend(this.parameters,params);OpenLayers.Layer.WMS.prototype.initialize.apply(this,[name,url,this.parameters,options]);},destroy:function(){OpenLayers.Layer.WMS.prototype.destroy.apply(this,arguments);this.parameters=null;this.defaultParams=null;this.territoryLayers=null;},getDefaultParameters:function(){return this.defaultParams;},restoreDefaults:function(){this.parameters=OpenLayers.Util.extend({},this.defaultParams);this.mergeNewParams(this.parameters);this.propagateState();},saveAsDefault:function(){this.defaultParams=OpenLayers.Util.extend({},this.parameters);},setShapeType:function(shape){if(this.parameters.shape===shape||!shape){return;}
var param={shape:shape};this.parameters=OpenLayers.Util.extend(this.parameters,param);this.mergeNewParams(param);this.propagateState();},getShapeType:function(){return this.parameters.shape;},getShapeTypes:function(){return[{name:"Freguesia",id:"Parish"},{name:"Concelho",id:"Municipality"},{name:"Distrito",id:"District"},{name:"NUTS3",id:"NUTS3"},{name:"NUTS2",id:"NUTS2"},{name:"NUTS1",id:"NUTS1"},{name:"País",id:"Country"}];},setShapeColor:function(rgb){if(this.parameters.color===rgb){return;}
var param={color:rgb};this.parameters=OpenLayers.Util.extend(this.parameters,param);this.mergeNewParams(param);this.propagateState();},showLabel:function(showlabel){if(this.parameters.showLabels===showlabel){return;}
var param={showLabels:showlabel};this.parameters=OpenLayers.Util.extend(this.parameters,param);this.mergeNewParams(param);this.propagateState();},setOutlineColor:function(rgb){if(this.parameters.outlineColor===rgb){return;}
var param={outlineColor:rgb};this.parameters=OpenLayers.Util.extend(this.parameters,param);this.mergeNewParams(param);this.propagateState();},showIcons:function(show){if(this.parameters.showIcons===show){return;}
var param={showIcons:show};this.parameters=OpenLayers.Util.extend(this.parameters,param);this.mergeNewParams(param);this.propagateState();},setIconURL:function(url){if(this.parameters.iconUrl===url){return;}
var param={iconUrl:encodeURIComponent(url)};this.parameters=OpenLayers.Util.extend(this.parameters,param);this.mergeNewParams(param);this.propagateState();},showArchipelagos:function(show){if(this.parameters.hideArchipelagos===!show){return;}
var param={hideArchipelagos:!show};this.parameters=OpenLayers.Util.extend(this.parameters,param);this.mergeNewParams(param);this.propagateState();},showOnlyArchipelagos:function(show){if(show===true&&this.parameters.hideArchipelagos===true){this.showArchipelagos(true);}
if(this.parameters.showOnlyArchipelagos===show){return;}
var param={showOnlyArchipelagos:show};this.parameters=OpenLayers.Util.extend(this.parameters,param);this.mergeNewParams(param);this.propagateState();},showLabelsInCentroid:function(show){if(this.parameters.showLabelsInCentroid===show){return;}
var param={showLabelsInCentroid:show};this.parameters=OpenLayers.Util.extend(this.parameters,param);this.mergeNewParams(param);this.propagateState();},setCustomColors:function(ccolors){var style=false,administrativeId=false,customColors="";for(var i=0;i<ccolors.length;++i){style=ccolors[i];customColors+=style.Color+",";if(style.IconUrl){customColors+=style.IconUrl;this.showIcons(true);}else{this.showIcons(false);}
for(var j=0;j<style.AdministrativeDivisionsIds.length;++j){administrativeId=style.AdministrativeDivisionsIds[j];customColors+=","+administrativeId;}
customColors+=";";}
customColors=customColors.slice(0,customColors.length-1);var param={customColors:customColors};this.parameters=OpenLayers.Util.extend(this.parameters,param);this.mergeNewParams(param);this.propagateState();},setCustomColorsGuid:function(guid){var param={customColorsGuid:guid};this.parameters=OpenLayers.Util.extend(this.parameters,param);this.mergeNewParams(param);this.propagateState();},setLayerStyle:function(style){var diferent=SAPO.Maps.Utils.diferent(this.parameters,style);if(!diferent){return;}
this.parameters=OpenLayers.Util.extend(this.parameters,style);this.mergeNewParams(this.parameters);this.propagateState();},getLayerStyle:function(){return this.parameters;},addLayer:function(territoryLayer){territoryLayer.setLayerStyle(this.parameters);if(!this.territoryLayers){this.territoryLayers=[];}
this.territoryLayers.push(territoryLayer);},removeLayer:function(territoryLayer){if(!this.territoryLayers){return;}
OpenLayers.Util.removeItem(this.territoryLayers,territoryLayer);},setOpacity:function(opacity){OpenLayers.Layer.WMS.prototype.setOpacity.apply(this,arguments);if(this.territoryLayers){var layer=false;for(var i=0,len=this.territoryLayers.length;i<len;++i){layer=this.territoryLayers[i];layer.setOpacity(opacity);}}},setVisibility:function(visibility){OpenLayers.Layer.WMS.prototype.setVisibility.apply(this,arguments);if(this.territoryLayers){var layer=false;for(var i=0,len=this.territoryLayers.length;i<len;++i){layer=this.territoryLayers[i];layer.setVisibility(visibility);}}},clone:function(obj){if(!obj){obj=new SAPO.Maps.Layer.Territory(this.name,this.url,this.params,this.options);obj.parameters=OpenLayers.Util.extend({},this.parameters);obj.defaultParams=OpenLayers.Util.extend({},this.defaultParams);}
obj=OpenLayers.Layer.WMS.prototype.clone.apply(this,[obj]);obj.territoryLayers=null;return obj;},propagateState:function(){if(!this.territoryLayers){return;}
var layer=false;for(var i=0,len=this.territoryLayers.length;i<len;++i){layer=this.territoryLayers[i];layer.setLayerStyle(this.parameters);}},CLASS_NAME:'SAPO.Maps.Layer.Territory'});SAPO.Maps.HTMLLayer=OpenLayers.Class(OpenLayers.Layer,{isBaseLayer:false,chartsOverlay:null,drawn:false,initialize:function(name,options){OpenLayers.Layer.prototype.initialize.apply(this,arguments);this.chartsOverlay={};},destroy:function(){},moveTo:function(bounds,zoomChanged,dragging){OpenLayers.Layer.prototype.moveTo.apply(this,arguments);if(zoomChanged||!this.drawn){for(var c in this.chartsOverlay){this.updatePosition(this.chartsOverlay[c]);}
this.drawn=true;}},addCharts:function(charts){if(!(charts instanceof Array)){charts=[charts];}
var chart=false;for(var i=0,len=charts.length;i<len;++i){chart=charts[i];if(!chart.id){chart.id=OpenLayers.Util.createUniqueID(chart.CLASS_NAME+"_");}
this.chartsOverlay[chart.id]=chart;this.drawChart(chart);chart.setLayer(this);}},removeCharts:function(charts){if(!charts||charts.length===0){return;}
if(!(charts instanceof Array)){charts=[charts];}
var chart=false;for(var i=0,len=charts.length;i<len;++i){chart=charts[i];if(!this.chartsOverlay[chart.id]){continue;}
delete this.chartsOverlay[chart.id];this.div.removeChild(chart._htmlElement);chart._htmlElement=null;chart._drawn=false;chart.removed();}},clearCharts:function(){if(this.chartsOverlay!==null){for(var c in this.chartsOverlay){this.removeCharts(this.chartsOverlay[c]);}}},drawChart:function(chart){var lonlat=chart.getLonLat().clone().transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));var px=this.map.getLayerPxFromLonLat(lonlat);var chartElement=chart.draw(px);if(!chart._drawn){this.div.appendChild(chartElement);chart._htmlElement=chartElement;chart._drawn=true;}},updatePosition:function(chart){var lonlat=chart.getLonLat().clone().transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));var px=this.getViewPortPxFromLonLat(lonlat);chart.moveTo(px);},CLASS_NAME:'SAPO.Maps.LayerCharts'});var ZeroClipboard={version:"1.0.4",clients:{},moviePath:'ZeroClipboard.swf',nextId:1,$:function(thingy){if(typeof(thingy)=='string')thingy=document.getElementById(thingy);if(!thingy.addClass){thingy.hide=function(){this.style.display='none';};thingy.show=function(){this.style.display='';};thingy.addClass=function(name){this.removeClass(name);this.className+=' '+name;};thingy.removeClass=function(name){this.className=this.className.replace(new RegExp("\\s*"+name+"\\s*")," ").replace(/^\s+/,'').replace(/\s+$/,'');};thingy.hasClass=function(name){return!!this.className.match(new RegExp("\\s*"+name+"\\s*"));}}
return thingy;},setMoviePath:function(path){this.moviePath=path;},dispatch:function(id,eventName,args){var client=this.clients[id];if(client){client.receiveEvent(eventName,args);}},register:function(id,client){this.clients[id]=client;},getDOMObjectPosition:function(obj){var info={left:0,top:0,width:obj.width?obj.width:obj.offsetWidth,height:obj.height?obj.height:obj.offsetHeight};while(obj){info.left+=obj.offsetLeft;info.top+=obj.offsetTop;obj=obj.offsetParent;}
return info;},Client:function(elem){this.handlers={};this.id=ZeroClipboard.nextId++;this.movieId='ZeroClipboardMovie_'+this.id;ZeroClipboard.register(this.id,this);if(elem)this.glue(elem);}};ZeroClipboard.Client.prototype={id:0,ready:false,movie:null,clipText:'',handCursorEnabled:true,cssEffects:true,handlers:null,glue:function(elem){this.domElement=ZeroClipboard.$(elem);var zIndex=9999999999;if(this.domElement.style.zIndex){zIndex=parseInt(this.domElement.style.zIndex)+1;}
var box=ZeroClipboard.getDOMObjectPosition(this.domElement);this.div=document.createElement('div');var style=this.div.style;style.position='absolute';style.left=''+box.left+'px';style.top=''+box.top+'px';style.width=''+box.width+'px';style.height=''+box.height+'px';style.zIndex=zIndex;var body=document.getElementsByTagName('body')[0];body.appendChild(this.div);this.div.innerHTML=this.getHTML(box.width,box.height);},getHTML:function(width,height){var html='';var flashvars='id='+this.id+'&width='+width+'&height='+height;if(navigator.userAgent.match(/MSIE/)){var protocol=location.href.match(/^https/i)?'https://':'http://';html+='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="'+protocol+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+width+'" height="'+height+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+ZeroClipboard.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/><param name="wmode" value="transparent"/></object>';}
else{html+='<embed id="'+this.movieId+'" src="'+ZeroClipboard.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" wmode="transparent" />';}
return html;},hide:function(){if(this.div){this.div.style.left='-2000px';}},show:function(){this.reposition();},destroy:function(){if(this.domElement&&this.div){this.hide();this.div.innerHTML='';var body=document.getElementsByTagName('body')[0];try{body.removeChild(this.div);}catch(e){;}
this.domElement=null;this.div=null;}},reposition:function(elem){if(elem){this.domElement=ZeroClipboard.$(elem);if(!this.domElement)this.hide();}
if(this.domElement&&this.div){var box=ZeroClipboard.getDOMObjectPosition(this.domElement);var style=this.div.style;style.left=''+box.left+'px';style.top=''+box.top+'px';}},setText:function(newText){this.clipText=newText;if(this.ready)this.movie.setText(newText);},addEventListener:function(eventName,func){eventName=eventName.toString().toLowerCase().replace(/^on/,'');if(!this.handlers[eventName])this.handlers[eventName]=[];this.handlers[eventName].push(func);},setHandCursor:function(enabled){this.handCursorEnabled=enabled;if(this.ready)this.movie.setHandCursor(enabled);},setCSSEffects:function(enabled){this.cssEffects=!!enabled;},receiveEvent:function(eventName,args){eventName=eventName.toString().toLowerCase().replace(/^on/,'');switch(eventName){case'load':this.movie=document.getElementById(this.movieId);if(!this.movie){var self=this;setTimeout(function(){self.receiveEvent('load',null);},1);return;}
if(!this.ready&&navigator.userAgent.match(/Firefox/)&&navigator.userAgent.match(/Windows/)){var self=this;setTimeout(function(){self.receiveEvent('load',null);},100);this.ready=true;return;}
this.ready=true;this.movie.setText(this.clipText);this.movie.setHandCursor(this.handCursorEnabled);break;case'mouseover':if(this.domElement&&this.cssEffects){this.domElement.addClass('hover');if(this.recoverActive)this.domElement.addClass('active');}
break;case'mouseout':if(this.domElement&&this.cssEffects){this.recoverActive=false;if(this.domElement.hasClass('active')){this.domElement.removeClass('active');this.recoverActive=true;}
this.domElement.removeClass('hover');}
break;case'mousedown':if(this.domElement&&this.cssEffects){this.domElement.addClass('active');}
break;case'mouseup':if(this.domElement&&this.cssEffects){this.domElement.removeClass('active');this.recoverActive=false;}
break;}
if(this.handlers[eventName]){for(var idx=0,len=this.handlers[eventName].length;idx<len;idx++){var func=this.handlers[eventName][idx];if(typeof(func)=='function'){func(this,args);}
else if((typeof(func)=='object')&&(func.length==2)){func[0][func[1]](this,args);}
else if(typeof(func)=='string'){window[func](this,args);}}}}};SAPO.Maps.Utils={};SAPO.Maps.Utils.createLoadingDiv=function(width,height){width=width?width:100;height=height?height:100;var div=document.createElement('div');div.style.width=width+"px";div.style.height=height+"px";SAPO.Maps.Utils.displayWaitIcon(div);return div;};SAPO.Maps.Utils.WaitIconClassName='Sapo_Panels_DIV_WAIT_ICON';SAPO.Maps.Utils.WaitIconWidth=111;SAPO.Maps.Utils.WaitIconHeight=82;SAPO.Maps.Utils.displayWaitIcon=function(panel){if(!panel){return;}
var div=document.createElement('div');div.style.width=SAPO.Maps.Utils.WaitIconWidth+"px";div.style.height=SAPO.Maps.Utils.WaitIconHeight+"px";div.className=SAPO.Maps.Utils.WaitIconClassName;var img=document.createElement('img');img.src='http://imgs.sapo.pt/fotos_gis/site/bigwheel.gif';img.style.visibility='hidden';div.style.position='relative';div.appendChild(img);panel.appendChild(div);var width=img.width?img.width:SAPO.Maps.Utils.WaitIconWidth;var height=img.height?img.height:SAPO.Maps.Utils.WaitIconHeight;if(OpenLayers.Util.getBrowserName()==='msie'){div.style.top=Math.floor((panel.offsetHeight/2)-(height/2))+"px";div.style.left=Math.floor((panel.offsetWidth/2)-(width/2))+"px";var timer=window.setTimeout(function(){div.style.top=Math.floor((panel.offsetHeight/2)-(height/2))+"px";div.style.left=Math.floor((panel.offsetWidth/2)-(width/2))+"px";img.style.visibility='visible';window.clearTimeout(timer);},0);}
else{img.onload=function(){div.style.top=Math.floor((panel.offsetHeight/2)-(height/2))+"px";div.style.left=Math.floor((panel.offsetWidth/2)-(width/2))+"px";img.style.visibility='visible';};}};SAPO.Maps.Utils.removeWaitIcon=function(panel){var elems=panel.childNodes;for(var i=0;i<elems.length;++i){if(elems[i].className==SAPO.Maps.Utils.WaitIconClassName){panel.removeChild(elems[i]);}}};SAPO.Maps.Utils.checkWaitIcon=function(panel){var elems=panel.childNodes;for(var i=0;i<elems.length;++i){if(elems[i].className==SAPO.Maps.Utils.WaitIconClassName){return true;}}};SAPO.Maps.Utils.MessageType={NONE:null,OK:'http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Icons/ok.png',ERROR:'http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Icons/error.png',WARNING:'http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Icons/warning.gif',INFORMATION:'http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Icons/information.gif'};SAPO.Maps.Utils.ErrorMessageClassName="utils_msg_smapi";SAPO.Maps.Utils.displayMessageText=function(panel,msg,msgType){if(!panel){return;}
var div=document.createElement('div');if(msgType!=SAPO.Maps.Utils.MessageType.NONE){var img=document.createElement('img');img.src=msgType;img.height="27";img.width="31";div.appendChild(img);div.innerHTML+="";}
var msgContent=document.createElement('div');var dummy=document.createElement('div');msgContent.appendChild(document.createTextNode(msg));div.appendChild(msgContent);div.appendChild(dummy);div.className=SAPO.Maps.Utils.ErrorMessageClassName;msgContent.className='utils_msg_text_smapi';dummy.className='clear';panel.appendChild(div);};SAPO.Maps.Utils.displayMessageToRetry=function(panel,msg,anchor,msgType){if(!panel){return;}
var div=document.createElement('div');if(msgType!=SAPO.Maps.Utils.MessageType.NONE){var img=document.createElement('img');img.src=msgType;img.height="27";img.width="31";div.appendChild(img);}
var msgContent=document.createElement('div');var dummy=document.createElement('div');var span=document.createElement('span');span.appendChild(anchor);msgContent.appendChild(document.createTextNode(msg));msgContent.appendChild(span);div.appendChild(msgContent);div.appendChild(dummy);div.className=SAPO.Maps.Utils.ErrorMessageClassName;msgContent.className='utils_msg_text_smapi';dummy.className='clear';panel.appendChild(div);};SAPO.Maps.Utils.displayMessageHTML=function(panel,msg1,html,msg2,msgType){if(!panel){return;}
var div=document.createElement('div');if(msgType!=SAPO.Maps.Utils.MessageType.NONE){var img=document.createElement('img');img.src=msgType;img.height="27";img.width="31";div.appendChild(img);}
var msgContent=document.createElement('div');var dummy=document.createElement('div');var span=document.createElement('span');span.appendChild(document.createTextNode(html));msgContent.appendChild(document.createTextNode(msg1));msgContent.appendChild(span);msgContent.appendChild(document.createTextNode(msg2));div.appendChild(msgContent);div.appendChild(dummy);div.className=SAPO.Maps.Utils.ErrorMessageClassName;msgContent.className='utils_msg_text_smapi';dummy.className='clear';panel.appendChild(div);};SAPO.Maps.Utils.removeErrorMessage=function(panel){var elems=panel.childNodes;for(var i=0;i<elems.length;++i){if(elems[i].className==SAPO.Maps.Utils.ErrorMessageClassName){panel.removeChild(elems[i]);}}};SAPO.Maps.Utils.checkQuery=function(query){if(query.length===0){return false;}
var arr=query.split(',');if(arr.length!==2){var coords=SAPO.Maps.Utils.convertDMSToDecimal(query);if(!isNaN(coords.lat)&&!isNaN(coords.lon)){return{Latitude:coords.lat,Longitude:coords.lon};}
return false;}
var lat,lon;try{lat=Number(arr[0]);lon=Number(arr[1]);if(isNaN(lat)||isNaN(lon)){return false;}
if(lat>90||lat<-90||lon>180||lon<-180){return false;}}catch(e){return false;}
return{Latitude:lat,Longitude:lon};};SAPO.Maps.Utils.getOuterHTML=function(element){if(element.outerHTML){return element.outerHTML;}
var wrapper=document.createElement("div");wrapper.appendChild(element.cloneNode(true));return wrapper.innerHTML;};SAPO.Maps.Utils.copy2Clipboard=function(str){if(OpenLayers.Util.getBrowserName()==='msie'){var copier='copy2clipboard';var copierElement=document.getElementById(copier);if(!copierElement){copierElement=document.createElement('input');copierElement.type='text';copierElement.id=copier;copierElement.style.visibility='hidden';document.body.appendChild(copierElement);}
copierElement.value=str;var range=copierElement.createTextRange();if(range){range.execCommand('Copy');}}
else{var flashcopier='flashcopier';if(!document.getElementById(flashcopier)){var divholder=document.createElement('div');divholder.id=flashcopier;document.body.appendChild(divholder);}
document.getElementById(flashcopier).innerHTML='';var divinfo='<embed id="fla" src="http://js.sapo.pt/Assets/Maps/_clipboard.swf" FlashVars="clipboard='+encodeURIComponent(str)+'" width="100" height="100" type="application/x-shockwave-flash"></embed>';document.getElementById(flashcopier).innerHTML=divinfo;}};SAPO.Maps.Utils.copy2ClipboardWhenClick=function(element,strFn,completeFn){var clip=null;if(OpenLayers.Util.getBrowserName()==='msie'){if(!element.attachEvent){element=document.getElementById(element);}
if(!element){return;}
OpenLayers.Event.observe(element,"click",function(){var copier='copy2clipboard';var copierElement=document.getElementById(copier);if(!copierElement){copierElement=document.createElement('input');copierElement.type='text';copierElement.id=copier;copierElement.style.visibility='hidden';document.body.appendChild(copierElement);}
copierElement.value=strFn();var range=copierElement.createTextRange();if(range){range.execCommand('Copy');}
completeFn();});}
else{ZeroClipboard.setMoviePath("http://imgs.sapo.pt/fotos_gis/ZeroClipboard.swf");clip=new ZeroClipboard.Client();clip.setCSSEffects(true);clip.glue(element);clip.addEventListener('onMouseDown',function(){clip.setText(strFn());});clip.addEventListener('onComplete',function(){completeFn();clip.destroy();});}
var retObj={zeroClipboard:clip,destroy:function(){if(clip){clip.destroy();}}};return retObj;};SAPO.Maps.Utils.checkUrl=function(){return window.location.href.indexOf('http://mapas.sapo.pt')!=-1;};SAPO.Maps.Utils.checkIE6=function(){return parseFloat(navigator.appVersion.split("MSIE")[1])<7;};SAPO.Maps.Utils.hasProperties=function(obj){if(!obj){return false;}
for(var p in obj){return true;}
return false;};SAPO.Maps.Utils.numberOfProperties=function(obj){var count=0;if(obj){for(var prop in obj){++count;}}
return count;};SAPO.Maps.Utils.addClassName=function(element,className){element=OpenLayers.Util.getElement(element);var classeNames=element.className;var classesArr=classeNames.split(' ');if(!classesArr||classesArr.length===0){element.className=className;return;}
for(var i=0;i<classesArr.length;++i){if(classesArr[i]===className){return;}}
element.className+=' '+className;};SAPO.Maps.Utils.removeClassName=function(element,className){element=OpenLayers.Util.getElement(element);var classeNames=element.className;var classesArr=classeNames.split(' ');var classNames2Copy='';for(var i=0;i<classesArr.length;++i){if(classesArr[i]!==className){classNames2Copy+=' '+classesArr[i];}}
element.className=classNames2Copy;};SAPO.Maps.Utils.FadeColor=155;SAPO.Maps.Utils.Fade=function(element){var background=element.style.background;var b=SAPO.Maps.Utils.FadeColor;function f(){element.style.background='rgb(255,255,'+(b+=20)+')';if(b<255){setTimeout(f,20);}else{element.style.background=background;}}
f();};SAPO.Maps.Utils.AdjustBoundsConsideringBorders=function(map,bounds,borders){if(!borders){borders={left:0,right:0,top:0,bottom:0};}
map.setBounds(bounds,false);var center=bounds.getCenterLonLat();var size=map.getSize();SAPO.Maps.Utils.CenterMapConsideringBorders(map,center,borders);var bottom_left=new OpenLayers.Pixel(borders.left,size.h-borders.bottom);var top_right=new OpenLayers.Pixel(size.w-borders.right,borders.top);var bounds_sw=map.getContainerPixelFromLonLat(new OpenLayers.LonLat(bounds.left,bounds.bottom));var bounds_ne=map.getContainerPixelFromLonLat(new OpenLayers.LonLat(bounds.right,bounds.top));while(bounds_sw.x<bottom_left.x||bounds_ne.y<top_right.y||bounds_sw.y>bottom_left.y||bounds_ne.x>top_right.x){map.zoomOut();SAPO.Maps.Utils.CenterMapConsideringBorders(map,center,borders);bounds_sw=map.getContainerPixelFromLonLat(new OpenLayers.LonLat(bounds.left,bounds.bottom));bounds_ne=map.getContainerPixelFromLonLat(new OpenLayers.LonLat(bounds.right,bounds.top));}};SAPO.Maps.Utils.CenterMapConsideringBorders=function(map,center,borders,zoomLevel){if(!borders){borders={left:0,top:0,right:0,bottom:0};}
if(zoomLevel){map.zoomTo(zoomLevel);}
var center_px=map.getContainerPixelFromLonLat(center);var size=map.getSize();var x_min=borders.left;var y_min=borders.top;var x_max=size.w-borders.right;var y_max=size.h-borders.bottom;var center_x=x_min+Math.floor((x_max-x_min)/2);var center_y=y_min+Math.floor((y_max-y_min)/2);var dx=center_px.x-center_x;var dy=center_px.y-center_y;map.pan(dx,dy,{animate:false});};SAPO.Maps.Utils.getMapCenterConsideringBorders=function(map){var centerPx=map.getContainerPixelFromLonLat(map.getMapCenter());centerPx.y+=map.borders.top/2;centerPx.x+=map.borders.left/2;centerPx.y-=map.borders.bottom/2;centerPx.x-=map.borders.right/2;return map.getLonLatFromContainerPixel(centerPx);};SAPO.Maps.Utils.zoomMapConsideringBorders=function(map,zoom){var center=SAPO.Maps.Utils.getMapCenterConsideringBorders(map);SAPO.Maps.Utils.CenterMapConsideringBorders(map,center,map.borders,zoom);};SAPO.Maps.Utils.diferent=function(obj1,obj2){var dif=false;for(var e in obj1){if(obj2.hasOwnProperty(e)&&obj1[e]!==obj2[e]){dif=true;break;}}
return dif;};SAPO.Maps.Utils.composeUrl=function(endpoint,parameters){var url=endpoint;if(parameters){url+='?';var first=true;for(var param in parameters){if(!first){url+="&";}
first=false;url+=param+"="+parameters[param];}}
return url;};SAPO.Maps.Utils.getLastKey=function(object,excludeKey){var k=false;for(var key in object){if(key!=excludeKey){k=key;}}
return k;};SAPO.Maps.Utils.getFirstKey=function(object,excludeKey){var k=false;for(var key in object){if(key!=excludeKey){return key;}}
return null;};SAPO.Maps.Utils.removeMapControls=function(map){var scale=map.getControlsByClass('SAPO.Maps.Control.Scale')[0];var logo=map.getControlsByClass('SAPO.Maps.Control.PermanentLink')[0];map.removeControl(scale);map.removeControl(logo);};SAPO.Maps.Utils.round=function(num,dec){var result=Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);return result;};SAPO.Maps.Utils.convertHexToRGB=function(hex){hex=hex.replace(/#/,"");var r=hex.charAt(0)+hex.charAt(1);var g=hex.charAt(2)+hex.charAt(3);var b=hex.charAt(4)+hex.charAt(5);return parseInt(r,16)+","+parseInt(g,16)+","+parseInt(b,16);};SAPO.Maps.Utils.convertRGBToHex=function(decRgb){var rgb=decRgb.split(',');var r=Number(rgb[0]).toString(16).toUpperCase();r=r.length<2?"0"+r:r;var g=Number(rgb[1]).toString(16).toUpperCase();g=g.length<2?"0"+g:g;var b=Number(rgb[2]).toString(16).toUpperCase();b=b.length<2?"0"+b:b;return r+g+b;};SAPO.Maps.Utils.hasItem=function(array,item){for(var i=0;i<array.length;++i){if(array[i]==item){return true;}}
return false;};SAPO.Maps.Utils.removeChildNodes=function(node){if(!node||!node.childNodes){return;}
for(var i=node.childNodes.length-1;i>=0;--i){node.removeChild(node.childNodes[i]);}};SAPO.Maps.Utils.convertDecimalToDMS=function(latitude,longitude){var signlat=latitude<0?-1:1;var signlon=longitude<0?-1:1;latitude=Math.abs(latitude*1000000);longitude=Math.abs(longitude*1000000);var latD=Math.floor(latitude/1000000);var latM=Math.floor(((latitude/1000000)-Math.floor(latitude/1000000))*60);var latS=Math.round((Math.floor(((((latitude/1000000)-Math.floor(latitude/1000000))*60)-Math.floor(((latitude/1000000)-Math.floor(latitude/1000000))*60))*100000)*60/100000));var lonD=Math.floor(longitude/1000000);var lonM=Math.floor(((longitude/1000000)-Math.floor(longitude/1000000))*60);var lonS=Math.round((Math.floor(((((longitude/1000000)-Math.floor(longitude/1000000))*60)-Math.floor(((longitude/1000000)-Math.floor(longitude/1000000))*60))*100000)*60/100000));latD=latD.toString().length===1?'0'+latD.toString():latD.toString();latM=latM.toString().length===1?'0'+latM.toString():latM.toString();latS=latS.toString().length===1?'0'+latS.toString():latS.toString();lonD=lonD.toString().length===1?'0'+lonD.toString():lonD.toString();lonM=lonM.toString().length===1?'0'+lonM.toString():lonM.toString();lonS=lonS.toString().length===1?'0'+lonS.toString():lonS.toString();var latDMS=latD+'° '+latM+'\' '+latS+'"';var lonDMS=lonD+'° '+lonM+'\' '+lonS+'"';latDMS+=signlat>0?" N":" S";lonDMS+=signlon>0?" E":" W";return{lat:latDMS,lon:lonDMS};};SAPO.Maps.Utils.convertDMSToDecimal=function(objOrLatitudeOrCoords,longitude){var partsLat,partsLon;if(typeof(objOrLatitudeOrCoords)==="string"&&!longitude){partsLat=objOrLatitudeOrCoords.split(/[^\d\w]+/);partsLon=partsLat.splice(4);}
else{if(typeof(objOrLatitudeOrCoords)==="string"&&typeof(longitude)==="string"){partsLat=objOrLatitudeOrCoords.split(/[^\d\w]+/);partsLon=longitude.split(/[^\d\w]+/);}
else{partsLat=objOrLatitudeOrCoords.lat.split(/[^\d\w]+/);partsLon=objOrLatitudeOrCoords.lon.split(/[^\d\w]+/);}}
var convert=function(days,minutes,seconds,direction){var dd=Number(days)+Number(minutes)/60+Number(seconds)/(60*60);if(direction=="S"||direction=="W"){dd=dd*-1;}
return Number(dd.toFixed(6));};return{lat:convert.apply(this,partsLat),lon:convert.apply(this,partsLon)};};SAPO.Maps.Utils.getDifferences=function(defaultObj,currentObj){var resObj={};for(var e in defaultObj){if(typeof(defaultObj[e])==='object'&&typeof(currentObj[e])==='object'){var obj=SAPO.Maps.Utils.getDifferences(defaultObj[e],currentObj[e]);if(SAPO.Maps.Utils.hasProperties(obj)){resObj[e]=obj;}}else{if(defaultObj[e]!==currentObj[e]){resObj[e]=currentObj[e];}}}
return resObj;};SAPO.Maps.Utils.object2Array=function(obj){var arr=[];for(var key in obj){arr.push(obj[key]);}
return arr;};SAPO.Maps.Utils.getBoundingBoxFromCenterAndRadius=function(center,radius){var newCenter=center.clone();newCenter=newCenter.transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));var top,bottom,left,right;top=newCenter.lat+radius;bottom=newCenter.lat-radius;left=newCenter.lon-radius;right=newCenter.lon+radius;var bbox=new OpenLayers.Bounds(left,bottom,right,top);bbox.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));return bbox;};SAPO.Maps.Utils.preventDefault=function(evt){if(evt&&evt.preventDefault){evt.preventDefault();}
return false;};SAPO.Maps.Utils.htmlEntityDecode=function(str){var ta=document.createElement("textarea");ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");return ta.value;};SAPO.Maps.Utils.createNewElement=function(elementType,options){var element=document.createElement(elementType);for(var attr in options){element[attr]=options[attr];}
return element;};SAPO.Maps.Utils.stringReplace=function(baseString,options){var result=baseString;for(var particle in options){var re=new RegExp('%'+particle+'%',"g");result=result.replace(re,options[particle]);}
return result;};SAPO.Maps.Utils.getDefaultDateView=function(date){var dd=date.getDate();if(dd<10){dd='0'+dd;}
var mm=date.getMonth()+1;if(mm<10){mm='0'+mm;}
var yyyy=date.getFullYear();return String(yyyy+'-'+mm+'-'+dd);};SAPO.Maps.Utils.getDefaultTimeView=function(date){return String(date.getHours()+":"+date.getMinutes()+":"+date.getSeconds());};SAPO.Maps.Request=OpenLayers.Class({requestTypes:['XMLHttpRequest','Syndication'],initialize:function(){},destroy:function(){},request:function(url,objs){},cancel:function(id){},getRequester:function(){for(var i=0;i<this.requestTypes.length;i++){var requestClass=SAPO.Maps.Request[this.requestTypes[i]];if(requestClass&&requestClass.prototype.supported()){return new requestClass();}}
return null;},supported:function(){return true;}});SAPO.Maps.Request.Syndication=OpenLayers.Class(SAPO.Maps.Request,{syndication:null,syndicationObjsHelper:null,initialize:function(){this.syndication=new SAPO.Communication.Syndication();this.syndicationObjsHelper={};},destroy:function(){this.syndication.destroy();this.syndication=null;syndicationObjsHelper=null;},request:function(url,objs){var context={canceled:false,objs:objs,id:null};var timeoutFunc=OpenLayers.Function.bind(this.timeout,this,context);var completeFunc=OpenLayers.Function.bind(this.complete,this);var id=this.syndication.push(url,{timeout:objs.timeout,onTimeout:timeoutFunc,onComplete:completeFunc,optOnComplete:context});context.id=id;this.syndicationObjsHelper[id]=context;this.syndication.run(id);return id;},cancel:function(id){if(id===null||id===undefined){throw"Invalid Parameters. Id must be a value.";}
if(this.syndicationObjsHelper[id]){this.syndicationObjsHelper[id].canceled=true;this.removeSyndicationInfo(id);return true;}
return false;},supported:function(){return true;},timeout:function(context){if(context.canceled===true){return;}
context.canceled=true;var info=this.syndicationObjsHelper[context.id];if(info.objs.onTimeout){info.objs.onTimeout();}
this.removeSyndicationInfo(context.id);},complete:function(obj,context){if(context.canceled===true){return;}
var info=this.syndicationObjsHelper[context.id];if(info.objs.onComplete){info.objs.onComplete(obj,info.objs.optOnComplete);}
this.removeSyndicationInfo(context.id);},removeSyndicationInfo:function(id){this.syndicationObjsHelper[id].objs.onTimeout=null;this.syndicationObjsHelper[id].objs.onComplete=null;this.syndicationObjsHelper[id].objs.timeout=null;this.syndicationObjsHelper[id].objs=null;this.syndicationObjsHelper[id].id=null;delete this.syndicationObjsHelper[id];this.syndication._removeScript(id);}});SAPO.Maps.Request.XMLHttpRequest=OpenLayers.Class(SAPO.Maps.Request,{requestObjs:null,supportedHost:'http://mapas.sapo.pt/',retryOnError:true,initialize:function(){SAPO.Maps.Request.prototype.initialize.apply(this,arguments);this.requestObjs={};},destroy:function(){},request:function(url,objs){var mapsUrl=this.modifyURL(url);var id=false;do{id=Math.round(1000000*Math.random())+"";}while(this.requestObjs[id]);this.requestObjs[id]={xhr:this.createXHR(),url:mapsUrl,objs:objs,inProgress:false,timeoutInterval:null};if(this.requestObjs[id].objs.timeout){var timeoutFunc=OpenLayers.Function.bind(this.timeout,this,id);this.requestObjs[id].timeoutInterval=setTimeout(timeoutFunc,this.requestObjs[id].objs.timeout*1000);}
var func=OpenLayers.Function.bind(this.complete,this,id);this.requestObjs[id].xhr.onreadystatechange=func;this.requestObjs[id].inProgress=true;this.requestObjs[id].xhr.open("GET",this.requestObjs[id].url,true);this.requestObjs[id].xhr.send(null);return id;},cancel:function(id){if(id===null||id===undefined){throw"Invalid Parameters. Id must be a value.";}
if(this.requestObjs[id]){if(this.requestObjs[id].inProgress){this.requestObjs[id].inProgress=false;this.requestObjs[id].xhr.abort();this.deleteXHR(id);return true;}}
return false;},getRequester:function(){for(var i=0;i<this.requestTypes.length;i++){var requestClass=SAPO.Maps.Request[this.requestTypes[i]];if(requestClass&&requestClass.prototype.supported()){return new requestClass();}}
return null;},supported:function(){if(window.location.href.indexOf(this.supportedHost)===0){return true;}
return false;},retry:function(id){this.requestObjs[id].xhr.open("GET",this.requestObjs[id].url,true);this.requestObjs[id].xhr.send(null);},complete:function(id){if(!this.requestObjs[id]){return;}
if(this.requestObjs[id].inProgress===false){return;}
var xhr=this.requestObjs[id].xhr;if(xhr.readyState!=4){return;}
if(xhr.status!=200){if(this.requestObjs[id].objs.onError){this.requestObjs[id].objs.onError(xhr.responseText);}else{if(this.retryOnError&&this.requestObjs[id]){this.retry(id);return;}}}else{if(this.requestObjs[id].objs.onComplete){var response=eval('('+xhr.responseText+')');this.requestObjs[id].objs.onComplete(response,this.requestObjs[id].objs.optOnComplete);}}
if(this.requestObjs[id].timeoutInterval){clearInterval(this.requestObjs[id].timeoutInterval);}
this.requestObjs[id].inProgress=false;this.deleteXHR(id);},timeout:function(id){if(!this.requestObjs[id]){return;}
var timeoutListener=this.requestObjs[id].objs.onTimeout;this.cancel(id);if(timeoutListener){timeoutListener();}},createXHR:function(){var xhr;if(window.XMLHttpRequest){xhr=new XMLHttpRequest();}else{if(window.ActiveXObject){xhr=new ActiveXObject("Microsoft.XMLHTTP");}}
return xhr;},deleteXHR:function(id){this.requestObjs[id].url=null;this.requestObjs[id].objs=null;this.requestObjs[id].inProgress=null;this.requestObjs[id].xhr=null;this.requestObjs[id]=null;delete this.requestObjs[id];},modifyURL:function(url){if(url.indexOf('http://')==-1){return url;}
return this.supportedHost+url.substring(7);}});SAPO.Maps.Request.RequestLimiter=OpenLayers.Class({nrPixelsToRequest:50,inactivityTime:500,lastRequestCoords:null,inactivityTimer:null,callbacks:null,parameters:null,map:null,lastZoomLevel:null,_mapEventsActive:false,initialize:function(map,callbacks,options){OpenLayers.Util.extend(this,options);this.callbacks=callbacks;this.map=map;},activateMapEvents:function(){if(this.mapEventsActive()){return;}
this._mapEventsActive=true;this.listeners={moveend:OpenLayers.Function.bind(this.moveend,this),movestart:OpenLayers.Function.bind(this.movestart,this)};this.map.events.register('moveend',this,this.listeners.moveend);this.map.events.register('movestart',this,this.listeners.movestart);},deactivateMapEvents:function(){if(!this.mapEventsActive()){return;}
this._mapEventsActive=false;this.map.events.unregister('moveend',this,this.listeners.moveend);this.map.events.unregister('movestart',this,this.listeners.movestart);delete this.listeners.moveend;delete this.listeners.movestart;},mapEventsActive:function(){return this._mapEventsActive;},startRequestingTimer:function(bbox,parameters){this.parameters=parameters?parameters:[];this.clearTimer();function fire(){this.notifyCallbacks(bbox);this.clearTimer();}
this.inactivityTimer=window.setTimeout(fire.bindObj(this),this.inactivityTime);var currentZoom=this.map.getZoom();if(this.lastZoomLevel!=currentZoom){this.lastRequestCoords=null;}
this.lastZoomLevel=currentZoom;},stopRequestingTimer:function(){this.clearTimer();this.parameters=null;},notifyCallbacks:function(bbox){if(this.lastRequestCoords){var lastpx=this.map.getContainerPixelFromLonLat(this.lastRequestCoords);var px=this.map.getContainerPixelFromLonLat(new OpenLayers.LonLat(bbox.right,bbox.top));var deltax=lastpx.x-px.x;var deltay=lastpx.y-px.y;if(deltax<0){deltax*=-1;}
if(deltay<0){deltay*=-1;}
if(deltax<this.nrPixelsToRequest&&deltay<this.nrPixelsToRequest){return;}}
this.lastRequestCoords=new OpenLayers.LonLat(bbox.right,bbox.top);var scope=this.callbacks.scope?this.callbacks.scope:this;this.callbacks.request.apply(scope,this.parameters);},clearTimer:function(){if(this.inactivityTimer){window.clearTimeout(this.inactivityTimer);this.inactivityTimer=null;}},movestart:function(){this.stopRequestingTimer();},moveend:function(){this.startRequestingTimer(this.map.getBounds());},CLASS_NAME:'SAPO.Maps.Request.RequestLimiter'});SAPO.Maps.Request.Status={STOP:0,OK:1,ERROR:2,REQUESTING:3,CANCELED:4};SAPO.Maps.Renderer={};SAPO.Maps.PopupRenderer=OpenLayers.Class(SAPO.Maps.Renderer,{});SAPO.Maps.PanelRenderer=OpenLayers.Class(SAPO.Maps.Renderer,{});SAPO.Maps.PoiPanelRenderer={markerImgs:'http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Markers/new/m',markerImgsExtension:'.png',getPanelHTML:function(poi,number,showImg,map){var itemHolder=document.createElement('div');var markerHolder=document.createElement('div');var marker=document.createElement('img');var detailsHolder=document.createElement('div');var dummy=document.createElement('div');var a_magnifier=document.createElement("a");itemHolder.className='search_item_smapi';markerHolder.className='search_item_marker';detailsHolder.className='search_detail_smapi';dummy.className='clear';if(showImg){marker.src=this.markerImgs+number+this.markerImgsExtension;markerHolder.appendChild(marker);itemHolder.appendChild(markerHolder);if(SAPO.Maps.Utils.checkIE6()){markerHolder.className+=' search_item_marker_ie6';marker.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',src='"+this.markerImgs+number+this.markerImgsExtension+"')";}}
a_magnifier.className="lupa";a_magnifier.href="#";if(map&&map instanceof SAPO.Maps.Map){markerHolder.appendChild(a_magnifier);}
itemHolder.appendChild(detailsHolder);itemHolder.appendChild(dummy);if(poi.Name){if(poi.martelada){detailsHolder.innerHTML="<span class='search_title_smapi'>"+
poi.Name+"</span>"+"<br/>"+"<span>"+poi.text+"</span>";}else{switch(poi.CategoryId){case'213':this.getLocalityPanelHTML(poi,detailsHolder,"local");break;case'214':this.getLocalityPanelHTML(poi,detailsHolder,"street");break;default:this.getCommonPanelHTML(poi,detailsHolder);break;}}}else{this.getCoordsPanelHTML(poi,detailsHolder);}
if(map&&map instanceof SAPO.Maps.Map){var zoomFunction=function(e){map.zoomTo(14);};a_magnifier.onclick=zoomFunction;itemHolder.ondblclick=zoomFunction;}
return itemHolder;},getLocalityPanelHTML:function(poi,holder,poiType){var name=document.createElement('span');name.className='search_title_smapi';name.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(poi.Name)));var address=document.createElement('span');var municipality=document.createElement('strong');var district=document.createElement('strong');var type=document.createElement("span");if(poi.Municipality&&poi.Municipality.length>0){address.appendChild(document.createTextNode('Concelho de '));municipality.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(poi.Municipality)));address.appendChild(municipality);}
if(poi.District&&poi.District.length>0){districtText=', distrito de ';if(!poi.Municipality||poi.Municipality.length===0){districtText='Distrito de ';}
district.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(poi.District)));address.appendChild(document.createTextNode(districtText));address.appendChild(district);}
type.innerHTML=poiType==="local"?"(Localidades)":"(Ruas)";holder.appendChild(name);holder.appendChild(document.createElement('br'));holder.appendChild(type);holder.appendChild(document.createElement('br'));holder.appendChild(address);},getCommonPanelHTML:function(poi,holder){var name=document.createElement('span');name.className='search_title_smapi';name.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(poi.Name)));var type=document.createElement("span");var address=document.createElement('span');if(poi.Street&&poi.Street.length>0){address.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(poi.Street)));address.innerHTML+=', ';}
if(poi.ZipCode&&poi.ZipCode.length>0){var zc=poi.ZipCode;if(poi.ZipCode.length>4){zc=(poi.ZipCode.substring(0,4)+"-"+poi.ZipCode.substring(4));}
address.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(zc)));}
if(poi.Locality&&poi.Locality.length>0){address.appendChild(document.createTextNode(', '+SAPO.Maps.Utils.htmlEntityDecode(poi.Locality)));}else{if(poi.Parish&&poi.Parish.length>0){address.appendChild(document.createTextNode(', '+SAPO.Maps.Utils.htmlEntityDecode(poi.Parish)));}}
if(poi.Municipality&&poi.Municipality.length>0){if(poi.Locality!==poi.Municipality&&poi.Parish!==poi.Municipality){address.appendChild(document.createTextNode(', '+SAPO.Maps.Utils.htmlEntityDecode(poi.Municipality)));}}
if(poi.District&&poi.District.length>0&&poi.Municipality!==poi.District){address.appendChild(document.createTextNode(', '+SAPO.Maps.Utils.htmlEntityDecode(poi.District)));}
var contacts=document.createElement('span');if(poi.Phone&&poi.Phone.length>0){contacts.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(poi.Phone)));contacts.appendChild(document.createTextNode(' '));contacts.appendChild(document.createElement('br'));}
if(poi.URL&&poi.URL.length>0){var site=document.createElement('a');site.className='search_site_link';site.href=poi.URL;site.target='blank';site.appendChild(document.createTextNode('Site'));contacts.appendChild(site);}
type.innerHTML="("+poi.Category+")";holder.appendChild(name);holder.appendChild(document.createElement('br'));holder.appendChild(type);holder.appendChild(document.createElement('br'));holder.appendChild(address);holder.appendChild(document.createElement('br'));holder.appendChild(contacts);},getCoordsPanelHTML:function(poi,holder){var name=document.createElement('span');name.className='search_title_smapi';name.innerHTML='Coordenadas';var coords=document.createElement('span');coords.appendChild(document.createTextNode(poi.Latitude));coords.appendChild(document.createTextNode(', '));coords.appendChild(document.createTextNode(poi.Longitude));holder.appendChild(name);holder.appendChild(document.createElement('br'));holder.appendChild(coords);}};SAPO.Maps.Renderer.TerritoryPanel=OpenLayers.Class({layer:null,panel:null,holder:null,elements:null,sliderControl:null,opacityValue:100,iconURL:"http://imgs.sapo.pt/fotos_gis/mapas_api/v1.0/Markers/pin_small.png",statisticsObj:null,windowManagerObj:null,elementsObserved:null,drawn:false,madeiraOpened:false,visible:false,acoresOpened:false,initialize:function(layer,panel,windowManager,options){this.layer=layer;this.panel=panel;this.windowManagerObj=windowManager;OpenLayers.Util.extend(this,options);this.elements={};this.elementsObserved=[];this.layer.map.events.register('changebaselayer',this,this.checkTerritoryZoneElements);},destroy:function(){this.removeEventHandlers();},removeEventHandlers:function(elements){if(elements){for(var i=0;i<this.elements.length;++i){OpenLayers.Event.stopObservingElement(this.elements[i]);}}
else{for(var j=0;j<this.elementsObserved.length;++j){OpenLayers.Event.stopObservingElement(this.elementsObserved[j]);}
this.elementsObserved=[];}},draw:function(){if(!this.holder){this.holder=document.createElement("div");this.holder.className="smapi_customize_territory";this.panel.appendChild(this.holder);}
this.redraw();this.drawn=true;this.checkTerritoryZoneElements();this.checkFloatWindowsZoneElements();},isDrawn:function(){return this.drawn;},isVisible:function(){return this.visible;},redraw:function(){if(!('territoryLink'in this.elements)){this.elements.territoryLink=this.buildterritoryLink();}
if(!("territory"in this.elements)){this.elements.territory=this.buildTerritory();}
if(!("style"in this.elements)){this.elements.style=this.buildStyle();}
for(var i=this.holder.childNodes.length-1;i>=0;--i){this.holder.removeChild(this.holder.childNodes[i]);}
this.holder.appendChild(this.elements.territoryLink);this.holder.appendChild(this.elements.territory);this.holder.appendChild(this.elements.style);if(this.windowManagerObj){this.elements.windows=this.buildWindows();this.holder.appendChild(this.elements.windows);}},show:function(){this.holder.style.display="block";this.visible=true;},hide:function(){this.holder.style.display="none";this.visible=false;},setStatisticsObj:function(statsObj){this.statisticsObj=statsObj;},setWindowManagerObj:function(windowMngrObj){this.windowManagerObj=windowMngrObj;},setOpacity:function(opacity){this.opacityValue=parseInt(opacity*100,10);this.elements.inputOpacity.value=this.opacityValue+"%";this.windowManagerObj.setWindowsOpacity(parseFloat((this.opacityValue/100).toFixed(2),10));this.sliderControl.setValue(this.opacityValue,true);},setShowNames:function(visible){this.layer.showLabel(visible);if(this.windowManagerObj){var windows=this.windowManagerObj.getWindowsWithIds();for(var i=0;i<windows.length;++i){windows[i].map.getBaseLayers().TERRITORY_MAP.showLabel(visible);}}
if(this.statisticsObj){this.statisticsObj.setTerritoryNamesVisibility(visible);}},setOutlineColor:function(color){color=SAPO.Maps.Utils.convertHexToRGB(color);this.layer.setOutlineColor(color);if(this.windowManagerObj){var windows=this.windowManagerObj.getWindowsWithIds();for(var i=0;i<windows.length;++i){windows[i].map.baseLayers.TERRITORY_MAP.setOutlineColor(color);}}else{alert("windowManagerObj does not exist here");}
if(this.statisticsObj){this.statisticsObj.setOutlineColor(color);}},checkTerritoryZoneElements:function(){if(!this.isDrawn()){return;}
var map=this.layer.map;if(map.baseLayer==map.getBaseLayers().TERRITORY_MAP){this.elements.labelSelectShapeTypes.className='';this.elements.selectShapeType.className='';this.elements.selectShapeType.disabled=false;this.elements.labelArea.className='';this.elements.inputAreaColor.className='';this.elements.inputAreaColor.disabled=false;this.elements.territoryLink.style.display='none';}else{this.elements.labelSelectShapeTypes.className='smapi_inactive';this.elements.selectShapeType.className='disabled_input';this.elements.selectShapeType.disabled=true;this.elements.labelArea.className='smapi_inactive';this.elements.inputAreaColor.className='disabled_input';this.elements.inputAreaColor.disabled=true;this.elements.territoryLink.style.display='block';}
var selectedShowNames=this.layer.parameters.showLabels;var showIcons=this.layer.parameters.showIcons;if(showIcons){this.elements.labelIcon.className='';this.elements.inputIcon.className='';}else{this.elements.labelIcon.className='smapi_inactive';this.elements.inputIcon.className='disabled_input';}
if(!selectedShowNames){this.elements.inputShowNamesInCentroid.disabled=true;this.elements.inputShowIcons.disabled=true;this.elements.inputIcon.disabled=true;this.elements.inputShowNamesInCentroid.className='smapi_inactive';this.elements.inputShowIcons.className='smapi_inactive';this.elements.labelShowNamesInCentroid.className='smapi_inactive';this.elements.labelShowIcons.className='smapi_inactive';this.elements.labelIcon.className='smapi_inactive';this.elements.inputIcon.className='disabled_input';}else{this.elements.inputShowNamesInCentroid.disabled=false;this.elements.inputShowIcons.disabled=false;this.elements.inputIcon.disabled=false;this.elements.inputShowNamesInCentroid.className='';this.elements.inputShowIcons.className='';this.elements.labelShowNamesInCentroid.className='';this.elements.labelShowIcons.className='';}},checkFloatWindowsZoneElements:function(){if(!this.windowManagerObj){return;}
var acoresWindowOpened=this.windowManagerObj.getAcoresWindow()&&!this.windowManagerObj.getAcoresWindow().windowControl.isHidden();var medeiraWindowOpened=this.windowManagerObj.getMadeiraWindow()&&!this.windowManagerObj.getMadeiraWindow().windowControl.isHidden();if(!acoresWindowOpened&&!medeiraWindowOpened){this.elements.inputHeader.disabled=true;this.elements.inputHeader.className='smapi_inactive';this.elements.labelHeader.className='smapi_inactive';SAPO.Maps.Utils.addClassName(this.elements.labelWindowsBackgroundColor,'smapi_inactive');this.elements.inputWindowsBackgroundColor.className='disabled_input';this.elements.inputWindowsBackgroundColor.jscolor.hidePicker();this.elements.inputWindowsBackgroundColor.disabled=true;this.elements.floatWindowsLabel.className='smapi_inactive';this.sliderControl.disableControl();this.elements.inputOpacity.disabled=true;SAPO.Maps.Utils.addClassName(this.elements.inputOpacity,'disabled_input');}else{this.elements.inputHeader.disabled=false;this.elements.inputHeader.className='';this.elements.labelHeader.className='';SAPO.Maps.Utils.removeClassName(this.elements.labelWindowsBackgroundColor,'smapi_inactive');this.elements.inputWindowsBackgroundColor.className='';this.elements.inputWindowsBackgroundColor.disabled=false;this.elements.floatWindowsLabel.className='';this.sliderControl.enableControl();this.elements.inputOpacity.disabled=false;SAPO.Maps.Utils.removeClassName(this.elements.inputOpacity,'disabled_input');}},buildterritoryLink:function(){var link=document.createElement('a');link.href='#';link.className='smapi_territory_link';link.onclick=function(){this.layer.map.setBaseLayer(this.layer);return false;}.bindObj(this);link.innerHTML="Ir para o modo territorial";this.elements.territoryLink=link;return link;},buildTerritory:function(){var div_wrapper=document.createElement("div");div_wrapper.className='smapi_zone_header';var h2_title=document.createElement("h2");var label_shapeType=document.createElement("label");var select_shapeType=document.createElement("select");var div_territory_options=document.createElement("div");var label_territory_options_names=document.createElement("label");var input_territory_options_names=document.createElement("input");var label_territory_options_centerNames=document.createElement("label");var input_territory_options_centerNames=document.createElement("input");var label_territory_options_icons=document.createElement("label");var input_territory_options_icons=document.createElement("input");div_territory_options.className="territory_check_options";h2_title.innerHTML="Território";var random=this.CLASS_NAME+Math.random();label_shapeType.id=random;label_shapeType.className="df_label";label_shapeType.htmlFor=random;label_shapeType.innerHTML="&Aacute;rea:";select_shapeType.id=random;var option;var shapeTypes=this.layer.getShapeTypes();var initialIndex=0;for(var i=0;i<shapeTypes.length;++i){option=document.createElement("option");option.value=shapeTypes[i].id;if(shapeTypes[i].id===this.layer.parameters.shape){initialIndex=i;}
option.innerHTML=shapeTypes[i].name;select_shapeType.appendChild(option);}
select_shapeType.selectedIndex=initialIndex;random=this.CLASS_NAME+Math.random();label_territory_options_names.htmlFor=random;input_territory_options_names.id=random;input_territory_options_names.type="checkbox";input_territory_options_names.checked=this.statisticsObj===null?true:false;random=this.CLASS_NAME+Math.random();label_territory_options_centerNames.htmlFor=random;input_territory_options_centerNames.id=random;input_territory_options_centerNames.type="checkbox";random=this.CLASS_NAME+Math.random();label_territory_options_icons.htmlFor=random;input_territory_options_icons.id=random;input_territory_options_icons.type="checkbox";label_territory_options_names.appendChild(input_territory_options_names);label_territory_options_names.appendChild(document.createTextNode("Mostrar nomes"));label_territory_options_centerNames.appendChild(input_territory_options_centerNames);label_territory_options_centerNames.appendChild(document.createTextNode("Mostrar os nomes no centróide"));label_territory_options_icons.appendChild(input_territory_options_icons);label_territory_options_icons.appendChild(document.createTextNode("Mostrar icones"));div_territory_options.appendChild(label_territory_options_names);div_territory_options.appendChild(label_territory_options_centerNames);div_territory_options.appendChild(label_territory_options_icons);div_wrapper.appendChild(h2_title);div_wrapper.appendChild(label_shapeType);div_wrapper.appendChild(select_shapeType);div_wrapper.appendChild(document.createElement("br"));div_wrapper.appendChild(div_territory_options);var selectedShapeType=this.layer.parameters.shape;for(var j=0;j<select_shapeType.options.length;++j){if(select_shapeType.options[j].value===select_shapeType){select_shapeType.selectedIndex=j;break;}}
var selectedShowNames=this.layer.parameters.showLabels;input_territory_options_names.checked=selectedShowNames;var selectedShowNamesInCentroid=this.layer.parameters.showLabelsInCentroid;input_territory_options_centerNames.checked=selectedShowNamesInCentroid;var selectedShowIcons=this.layer.parameters.showIcons;input_territory_options_icons.checked=selectedShowIcons;OpenLayers.Event.observe(select_shapeType,"change",this.shapeChange.bindObj(this));OpenLayers.Event.observe(input_territory_options_names,"click",this.showNamesChange.bindObj(this));OpenLayers.Event.observe(input_territory_options_centerNames,"click",this.showNamesInCentroidChange.bindObj(this));OpenLayers.Event.observe(input_territory_options_icons,"click",this.showIconsChange.bindObj(this));this.elements.labelSelectShapeTypes=label_shapeType;this.elements.selectShapeType=select_shapeType;this.elements.inputShowNames=input_territory_options_names;this.elements.inputShowNamesInCentroid=input_territory_options_centerNames;this.elements.inputShowIcons=input_territory_options_icons;this.elements.labelShowNamesInCentroid=label_territory_options_centerNames;this.elements.labelShowIcons=label_territory_options_icons;this.elementsObserved.push(select_shapeType);this.elementsObserved.push(input_territory_options_names);this.elementsObserved.push(input_territory_options_centerNames);this.elementsObserved.push(input_territory_options_icons);return div_wrapper;},buildStyle:function(){var div_wrapper=document.createElement("div");var label_icon=document.createElement("label");var div_input_icon=document.createElement("div");var input_icon=document.createElement("input");var label_area=document.createElement("label");var div_input_area=document.createElement("div");var input_area=document.createElement("input");var label_border=document.createElement("label");var div_input_border=document.createElement("div");var input_border=document.createElement("input");div_input_icon.className="inputWrapper";div_input_area.className="inputWrapper";div_input_border.className="inputWrapper";div_wrapper.className="terrain_labels_and_inputs";input_icon.className="disabled_input";var random=this.CLASS_NAME+Math.random();label_icon.htmlFor=random;label_icon.innerHTML="Icone (png)";input_icon.id=random;input_icon.type="text";input_icon.disabled=true;input_icon.value=this.iconURL;random=this.CLASS_NAME+Math.random();label_area.htmlFor=random;label_area.innerHTML="Cor da área";input_area.id=random;input_area.type="text";var x=new jscolor.color(input_area);random=this.CLASS_NAME+Math.random();label_border.htmlFor=random;label_border.innerHTML="Cor do contorno";input_border.id=random;input_border.type="text";x=new jscolor.color(input_border);random=this.CLASS_NAME+Math.random();div_input_icon.appendChild(input_icon);div_input_area.appendChild(input_area);div_input_border.appendChild(input_border);div_wrapper.appendChild(label_icon);div_wrapper.appendChild(div_input_icon);div_wrapper.appendChild(label_area);div_wrapper.appendChild(div_input_area);div_wrapper.appendChild(label_border);div_wrapper.appendChild(div_input_border);var selectedColor=this.layer.parameters.color;selectedColor=SAPO.Maps.Utils.convertRGBToHex(selectedColor);selectedColor=selectedColor.replace(/#/,"");input_area.value=selectedColor;var selectedBorderColor=this.layer.parameters.outlineColor;selectedBorderColor=SAPO.Maps.Utils.convertRGBToHex(selectedBorderColor);selectedBorderColor=selectedBorderColor.replace(/#/,"");input_border.value=selectedBorderColor;OpenLayers.Event.observe(input_icon,"change",this.iconURLChange.bindObj(this));OpenLayers.Event.observe(input_area,"change",this.areaColorChange.bindObj(this));OpenLayers.Event.observe(input_border,"change",this.borderColorChange.bindObj(this));this.elements.labelIcon=label_icon;this.elements.inputIcon=input_icon;this.elements.labelArea=label_area;this.elements.inputAreaColor=input_area;this.elements.inputBorderColor=input_border;this.elementsObserved.push(input_icon);this.elementsObserved.push(input_area);this.elementsObserved.push(input_border);return div_wrapper;},buildWindows:function(){var div_wrapper=document.createElement("div");var div_wrapper_checkbox=document.createElement("div");var h2=document.createElement('h2');var label_acores=document.createElement("label");var input_acores=document.createElement("input");var label_madeira=document.createElement("label");var input_madeira=document.createElement("input");var label_header=document.createElement("label");var input_header=document.createElement("input");h2.innerHTML="Janelas flutuantes";div_wrapper.className="smapi_zone_header";div_wrapper_checkbox.className="territory_check_options";var random=this.CLASS_NAME+Math.random();label_acores.htmlFor=random;input_acores.id=random;input_acores.type="checkbox";random=this.CLASS_NAME+Math.random();label_madeira.htmlFor=random;input_madeira.id=random;input_madeira.type="checkbox";random=this.CLASS_NAME+Math.random();label_header.htmlFor=random;input_header.id=random;input_header.type="checkbox";label_acores.appendChild(input_acores);label_acores.appendChild(document.createTextNode("Mostrar Açores numa janela flutuante"));label_madeira.appendChild(input_madeira);label_madeira.appendChild(document.createTextNode("Mostrar Madeira numa janela flutuante"));label_header.appendChild(input_header);label_header.appendChild(document.createTextNode("Mostrar cabeçalhos e limites das janelas"));div_wrapper.appendChild(h2);div_wrapper.appendChild(div_wrapper_checkbox);div_wrapper_checkbox.appendChild(label_acores);div_wrapper_checkbox.appendChild(label_madeira);div_wrapper_checkbox.appendChild(label_header);this.buildWindowOptions(div_wrapper,random);OpenLayers.Event.observe(input_acores,"click",this.acoresChange.bindObj(this));OpenLayers.Event.observe(input_madeira,"click",this.madeiraChange.bindObj(this));OpenLayers.Event.observe(input_header,"click",this.headerChange.bindObj(this));this.windowManagerObj.events.register("windowclosed",this,this.windowClosed.bindObj(this));this.elements.inputAcores=input_acores;this.elements.inputMadeira=input_madeira;this.elements.labelHeader=label_header;this.elements.inputHeader=input_header;this.elementsObserved.push(input_acores);this.elementsObserved.push(input_madeira);this.elementsObserved.push(input_header);this.acoresOpened=this.windowManagerObj.getAcoresWindow()&&!this.windowManagerObj.getAcoresWindow().windowControl.isHidden();this.madeiraOpened=this.windowManagerObj.getMadeiraWindow()&&!this.windowManagerObj.getMadeiraWindow().windowControl.isHidden();input_madeira.checked=this.madeiraOpened;input_acores.checked=this.acoresOpened;input_header.checked=this.windowManagerObj.isHeaderAndFooterVisible();return div_wrapper;},buildWindowOptions:function(div_wrapper,random){var label_background=document.createElement("label");var input_background=document.createElement("input");var div_opacity=document.createElement("div");var span_start_input=document.createElement("span");var input_opacity=document.createElement("input");div_opacity.className="smapi_slider";span_start_input.className="smapi_input_start";input_opacity.className="smapi_opacity_input";input_opacity.style.width="35px";label_background.htmlFor=random;label_background.innerHTML="Cor de fundo da janela";input_background.id=random;label_background.className="label_background_color";input_background.type="text";input_background.value=this.windowManagerObj.getWindowsColor();input_background.jscolor=new jscolor.color(input_background);var callbacks={scope:this,slideChanged:this.opacityChange};this.opacityValue=this.windowManagerObj.getWindowsOpacity()*100;this.sliderControl=new SAPO.Maps.Control.SliderControl(callbacks,{div:div_opacity,controlSize:220,value:this.opacityValue});this.sliderControl.draw();input_opacity.type="text";input_opacity.value=this.opacityValue+"%";div_wrapper.appendChild(document.createElement('br'));div_wrapper.appendChild(label_background);div_wrapper.appendChild(input_background);var clear=document.createElement('div');clear.className='clear';div_wrapper.appendChild(clear);var div=document.createElement("div");div.className="opacity_title";div.innerHTML="Opacidade das janelas flutuantes:";div_wrapper.appendChild(div);div_wrapper.appendChild(div_opacity);div_wrapper.appendChild(span_start_input);div_wrapper.appendChild(input_opacity);OpenLayers.Event.observe(input_background,"change",this.windowsBackgroundChange.bindObj(this));this.elements.labelWindowsBackgroundColor=label_background;this.elements.inputWindowsBackgroundColor=input_background;this.elements.floatWindowsLabel=div;this.elementsObserved.push(input_background);OpenLayers.Event.observe(input_opacity,"change",this.opacityValueChange.bindObj(this));this.elements.inputOpacity=input_opacity;},opacityChange:function(value){this.setOpacity(parseFloat((value/100).toFixed(2),10));},opacityValueChange:function(){var value=this.elements.inputOpacity.value.replace(/%/,"");if(isNaN(value)){this.elements.inputOpacity.value=this.opacityValue+"%";return;}
this.setOpacity(value/100,true);},shapeChange:function(){var shapeType=this.elements.selectShapeType.options[this.elements.selectShapeType.selectedIndex].value;this.layer.setShapeType(shapeType);if(this.windowManagerObj){var windows=this.windowManagerObj.getWindowsWithIds();for(var i=0;i<windows.length;++i){windows[i].map.getBaseLayers().TERRITORY_MAP.setShapeType(shapeType);}}},showNamesChange:function(){var showNames=this.elements.inputShowNames.checked;this.setShowNames(showNames);this.checkTerritoryZoneElements();},showNamesInCentroidChange:function(){var showNamesInCentroid=this.elements.inputShowNamesInCentroid.checked;this.layer.showLabelsInCentroid(showNamesInCentroid);if(this.windowManagerObj){var windows=this.windowManagerObj.getWindowsWithIds();for(var i=0;i<windows.length;++i){windows[i].map.getBaseLayers().TERRITORY_MAP.showLabelsInCentroid(showNamesInCentroid);}}
if(this.statisticsObj){this.statisticsObj.setTerritoryCentroid(showNamesInCentroid);}},showIconsChange:function(){this.layer.setIconURL(this.iconURL);var showIcons=this.elements.inputShowIcons.checked;this.layer.showIcons(showIcons);if(this.windowManagerObj){var windows=this.windowManagerObj.getWindowsWithIds();for(var i=0;i<windows.length;++i){windows[i].map.getBaseLayers().TERRITORY_MAP.setIconURL(this.iconURL);windows[i].map.getBaseLayers().TERRITORY_MAP.showIcons(showIcons);}}
this.checkTerritoryZoneElements();if(this.statisticsObj){this.statisticsObj.showTerritoryIcons(showIcons,this.iconURL);}},iconURLChange:function(){var url=this.elements.inputIcon.value;this.iconURL=url;this.showIconsChange();},areaColorChange:function(){var color=this.elements.inputAreaColor.value;color=SAPO.Maps.Utils.convertHexToRGB(color);this.layer.setShapeColor(color);if(this.windowManagerObj){var windows=this.windowManagerObj.getWindowsWithIds();for(var i=0;i<windows.length;++i){windows[i].map.getBaseLayers().TERRITORY_MAP.setShapeColor(color);}}},borderColorChange:function(){var color=this.elements.inputBorderColor.value;this.setOutlineColor(color);},windowsBackgroundChange:function(){var color="#"+this.elements.inputWindowsBackgroundColor.value;this.windowManagerObj.setWindowsColor(color);},acoresChange:function(){var showAcores=this.elements.inputAcores.checked;var id=this.windowManagerObj.createAcoresWindow(null,true);var func=showAcores===true?this.windowManagerObj.openWindow:this.windowManagerObj.closeWindow;func.apply(this.windowManagerObj,[id]);this.elements.inputAcores.checked=showAcores;this.checkFloatWindowsZoneElements();},madeiraChange:function(){var showMadeira=this.elements.inputMadeira.checked;var id=this.windowManagerObj.createMadeiraWindow(null,true);var func=showMadeira===true?this.windowManagerObj.openWindow:this.windowManagerObj.closeWindow;func.apply(this.windowManagerObj,[id]);this.elements.inputMadeira.checked=showMadeira;this.checkFloatWindowsZoneElements();},windowClosed:function(evt){if(evt.id===this.windowManagerObj.getMadeiraWindowId()){this.elements.inputMadeira.checked=false;}
if(evt.id===this.windowManagerObj.getAcoresWindowId()){this.elements.inputAcores.checked=false;}
this.checkFloatWindowsZoneElements();},headerChange:function(){var showHeader=this.elements.inputHeader.checked;this.windowManagerObj.toggleHeaderAndFooter(showHeader);},CLASS_NAME:"SAPO.Maps.Renderer.AdministrativePanel"});SAPO.Maps.Search=OpenLayers.Class({markerImgs:'http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Markers/new/m',markerImgsExtension:'.png',geocoder:null,listeners:null,map:null,panel:null,markers:null,pois:null,categorizedSearch:false,showEmptyZones:false,zones:null,nrZones:null,openedZone:null,showDashboard:true,dashboard:null,openedDashboardPOI:null,openedDashboardTab:null,dashboardMarker:null,resultsPerPage:10,allowPaging:false,searchForPOIS:false,searchForStreetsAndLocations:false,openDetailsWhenClick:true,numberOfPagesShown:5,currentPage:1,totalResults:0,query:null,request:null,selectedIdx:null,overedIdx:null,status:null,pageChanged:false,div:null,pagingDiv:null,displaySingleResult:true,showSearchTitleMessage:true,titleHeader:null,borders:null,whatsHereSearch:false,nearSearch:null,nearSearchMarker:null,initialize:function(map,panel,options){OpenLayers.Util.extend(this,options);this.geocoder=new SAPO.Maps.Geocoder();this.listeners={};this.status=SAPO.Maps.Request.Status.STOP;if(map){this.map=map;this.markers=new SAPO.Maps.Markers("searchResults");this.map.addMarkers(this.markers);this.markers.setZIndex(500);}
if(panel){this.panel=typeof(panel)=='string'?document.getElementById(panel):panel;}
this.onComplete=OpenLayers.Function.bind(this.complete,this);this.onTimeout=OpenLayers.Function.bind(this.timeout,this);},search:function(query,options){if(this.status==SAPO.Maps.Request.Status.REQUESTING){throw'cannot query the server while the last request is waiting';}
if(options){this.nearSearch=options.nearSearch;}
this.prepareRequest();OpenLayers.Util.extend(this,options);this.resultsPerPage=this.resultsPerPage>10?10:this.resultsPerPage;this.displaySingleResult=options?(options.displaySingleResult===false?false:true):true;this.query=query;try{this.notifyListeners('beforeSearch',[this,this.query]);}
catch(e){try{this.notifyListeners('error',[this,e]);}
catch(e1){}}
this.getResults();},searchWhatsHere:function(lonlat,zoom){if(this.status==SAPO.Maps.Request.Status.REQUESTING){throw'cannot query the server while the last request is waiting';}
this.allowPaging=false;this.prepareRequest();this.whatsHereSearch=true;this.getResults(lonlat,zoom);},searchNearLonLat:function(query,lonlat){var radius;var zoom=this.map.getZoom();if(zoom>=4&&zoom<=8){radius=30000;}
if(zoom>=9&&zoom<=11){radius=10000;}
if(zoom>=12&&zoom<=14){radius=3000;}
if(zoom>=15&&zoom<=16){radius=1000;}
if(zoom>=17&&zoom<=19){radius=500;}
var bbox=SAPO.Maps.Utils.getBoundingBoxFromCenterAndRadius(lonlat,radius);this.search(query,{bbox:bbox,categorizedSearch:true,nearSearch:{lonlat:lonlat}});},cancel:function(){if(this.status===SAPO.Maps.Request.Status.REQUESTING||this.request){this.request.cancel=true;this.status=SAPO.Maps.Request.Status.CANCELED;this.request=null;try{this.notifyListeners('canceled',[this]);}
catch(e){try{this.notifyListeners('error',[this,e]);}catch(e1){}}}},clear:function(silent){if(this.status==SAPO.Maps.Request.Status.REQUESTING){throw'cannot clear the info until the request is pending';}
if(this.selectedIdx!==null){this.unselectResult(this.selectedIdx);}
this.openedZone=null;this.removeDashboardMarker();this.cleanMarkers();if(this.nearSearchMarker){this.map.removeOverlay(this.nearSearchMarker);this.nearSearchMarker=null;}
this.cleanPanel();if(!silent){try{this.notifyListeners('cleanResults',[this]);}
catch(e){try{this.notifyListeners('error',[this,e]);}catch(e1){}}}},clearZone:function(zoneName){var zone=this.zones[zoneName];var content=zone.content;content.innerHTML="";},openDetails:function(resultIdx){if(this.markers){var markers=this.markers.getMarkers();var idx=markers.length-resultIdx-1;if(!this.map.getBounds().containsLonLat(markers[idx].getLonLat())){this.map.setMapCenter(markers[idx].getLonLat());}
this.removeDashboardMarker();markers[idx].openPopup(markers[idx].html,this.borders?{borders:this.borders}:null);}
if(this.panel){var node=null;if(!this.categorizedSearch){node=this.div.childNodes[resultIdx];node.className+=' search_selected_smapi';}
else{try{var offset=this.zones[this.openedZone].content.childNodes[0].className.contains("item")?0:1;node=this.zones[this.openedZone].content.childNodes[resultIdx+offset];if(node){node.className+=' selected';}}catch(e){}}}
this.selectedIdx=resultIdx;},selectResult:function(resultIdx,zoneName,onPanel){try{this.notifyListeners('beforeSelected',[this,this.pois[resultIdx],resultIdx,this.currentPage,zoneName]);}
catch(e){try{this.notifyListeners('error',[this,e]);}
catch(e1){}}
if(!this.categorizedSearch||this.isCoords){if(this.selectedIdx!==null){this.unselectResult(this.selectedIdx);}
if(resultIdx>=this.pois.length){return;}
if(this.openDetailsWhenClick){this.openDetails(resultIdx);}
this.selectedIdx=resultIdx;}
else{var zone=this.zones[zoneName];if(!zone){return;}
if(resultIdx>=zone.pois.length){return;}
if(this.selectedIdx!==null){this.unselectResult(this.selectedIdx);}
if(this.openedZone!==zoneName){this.openZone(zoneName);}
if(this.openDetailsWhenClick){this.openDetails(resultIdx);this.openDashboard(zone.pois[resultIdx]);}
this.selectedIdx=resultIdx;}
var evtType=onPanel?'selectedOnPanel':'selectedOnMap';try{if(!this.categorizedSearch||this.isCoords){this.notifyListeners(evtType,[this,this.pois[resultIdx],resultIdx,this.currentPage,zoneName]);this.notifyListeners('selected',[this,this.pois[resultIdx],resultIdx,this.currentPage,zoneName]);}
else{this.notifyListeners(evtType,[this,this.zones[this.openedZone].pois[resultIdx],resultIdx,this.currentPage,zoneName]);this.notifyListeners('selected',[this,this.zones[this.openedZone].pois[resultIdx],resultIdx,this.currentPage,zoneName]);}}
catch(e2){try{this.notifyListeners('error',[this,e2]);}
catch(e3){}}},unselectResult:function(resultIdx){this.removeDashboardMarker();if(this.selectedIdx===null||this.selectedIdx!==resultIdx||(this.openedZone&&resultIdx>=this.zones[this.openedZone].pois.length)){return;}
this.selectedIdx=null;if(this.markers){var markers=this.markers.getMarkers();var idx=markers.length-resultIdx-1;markers[idx].closePopup();}
if(this.panel){var node=null;if(!this.categorizedSearch){node=this.div.childNodes[resultIdx];node.className='search_item_smapi';}
else{var offset=this.zones[this.openedZone].content.childNodes[0].className.contains("item")?0:1;node=this.zones[this.openedZone].content.childNodes[resultIdx+offset];if(node){node.className='item';}}}
try{this.notifyListeners('unselected',[this,this.pois[resultIdx],resultIdx,this.currentPage,this.openedZone]);}
catch(e){try{this.notifyListeners('error',[this,e]);}catch(e4){}}},highlightResult:function(idx){this.deHighlightResult();if(idx===null){return;}
if(this.openedZone===null){return;}
var zone=this.zones[this.openedZone];if(idx>zone.pois.length){return;}
try{var offset=this.zones[this.openedZone].content.childNodes[0].className.contains("item")?0:1;var node=this.zones[this.openedZone].content.childNodes[idx+offset];node.childNodes[0].childNodes[0].src="http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Markers/new/selected/m"+(idx+1)+".png";this.zones[this.openedZone].markers[this.zones[this.openedZone].markers.length-idx-1].setStyle({markerImage:"http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Markers/new/big/m"+(idx+1)+".png",size:new OpenLayers.Size(29,38),markerAnchor:new OpenLayers.Pixel(-15,-38),zIndex:50});this.overedIdx=idx;}catch(e){}},deHighlightResult:function(){if(this.overedIdx===null){return;}
var zone=this.zones[this.openedZone];try{var offset=this.zones[this.openedZone].content.childNodes[0].className.contains("item")?0:1;var node=this.zones[this.openedZone].content.childNodes[this.overedIdx+offset];node.childNodes[0].childNodes[0].src="http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Markers/new/m"+(this.overedIdx+1)+".png";this.zones[this.openedZone].markers[this.zones[this.openedZone].markers.length-this.overedIdx-1].setStyle({markerImage:"http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Markers/new/m"+(this.overedIdx+1)+".png",size:new OpenLayers.Size(22,28),markerAnchor:new OpenLayers.Pixel(-11,-28),zIndex:10});this.overedIdx=null;}catch(e){}},zoomInResult:function(idx){if(!this.openedZone){return;}
var marker=this.zones[this.openedZone].markers[this.zones[this.openedZone].markers.length-idx];var zoomLevel=this.openedZone==="Localidades"?14:16;if(!this.map.isValidZoomLevel(zoomLevel)){zoomLevel=14;}
var center=marker.getLonLat();SAPO.Maps.Utils.CenterMapConsideringBorders(this.map,center,this.borders,zoomLevel);marker.popup.panIntoView(marker.popup._popupSize);},getStatus:function(){return this.status;},getPOIS:function(zoneName){if(!this.categorizedSearch){return this.pois;}
if(!zoneName||!this.zones[zoneName]){return null;}
return this.zones[zoneName].pois;},getCurrentPage:function(zoneName){if(!this.categorizedSearch){return this.currentPage;}
if(this.zones&&this.zones[zoneName]){return this.zones[zoneName].currentPage;}
return-1;},getSelectedIndex:function(){return this.selectedIdx;},goToPage:function(page,zoneName,force){if(this.allowPaging&&this.status===SAPO.Maps.Request.Status.REQUESTING){throw'Exception occurred at goToPage method: Pending request. Cancel the request first.';}
if(zoneName&&zoneName==="Coordenadas"){return;}
if((page===this.getCurrentPage(zoneName)||page<=0)&&!force){return;}
var numPages=null;if(!this.categorizedSearch){this.pageChanged=true;numPages=Math.ceil(this.totalResults/this.resultsPerPage);this.currentPage=page>numPages?numPages:page;this.clear(true);}
else{this.pageChanged=zoneName;numPages=Math.ceil(this.zones[zoneName].totalResults/this.resultsPerPage);this.zones[zoneName].currentPage=page>numPages?numPages:page;this.zones[zoneName].content.style.overflow="hidden";}
this.getResults();},getTotalResults:function(){if(this.status==SAPO.Maps.Request.Status.REQUESTING||this.status==SAPO.Maps.Request.Status.STOP||this.status==SAPO.Maps.Request.Status.ERROR||this.status==SAPO.Maps.Request.Status.CANCELED){return 0;}
if(!this.categorizedSearch){return this.totalResults;}
else{var totalResults=0;for(var e in this.zones){totalResults+=this.zones[e].totalResults;}
return totalResults;}},getMarker:function(idx){if(this.status==SAPO.Maps.Request.Status.REQUESTING||this.status==SAPO.Maps.Request.Status.STOP||this.status==SAPO.Maps.Request.Status.ERROR||this.status==SAPO.Maps.Request.Status.CANCELED){return null;}
if(this.markers){var markers=this.markers.getMarkers();if(idx>=markers.length){return null;}
return markers[(markers.length-1)-idx];}
return null;},getMarkers:function(){if(this.status==SAPO.Maps.Request.Status.REQUESTING||this.status==SAPO.Maps.Request.Status.STOP||this.status==SAPO.Maps.Request.Status.ERROR||this.status==SAPO.Maps.Request.Status.CANCELED){return null;}
if(this.markers){return this.markers.getMarkers();}
return null;},getResults:function(lonlat,zoom){var isCoords=SAPO.Maps.Utils.checkQuery(this.query);this.isCoords=isCoords;if(isCoords){this.pois=[isCoords];this.status=SAPO.Maps.Request.Status.OK;if(this.displaySingleResult){if(!this.categorizedSearch){this.displayResults(this.pois);}
else{this.zones={};this.zones.Coordenadas={currentPage:1,nrOfPages:1,totalResults:1,pois:[{Name:isCoords.Latitude+", "+isCoords.Longitude,Category:"Coordenadas",Latitude:isCoords.Latitude,Longitude:isCoords.Longitude}]};this.totalResults=1;this.displayResultsCategorized();this.openZone("Coordenadas");}}
this.totalResults=this.pois.length;try{this.notifyListeners('completed',[this,this.pois,this.totalResults]);}
catch(e3){try{this.notifyListeners('error',[this,e3]);}catch(e4){}}
return;}
if(this.checkIfTheQueryMatchesWithMadeiraOrAzores_hack()){return;}
if(this.panel){if(!this.categorizedSearch||!this.pageChanged){SAPO.Maps.Utils.displayWaitIcon(this.panel);}
else{if(this.pageChanged===this.openedZone){this.clearZone(this.openedZone);SAPO.Maps.Utils.displayWaitIcon(this.zones[this.openedZone].content);}}}
this.request={cancel:false};if(this.whatsHereSearch){this.geocoder.findWhatsHere(lonlat,zoom,this.onComplete,this.onTimeout,{context:this.request});}else{if(this.categorizedSearch){var opts={resultsPerPage:this.resultsPerPage,pageNumber:this.pageChanged?this.zones[this.pageChanged].currentPage:1,bbox:this.bbox,context:this.request,searchForPOIS:this.searchForPOIS,searchForStreetsAndLocations:this.searchForStreetsAndLocations,dashboard:this.showDashboard};if(this.pageChanged){opts.category=this.pageChanged;}
this.geocoder.getLocationsCategorized(this.query,this.onComplete,this.onTimeout,opts);}
else{this.geocoder.getLocations(this.query,this.onComplete,this.onTimeout,{resultsPerPage:this.resultsPerPage,pageNumber:this.currentPage,bbox:this.bbox,context:this.request,searchForPOIS:this.searchForPOIS,searchForStreetsAndLocations:this.searchForStreetsAndLocations});}}},checkIfTheQueryMatchesWithMadeiraOrAzores_hack:function(){if(this.query.toLowerCase().match(/^a\u00E7ores/)||this.query.toLowerCase().match(/^azores/)){this.pois=[{Name:'Açores',Latitude:38.711232699162856,Longitude:-27.19116201562631,CategoryId:'213',Category:'Localidades',zoom:7,text:'Arquipélago dos Açores',martelada:true}];this.status=SAPO.Maps.Request.Status.OK;this.totalResults=this.pois.length;if(!this.categorizedSearch){this.displayResults(this.pois);}
else{this.pois=[{name:"Localidades",totalResults:1,POIs:this.pois}];this.parseZones(this.pois);this.displayResultsCategorized();this.openZone("Localidades");}
try{this.notifyListeners('completed',[this,this.pois,this.totalResults]);}
catch(e3){try{this.notifyListeners('error',[this,e3]);}catch(e4){}}
return true;}
if(this.query.toLowerCase().match(/^madeira/)){this.pois=[{Name:'Madeira',Latitude:32.788429,Longitude:-16.961517,CategoryId:'213',Category:'Localidades',zoom:10,text:'Arquipélago da Madeira',martelada:true}];this.status=SAPO.Maps.Request.Status.OK;this.totalResults=this.pois.length;if(!this.categorizedSearch){this.displayResults(this.pois);}
else{this.pois=[{name:"Localidades",totalResults:1,POIs:this.pois}];this.parseZones(this.pois);this.displayResultsCategorized(this.pois);this.openZone("Localidades");}
try{this.notifyListeners('completed',[this,this.pois,this.totalResults]);}
catch(e5){try{this.notifyListeners('error',[this,e3]);}catch(e6){}}
return true;}
return false;},cleanPanel:function(){if(this.panel&&this.div){this.panel.removeChild(this.div);if(this.pagingDiv){this.panel.removeChild(this.pagingDiv);}
if(this.titleHeader){this.panel.removeChild(this.titleHeader);}
this.div=null;this.pagingDiv=null;this.titleHeader=null;}},cleanMarkers:function(){if(this.map&&this.markers){this.markers.removeMarkers();}},prepareRequest:function(){this.state=SAPO.Maps.Request.Status.REQUESTING;this.clear(true);this.pois=null;this.selectedIdx=null;this.currentPage=1;this.totalResults=0;this.query='';this.pageChanged=false;this.whatsHereSearch=false;this.categorizedSearch=false;this.openedZone=null;this.zones=null;this.dashboard=null;this.openedDashboardTab=null;this.openedDashboardPOI=null;this.overedIdx=null;if(!this.nearSearch&&this.nearSearchMarker){this.map.removeOverlay(this.nearSearchMarker);this.nearSearchMarker=null;}
if(this.nearSearch&&this.map){this.nearSearchMarker=new SAPO.Maps.Marker(this.nearSearch.lonlat,null,{markerImage:'http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Search/imHere.png',size:new OpenLayers.Size(34,47),markerAnchor:new OpenLayers.Pixel(-17,-47)});this.map.addOverlay(this.nearSearchMarker);}},openZone:function(zoneName){if(!this.panel){return;}
if(zoneName===this.openedZone&&!this.pageChanged){return;}
var zone=this.zones[zoneName];if(!zone){return;}
this.closeZone();if(zone.pois.length===0){this.openedZone=zoneName;zone.content.style.display="block";this.goToPage(1,zoneName,true);return;}
zone.header.className+=" selected_cat";zone.header.childNodes[1].childNodes[1].className="slideUpbtn";if(this.map){this.cleanMarkers();this.markers.addMarkers(zone.markers);var bounds=this.markers.getBounds();if(bounds){var adjustedBounds=bounds;if(zone.pois.length===1&&(zone.pois[0].Category==="Localidades"||zone.pois[0].Category==="Códigos Postais")){adjustedBounds=new OpenLayers.Bounds(bounds.left-0.02199,bounds.bottom-0.02199,bounds.right+0.02199,bounds.top+0.02199);}
SAPO.Maps.Utils.AdjustBoundsConsideringBorders(this.map,adjustedBounds,this.borders);if(this.map.getZoom()===19){this.map.zoomTo(16);}}
var center=null;if(this.zones[zoneName].pois[0].Name==="Açores"){center=new OpenLayers.LonLat(this.zones[zoneName].pois[0].Longitude,this.zones[zoneName].pois[0].Latitude);SAPO.Maps.Utils.CenterMapConsideringBorders(this.map,center,this.borders,7);}
if(this.zones[zoneName].pois[0].Name==="Madeira"){center=new OpenLayers.LonLat(this.zones[zoneName].pois[0].Longitude,this.zones[zoneName].pois[0].Latitude);SAPO.Maps.Utils.CenterMapConsideringBorders(this.map,center,this.borders,9);}}
zone.content.style.display="block";this.openedZone=zoneName;if(this.zones[zoneName].pois.length===1||this.zones[zoneName].pois[0].Dashboard){this.selectResult(0,zoneName);}
try{this.notifyListeners('zoneOpened',[this,this.openedZone]);}
catch(e1){try{this.notifyListeners('error',[this,e1]);}
catch(e2){}}},closeZone:function(){if(!this.panel){return;}
if(!this.openedZone){return;}
var zone=this.zones[this.openedZone];if(!zone){return;}
this.unselectResult(this.selectedIdx);this.closeDashboardTab();zone.header.className=zone.header.className.replace(/selected_cat/,"");zone.header.childNodes[1].childNodes[1].className="slideDownbtn";if(this.map){this.markers.removeMarkers();}
zone.content.style.display="none";try{this.notifyListeners('zoneClosed',[this,this.openedZone]);}
catch(e1){try{this.notifyListeners('error',[this,e1]);}
catch(e2){}}
this.openedZone=null;},showAllZones:function(){this.showEmptyZones=true;this.displayResultsCategorized(true);var zoneToOpen=this.openedZone;this.openedZone=null;this.openZone(zoneToOpen);try{this.notifyListeners('completed',[this]);}catch(e){try{this.notifyListeners('error',[this,e]);}catch(e1){}}},getNrZones:function(){this.nrZones=0;for(var e in this.zones){this.nrZones++;}
return this.nrZones;},openDashboard:function(poi){this.closeDashboard();if(this.dashboard[poi.POIId]){this.dashboard[poi.POIId].html.style.display="block";this.openedDashboardPOI=poi;for(var e in this.dashboard[poi.POIId]){if(e==="html"){continue;}
this.openedDashboardTab=null;this.openDashboardTab(e);break;}}},closeDashboard:function(poi){if(this.openedDashboardPOI){this.dashboard[this.openedDashboardPOI.POIId].html.style.display="none";this.closeDashboardTab();this.openedDashboardPOI=null;}},openDashboardTab:function(tabName){var dashboardItem=this.dashboard[this.openedDashboardPOI.POIId][tabName];if(!dashboardItem){return;}
if(this.openedDashboardTab===tabName){return;}
this.removeDashboardMarker();this.closeDashboardTab();dashboardItem.tab.className="active_tab";dashboardItem.content.style.display="block";this.openedDashboardTab=tabName;try{this.notifyListeners('dashboardTabOpened',[this,tabName,this.openedDashboardPOI]);}
catch(e){try{this.notifyListeners('error',[this,e]);}
catch(e1){}}},closeDashboardTab:function(){if(!this.openedDashboardTab){return;}
this.dashboard[this.openedDashboardPOI.POIId][this.openedDashboardTab].tab.className="";this.dashboard[this.openedDashboardPOI.POIId][this.openedDashboardTab].content.style.display="none";this.openedDashboardTab=null;},removeDashboardMarker:function(){if(!this.dashboardMarker){return;}
this.map.removeOverlay(this.dashboardMarker);this.dashboardMarker.unRegisterEvent("popupclosed",this,this.removeDashboardMarker);this.dashboardMarker=null;},complete:function(pois,context,totalresults){if(this.panel){if(this.categorizedSearch&&this.openedZone){SAPO.Maps.Utils.removeWaitIcon(this.zones[this.openedZone].content);}
else{SAPO.Maps.Utils.removeWaitIcon(this.panel);}}
try{if(context.cancel){return;}
this.status=SAPO.Maps.Request.Status.OK;this.totalResults=totalresults;this.pois=pois;if((this.totalResults>1||this.totalResults===1&&this.displaySingleResult)&&(this.panel||this.map)){if(this.categorizedSearch){this.parseZones(pois);this.displayResultsCategorized();if(this.openedZone){var zoneToOpen=this.openedZone;this.openedZone=null;this.openZone(zoneToOpen);}
else{for(var e in this.zones){this.openZone(e);break;}}}
else{this.displayResults(pois,totalresults);}}
else{if((pois.length===0||!this.zones)&&this.panel){var elem=document.createElement('div');elem.className='search_results_smapi';if(this.whatsHereSearch){SAPO.Maps.Utils.displayMessageHTML(elem,"Lamentamos mas não existem resultados para o local seleccionado.","","",SAPO.Maps.Utils.MessageType.WARNING);this.panel.appendChild(elem);this.div=elem;}else{if(this.categorizedSearch){if(this.pageChanged){SAPO.Maps.Utils.displayMessageHTML(elem,"Lamentamos mas de momento não existem resultados para esta categoria.","","",SAPO.Maps.Utils.MessageType.WARNING);}
else{SAPO.Maps.Utils.displayMessageHTML(elem,"A sua pesquisa por: ",this.query," não devolveu qualquer resultado.",SAPO.Maps.Utils.MessageType.WARNING);}
if(this.openedZone){this.zones[this.openedZone].content.appendChild(elem);}
else{this.panel.appendChild(elem);this.div=elem;}}
else{SAPO.Maps.Utils.displayMessageHTML(elem,"A sua pesquisa por: ",this.query," não devolveu qualquer resultado.",SAPO.Maps.Utils.MessageType.WARNING);this.panel.appendChild(elem);this.div=elem;}}}}
var evtType=this.pageChanged===false?'completed':'pageChanged';var params=this.pageChanged===false?[this,this.pois,this.totalResults]:[this,this.currentPage,this.pois];this.pageChanged=false;try{this.notifyListeners(evtType,params);}
catch(e3){try{this.notifyListeners('error',[this,e3]);}catch(e4){}}
if(this.getNrZones()===1&&this.zones.Localidades){this.zones.Localidades.content.style.height=(this.panel.clientHeight-this.zones.Localidades.content.offsetTop-11)+"px";}}catch(e1){try{this.notifyListeners('error',[this,e1]);}catch(e2){}}},timeout:function(context){if(this.panel){SAPO.Maps.Utils.removeWaitIcon(this.panel);}
if(context.cancel){return;}
this.status=SAPO.Maps.Request.Status.ERROR;if(this.panel){var elem=document.createElement('div');elem.className='search_results_smapi';SAPO.Maps.Utils.displayMessageText(elem,"Lamentamos mas de momento não é possível apresentar os resultados da pesquisa.",SAPO.Maps.Utils.MessageType.WARNING);this.panel.appendChild(elem);}
try{this.notifyListeners('timeout',[this]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}},getPOIHTML:function(poi,marker){return SAPO.Maps.PoiInfoRenderer.getHTML(poi,marker);},displayResults:function(pois){if(!this.panel&&!this.map){return;}
var div=null;var poi=null;var marker=null;var name=null;var category=null;var local=null;var length=pois.length;var style=null;var imgSrc=null;var holder=document.createElement('div');var holderResult=null;var imgContent=null;var img=null;var detailsContent=null;var titleContent=null;var poiLocation=null;var strongContent=null;var dummy=null;var locality=null;if(this.showSearchTitleMessage){var msg=document.createElement("h1");msg.className="search_title_header";msg.innerHTML="Resultados da pesquisa";this.panel.appendChild(msg);this.titleHeader=msg;}
for(var i=length-1;i>=0;--i){poi=pois[i];imgSrc=this.markerImgs+(i+1)+this.markerImgsExtension;if(this.map){style={markerImage:imgSrc};marker=new SAPO.Maps.Marker(new OpenLayers.LonLat(Number(poi.Longitude),Number(poi.Latitude)),null,style);marker.html=this.getPOIHTML(poi,marker);this.markers.addMarker(marker);marker.registerEvent('click',{search:this,index:i},function(marker){this.search.selectResult(this.index,null,false);});marker.registerEvent('popupclosed',{search:this,index:i},function(marker){this.search.unselectResult(this.index);});}
if(this.panel){holderResult=SAPO.Maps.PoiPanelRenderer.getPanelHTML(poi,i+1,true,this.map);holder.insertBefore(holderResult,holder.firstChild);var _this=this;holderResult.idx=i;holderResult.onclick=function(){_this.selectResult(this.idx,null,true);};}}
if(this.panel){holder.className='search_results_smapi';this.panel.appendChild(holder);this.div=holder;}
if(this.map&&this.markers&&!this.whatsHereSearch){var bounds=this.markers.getBounds();if(bounds){var adjustedBounds=new OpenLayers.Bounds(bounds.left-0.02199,bounds.bottom-0.02199,bounds.right+0.02199,bounds.top+0.02199);SAPO.Maps.Utils.AdjustBoundsConsideringBorders(this.map,adjustedBounds,this.borders);}
if(pois.length===1&&pois[0].CategoryId!=='213'){if(pois[0].CategoryId==='214'){SAPO.Maps.Utils.CenterMapConsideringBorders(this.map,new OpenLayers.LonLat(pois[0].Longitude,pois[0].Latitude),this.borders,17);}else{SAPO.Maps.Utils.CenterMapConsideringBorders(this.map,new OpenLayers.LonLat(pois[0].Longitude,pois[0].Latitude),this.borders,18);}}
if(pois.length===1&&pois[0].zoom){SAPO.Maps.Utils.CenterMapConsideringBorders(this.map,new OpenLayers.LonLat(pois[0].Longitude,pois[0].Latitude),this.borders,pois[0].zoom);}}
if(length==1&&this.openDetailsWhenClick){this.selectResult(0,null,true);}
if(this.allowPaging&&this.totalResults>this.resultsPerPage){this.pagingDiv=this.drawPaging();this.panel.appendChild(this.pagingDiv);}},parseZones:function(pois){if(!this.zones){this.zones={};}
for(var i=0;i<pois.length;++i){if(Number(pois[i].totalResults)>0&&pois[i].POIs){if(!this.zones[pois[i].name]){this.zones[pois[i].name]={};}
if(!pois[i].POIs.length){pois[i].POIs=[pois[i].POIs];}
OpenLayers.Util.extend(this.zones[pois[i].name],{pois:pois[i].POIs,totalResults:Number(pois[i].totalResults),nrOfPages:Math.ceil(Number(pois[i].totalResults)/this.resultsPerPage),currentPage:this.pageChanged===pois[i].name?this.zones[pois[i].name].currentPage:1});}
else{this.zones[pois[i].name]={pois:[],totalResults:Number(pois[i].totalResults),nrOfPages:Math.ceil(Number(pois[i].totalResults)/this.resultsPerPage),currentPage:1};}}},displayResultsCategorized:function(){if(!this.panel&&!this.map){return;}
this.cleanPanel();if(OpenLayers.Util.getBrowserName()==='msie'){this.panel.className+=" results_ie";}
var id=null;var holder=document.createElement("div");id=((new Date()).getTime()).toString()+Math.random().toString();holder.id=id;holder.className="category_results";if(this.showSearchTitleMessage){var msg=document.createElement("h1");msg.className="search_title_header";var resultsText=this.getTotalResults()>1?"resultados":"resultado";var categoriesText=this.getNrZones()>1?"categorias":"categoria";msg.innerHTML=this.getTotalResults()+" "+resultsText+" em "+this.getNrZones()+" "+categoriesText;this.panel.appendChild(msg);this.titleHeader=msg;}
var emptyZones=[];var _this=this;var zonePois=null;var poi=null;var zoneHeader=null;var poiHTML=null;var zonePoisWrapper=null;var zoneMarker=null;var zoneMarkers=null;var style=null;var imgSrc=null;for(var e in this.zones){zoneMarkers=[];zonePois=this.zones[e].pois;if(!this.showEmptyZones){if(zonePois.length===0){emptyZones.push(e);continue;}}
if(this.panel){zoneHeader=this.buildZoneHeader(e);zoneHeader.id=id+e+"-header";zoneHeader.onclick=this.zoneClicked.bindObj({search:this,elem:zoneHeader});zoneHeader.zoneName=e;holder.appendChild(zoneHeader);zonePoisWrapper=document.createElement("div");zonePoisWrapper.style.overflow="auto";zonePoisWrapper.className="results_list "+this.getClassNameFromZoneName(e);for(var i=zonePois.length-1;i>=0;--i){poi=zonePois[i];poiHTML=this.getCategorizedPanelHTML(e,poi,i+1,this.map,true);if(zonePois.length===1){if(poiHTML.childNodes[1].className==="item_content"){poiHTML.childNodes[1].style.position="relative";}}
poiHTML.idx=i;poiHTML.zoneName=e;poiHTML.onclick=function(){_this.selectResult(this.idx,this.zoneName,true);};poiHTML.ondblclick=function(e){if(document.selection&&document.selection.empty){document.selection.empty();}else if(window.getSelection){var sel=window.getSelection();sel.removeAllRanges();}
if(!e){e=window.event;}
_this.zoomInResult(this.idx+1);Event.stop(e);};zonePoisWrapper.insertBefore(poiHTML,zonePoisWrapper.firstChild);OpenLayers.Event.observe(poiHTML,"mouseover",function(e){var idx=this.idx;if(idx===null||idx===undefined){var element=(e.originalTarget!==null&&e.originalTarget!==undefined)?e.originalTarget:e.srcElement;while(element.idx===null||element.idx===undefined){element=element.parentNode;}
idx=element.idx;}
if(_this.overedIdx===idx){return;}
_this.highlightResult(idx);},true);OpenLayers.Event.observe(poiHTML,"mouseout",function(e){var idx=this.idx;if(idx===null||idx===undefined){var element=(e.originalTarget!==null&&e.originalTarget!==undefined)?e.originalTarget:e.srcElement;while(element.idx===null||element.idx===undefined){element=element.parentNode;}
idx=element.idx;}
if(_this.overedIdx===idx){return;}
_this.deHighlightResult();},true);}
if(this.zones[e].currentPage===1&&this.zones[e].pois.length<this.resultsPerPage&&this.zones[e].pois.length<this.zones[e].totalResults){var p_wrapper=document.createElement("p");var a_results=document.createElement("a");p_wrapper.className="vermais";a_results.zoneName=e;a_results.innerHTML="Ver mais resultados";a_results.onclick=function(event){if(!event){event=window.event;}
_this.openedZone=this.zoneName;_this.goToPage(1,this.zoneName,true);Event.stop(event);return false;};p_wrapper.appendChild(a_results);zonePoisWrapper.appendChild(p_wrapper);}
zonePoisWrapper.id=id+e+"-content";holder.appendChild(zonePoisWrapper);if(this.allowPaging&&(this.zones[e].currentPage>1||this.zones[e].totalResults>this.resultsPerPage&&this.zones[e].pois.length>=this.resultsPerPage)){this.zones[e].pagingDiv1=this.drawCategorizedPaging(e);zonePoisWrapper.appendChild(this.zones[e].pagingDiv1);this.zones[e].pagingDiv2=this.drawCategorizedPaging(e);zonePoisWrapper.insertBefore(this.zones[e].pagingDiv2,zonePoisWrapper.firstChild);}}
if(this.map){for(var j=zonePois.length-1;j>=0;--j){poi=zonePois[j];imgSrc=this.markerImgs+(j+1)+this.markerImgsExtension;style={markerImage:imgSrc};zoneMarker=new SAPO.Maps.Marker(new OpenLayers.LonLat(Number(poi.Longitude),Number(poi.Latitude)),null,style);zoneMarker.idx=j;zoneMarker.html=this.getPOIHTML(poi,zoneMarker);zoneMarker.registerEvent('click',{search:this,index:j,zoneName:e},function(marker){this.search.selectResult(this.index,this.zoneName,false);});zoneMarker.registerEvent('popupclosed',{search:this,index:j,zoneName:e},function(marker){this.search.unselectResult(this.index);});zoneMarker.registerEvent('mouseover',this,function(marker){this.highlightResult(marker.idx);});zoneMarker.registerEvent('mouseout',this,function(marker){this.deHighlightResult();});zoneMarkers.push(zoneMarker);}}
this.zones[e].header=zoneHeader;this.zones[e].content=zonePoisWrapper;this.zones[e].markers=zoneMarkers;zonePoisWrapper.style.display="none";}
if(!this.showEmptyZones){if(emptyZones.length>0){var div_showAll=document.createElement("div");var anchorShowAllCats=document.createElement("a");anchorShowAllCats.innerHTML="Ver todas as categorias";anchorShowAllCats.onclick=this.showAllZones.bindObj(this);div_showAll.appendChild(anchorShowAllCats);holder.appendChild(div_showAll);div_showAll.className="newsubmitbtn";}}
if(this.panel){this.panel.appendChild(holder);this.div=holder;}},buildZoneHeader:function(zoneName){var _this=this;var div_zone=document.createElement("div");var div_button=document.createElement("div");var h_name=document.createElement("h2");var h_nrResults=document.createElement("h3");div_zone.className="zone_header "+this.getClassNameFromZoneName(zoneName);div_button.className="slideDownbtn";h_name.innerHTML=zoneName;h_nrResults.innerHTML=this.zones[zoneName].totalResults.toString();div_zone.appendChild(h_name);div_zone.appendChild(h_nrResults);h_nrResults.appendChild(div_button);div_button.innerHTML="&nbsp;";return div_zone;},zoneClicked:function(){var zoneName=this.elem.zoneName;if(zoneName===this.search.openedZone){this.search.closeZone();}
else{this.search.openZone(zoneName);}},getClassNameFromZoneName:function(zoneName){var className=null;switch(zoneName){case"Localidades":case"Ruas":className="local";break;case"Fotos":className="fotos";break;case"Vídeos":className="videos";break;case"Compras":className="compras";break;case"Cultura":className="cultura";break;case"Desportos":className="desportos";break;case"Ensino":className="ensino";break;case"Hotéis e alojamentos":className="hoteis";break;case"Restaurantes":className="restaurantes";break;case"Saúde":className="saude";break;case"Segurança":className="seguranca";break;case"Transportes":className="transportes";break;case"Turismo e viagens":className="turismo";break;case"Utilidades":className="utilidades";break;case"Imóveis":className="realstate";break;default:className="local";break;}
return className;},drawPaging:function(){var _this=this;var pagingElement=document.createElement('div');var resultsInfo=document.createElement('div');var pages=document.createElement('div');pagingElement.className='smaps_api_search_paging';resultsInfo.className='smaps_api_search_paging_resultsInfo';pages.className='smaps_api_search_paging_pages';var totalResults=null;var currentPage=null;totalResults=this.totalResults;currentPage=this.currentPage;var numPages=Math.ceil(totalResults/this.resultsPerPage);var startPage=currentPage-Math.floor(this.numberOfPagesShown/2);var endPage=currentPage+Math.floor(this.numberOfPagesShown/2);if(endPage>numPages){endPage=numPages;}
if(startPage<1){startPage=1;}
if((endPage-startPage+1)<this.numberOfPagesShown&&numPages>=this.numberOfPagesShown){if(startPage<=Math.floor(this.numberOfPagesShown/2)){endPage+=this.numberOfPagesShown-endPage;}else if(endPage>=numPages-Math.floor(this.numberOfPagesShown/2)){startPage-=this.numberOfPagesShown-(endPage-startPage+1);}}
var pageNumber=false;if(currentPage!==1){var preview=document.createElement('a');preview.className='previous';preview.onclick=function(){_this.goToPage(currentPage-1,zoneName);return false;};pages.appendChild(preview);}
for(var i=startPage;i<=endPage;++i){pageNumber=document.createElement('a');pageNumber.innerHTML=i;pageNumber.page=i;pageNumber.onclick=function(){_this.goToPage(this.page);return false;};if(i===currentPage){pageNumber.className='smaps_api_search_paging_pageSelected';}
pages.appendChild(pageNumber);}
if(currentPage!==numPages){var next=document.createElement('a');next.className='next';next.onclick=function(){_this.goToPage(currentPage+1);return false;};pages.appendChild(next);}
resultsInfo.appendChild(document.createTextNode(totalResults+' resultados'));pagingElement.appendChild(resultsInfo);pagingElement.appendChild(pages);return pagingElement;},drawCategorizedPaging:function(zoneName){var _this=this;var div_paging=document.createElement('div');var span_previous=document.createElement('span');var span_pages=document.createElement('span');var span_next=document.createElement('span');div_paging.className="pagination";span_previous.className="prev";span_next.className="next";span_previous.innerHTML="&nbsp;";span_next.innerHTML="&nbsp;";var totalResults=null;var currentPage=null;totalResults=this.zones[zoneName].totalResults;currentPage=this.zones[zoneName].currentPage;var numPages=Math.ceil(totalResults/this.resultsPerPage);var startPage=currentPage-Math.floor(this.numberOfPagesShown/2);var endPage=currentPage+Math.floor(this.numberOfPagesShown/2);if(endPage>numPages){endPage=numPages;}
if(startPage<1){startPage=1;}
if((endPage-startPage+1)<this.numberOfPagesShown&&numPages>=this.numberOfPagesShown){if(startPage<=Math.floor(this.numberOfPagesShown/2)){endPage+=this.numberOfPagesShown-endPage;}else if(endPage>=numPages-Math.floor(this.numberOfPagesShown/2)){startPage-=this.numberOfPagesShown-(endPage-startPage+1);}}
var pageNumber=false;if(currentPage!==1){span_previous.onclick=function(){_this.goToPage(currentPage-1,zoneName);return false;};div_paging.appendChild(span_previous);}
for(var i=startPage;i<=endPage;++i){pageNumber=document.createElement('a');pageNumber.innerHTML=i;pageNumber.page=i;pageNumber.onclick=function(){_this.goToPage(this.page,zoneName);return false;};if(i===currentPage){pageNumber.className='current';}
span_pages.appendChild(pageNumber);}
div_paging.appendChild(span_pages);if(currentPage!==numPages){span_next.onclick=function(){_this.goToPage(currentPage+1,zoneName);return false;};div_paging.appendChild(span_next);}
return div_paging;},getCategorizedPanelHTML:function(zoneName,poi,number,showImg,displayDashboard){var div_item=document.createElement("div");var div_marker=document.createElement("div");var div_content=document.createElement("div");var div_cleaner=document.createElement("div");div_item.className="item";div_marker.className="marker";div_content.className="item_content";div_cleaner.className="floater_cleaner";var img_marker=document.createElement("img");var a_magnifier=document.createElement("a");img_marker.width=22;img_marker.height=28;img_marker.alt="Mini Marker";img_marker.src="http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Markers/new/m"+number+".png";a_magnifier.className="lupa";a_magnifier.href="#";div_marker.appendChild(img_marker);div_marker.appendChild(a_magnifier);a_magnifier.onclick=function(e){this.zoomInResult(number);}.bindObj(this);switch(zoneName){case"Localidades":case"Ruas":this.getCategorizedLocalityPanelHTML(poi,div_content);break;default:this.getCategorizedCommonPanelHTML(poi,div_content);break;}
var div_dashboardWrapper=document.createElement("div");div_dashboardWrapper.style.display="none";var div_tabsContentWrapper=document.createElement("div");div_tabsContentWrapper.className="shortlist_info";var div_weather=null;var ul_tabsHeader=null;var ul_tabNews=null;var ul_tabTraffic=null;var div_tabPhotos=null;var div_tabVideos=null;if(displayDashboard){if(!this.dashboard){this.dashboard={};}
this.dashboard[poi.POIId]={};this.dashboard[poi.POIId].html=div_dashboardWrapper;if(poi.Dashboard&&poi.Dashboard.Weather){div_weather=this.buildDashboardWeather(poi,div_weather);}
var tabs=[];if(poi.Dashboard){for(var e in poi.Dashboard){if(e==="Weather"){continue;}
if(e==="Videos"){continue;}
if(poi.Dashboard[e]){this.dashboard[poi.POIId][poi.Dashboard[e].Name]={};tabs.push(poi.Dashboard[e].Name);}}
ul_tabsHeader=this.buildDashboardTabs(tabs,poi);if(poi.Dashboard.News){ul_tabNews=this.buildDashboardNews(poi.Dashboard.News.Item);if(ul_tabNews){ul_tabNews.style.display="none";this.dashboard[poi.POIId]["Notícias"].content=ul_tabNews;div_tabsContentWrapper.appendChild(ul_tabNews);}}
if(poi.Dashboard.Traffic){ul_tabTraffic=this.buildDashboardTraffic(poi.Dashboard.Traffic.Item);if(ul_tabTraffic){ul_tabTraffic.style.display="none";this.dashboard[poi.POIId]["Trânsito"].content=ul_tabTraffic;div_tabsContentWrapper.appendChild(ul_tabTraffic);}}
if(poi.Dashboard.Photos){div_tabPhotos=this.buildDashboardPhotos(poi.Dashboard.Photos.Item);if(div_tabPhotos){div_tabPhotos.style.display="none";this.dashboard[poi.POIId].Fotos.content=div_tabPhotos;div_tabsContentWrapper.appendChild(div_tabPhotos);}}}}
div_item.appendChild(div_marker);div_item.appendChild(div_content);div_item.appendChild(document.createElement('div'));if(div_weather){div_dashboardWrapper.appendChild(div_weather);}
div_dashboardWrapper.appendChild(div_cleaner);if(ul_tabsHeader){div_dashboardWrapper.appendChild(ul_tabsHeader);div_dashboardWrapper.appendChild(div_tabsContentWrapper);}
div_item.appendChild(div_dashboardWrapper);div_item.appendChild(div_cleaner.cloneNode(true));return div_item;},getCategorizedLocalityPanelHTML:function(poi,holder){var div_metadata=document.createElement("div");var div_description=document.createElement("div");div_metadata.className="metadata";if(SAPO.Maps.Utils.checkIE6()){div_metadata.className+=" metadata_ie6";}
div_description.className="item_description";div_metadata.innerHTML=poi.Name;if(poi.Municipality&&poi.District){div_metadata.innerHTML+="<br/><span>Concelho de "+poi.Municipality+"</span><span>Distrito de "+poi.District+"</span>";div_description.innerHTML="";}
holder.appendChild(div_metadata);holder.appendChild(div_description);},getCategorizedCommonPanelHTML:function(poi,holder){var div_metadata=document.createElement("div");var div_description=document.createElement("div");div_metadata.className="metadata";if(SAPO.Maps.Utils.checkIE6()){div_metadata.className+=" metadata_ie6";}
div_description.className="item_description";div_metadata.innerHTML=poi.Name+"<br/>";var h_category=document.createElement("h5");h_category.className="search_panel_category_name";h_category.innerHTML="("+poi.Category+")";div_metadata.appendChild(h_category);var span_metadata=document.createElement("span");var span_address=document.createElement("span");span_address.className="address_line1";var span_address2=document.createElement("span");span_address.className="address_line2";var span_site=document.createElement("span");span_site.className="address_line2";span_site.className="site";var a_phone=document.createElement("a");a_phone.href="#";a_phone.className="phone";if(poi.Street&&poi.Street.length>0){span_address.innerHTML+=poi.Street;}
if(poi.ZipCode&&poi.ZipCode.length>0&&poi.ZipCode!=="0"){var zc=poi.ZipCode;if(poi.ZipCode.length>4){zc=(poi.ZipCode.substring(0,4)+"-"+poi.ZipCode.substring(4));}
span_address2.innerHTML+=zc;}
if(poi.Locality&&poi.Locality.length>0){if(span_address2.innerHTML!==""){span_address2.innerHTML+=", ";}
span_address2.innerHTML+=poi.Locality;}else{if(poi.Parish&&poi.Parish.length>0){if(span_address2.innerHTML!==""){span_address2.innerHTML+=", ";}
span_address2.innerHTML+=poi.Parish;}}
if(poi.Municipality&&poi.Municipality.length>0){if(poi.Locality!==poi.Municipality&&poi.Parish!==poi.Municipality){if(span_address2.innerHTML!==""){span_address2.innerHTML+=", ";}
span_address2.innerHTML+=poi.Municipality;}}
if(poi.District&&poi.District.length>0&&poi.Municipality!==poi.District){if(span_address2.innerHTML!==""){span_address2.innerHTML+=", ";}
span_address2.innerHTML+=poi.District;}
if(poi.Phone&&poi.Phone.length>0){a_phone.innerHTML+=poi.Phone;}
if(poi.URL&&poi.URL.length>0){var site=document.createElement('a');site.href=poi.URL;site.target='blank';site.appendChild(document.createTextNode('Site'));span_site.appendChild(site);}
span_metadata.appendChild(span_address);span_metadata.appendChild(span_address2);if(span_site.innerHTML!==""){span_metadata.appendChild(span_site);}
if(a_phone.innerHTML!==""){span_metadata.appendChild(a_phone);}
div_metadata.appendChild(span_metadata);if(poi.Description){div_description.innerHTML=poi.Description.length>125?poi.Description.substr(0,125)+"[...]":poi.Description;}
if(poi.DetailXml&&poi.DetailXml.Details&&poi.DetailXml.Details.Pictures&&poi.DetailXml.Details.Pictures.Picture){var image=null;var images=poi.DetailXml.Details.Pictures.Picture.length?poi.DetailXml.Details.Pictures.Picture:[poi.DetailXml.Details.Pictures.Picture];if(!(images instanceof Array)){images=[images];}
for(var i=0;i<images.length;++i){if(images[i]&&images[i].primary==="true"){image=images[i];break;}}
if(!image){image=images[0]!==null?images[0]:'';}
var div_img=document.createElement("div");div_img.className="search_panel_img_wrapper";div_img.style.width="0px";div_img.style.height="0px";div_img.style.overflow="hidden";var img=document.createElement("img");img.width=88;img.height=66;OpenLayers.Event.observe(img,'load',function(){div_img.style.width="88px";div_img.style.height="66px";});var src=image.value?image.value:image;if(window.location.protocol.indexOf('https')!==-1){src=src.replace(/http:\/\/map/,'https://imgs');if(src.indexOf('https://')===-1){src='';}}
img.src=src;div_img.appendChild(img);holder.appendChild(div_img);}
holder.appendChild(div_metadata);holder.appendChild(div_description);},buildDashboardWeather:function(poi){var weatherInfo=poi.Dashboard.Weather;var forecastInfo=weatherInfo.DetailXml.Details.WeatherForecast.Days.Day;var div_weather=document.createElement("div");div_weather.className="extrainfo meteo";var div_day=null;var img_image=null;var p_temperaturesWrapper=null;var span_day=null;var span_maxTemp=null;var span_minTemp=null;for(var i=0;i<3;++i){div_day=document.createElement("div");img_image=document.createElement("img");p_temperaturesWrapper=document.createElement("p");span_day=document.createElement("span");span_maxTemp=document.createElement("span");span_minTemp=document.createElement("span");div_day.className="weather_dayWrapper";if(i===2){div_day.className+=" last";}
img_image.className="weather_dayImage";span_day.className="weather_dayDay";span_maxTemp.className="weather_maxTemperature";span_minTemp.className="weather_minTemperature";img_image.width=60;img_image.height=53;img_image.src="http://js.sapo.pt/Assets/Images/Meteo/"+forecastInfo[i].WeatherCode+".png";if(i===0){span_day.innerHTML="Hoje";}
else{if(i===1){span_day.innerHTML="Amanh&atilde;";}
else{span_day.innerHTML=forecastInfo[i].Name.replace(/\*/,"&ordf;");}}
span_maxTemp.innerHTML=forecastInfo[i].High+"&ordm;";span_minTemp.innerHTML=forecastInfo[i].Low+"&ordm;";p_temperaturesWrapper.appendChild(span_day);p_temperaturesWrapper.appendChild(span_minTemp);p_temperaturesWrapper.appendChild(span_maxTemp);div_day.appendChild(img_image);div_day.appendChild(p_temperaturesWrapper);div_weather.appendChild(div_day);}
return div_weather;},buildDashboardTabs:function(tabs,poi){if(tabs.length===0){return null;}
var _this=this;var ul_tabsSystem=document.createElement("ul");ul_tabsSystem.className="smapi_tabsys";var li_tab=null;var span_tabName=null;for(var i=0;i<tabs.length;++i){li_tab=document.createElement("li");this.dashboard[poi.POIId][tabs[i]].tab=li_tab;span_tabName=document.createElement("span");span_tabName.innerHTML=tabs[i];li_tab.tabName=tabs[i];span_tabName.tabName=tabs[i];li_tab.onclick=function(e){if(!e){e=window.event;}
_this.openDashboardTab(this.tabName);OpenLayers.Event.stop(e);};li_tab.appendChild(span_tabName);ul_tabsSystem.appendChild(li_tab);}
return ul_tabsSystem;},buildDashboardNews:function(news){if(!news.length){news=[news];}
var ul_newsWrapper=document.createElement("ul");ul_newsWrapper.className="news_ul_list";var li_news=null;var a_news=null;var length=news.length>=4?4:news.length;for(var i=0;i<length;++i){li_news=document.createElement("li");a_news=document.createElement("a");a_news.className="news_a_link";a_news.innerHTML=news[i].Name;li_news.appendChild(a_news);ul_newsWrapper.appendChild(li_news);var _this=this;if(this.map){li_news.poi=news[i];li_news.onclick=function(e){if(!e){e=window.event;}
_this.markers.getMarkers()[0].closePopup();_this.removeDashboardMarker();var poi=this.poi;_this.dashboardMarker=new SAPO.Maps.Marker(new OpenLayers.LonLat(Number(poi.Longitude),Number(poi.Latitude)),{popupAnchor:new OpenLayers.Pixel(0,-11)},{markerImage:"http://imgs.sapo.pt/fotos_gis/News/icon.png",size:new OpenLayers.Size(22,23),markerAnchor:new OpenLayers.Pixel(-11,-11)});_this.dashboardMarker.registerEvent("popupclosed",_this,_this.removeDashboardMarker);_this.map.addOverlay(_this.dashboardMarker);_this.dashboardMarker.openPopup(_this.getPopupForNews(poi),{borders:_this.borders});OpenLayers.Event.stop(e);};}}
return ul_newsWrapper;},getPopupForNews:function(poi){var div_wraper=document.createElement("div");var div_header=document.createElement("div");var div_content=document.createElement("div");var div_newsBody=document.createElement("div");var p_newsBodyContent=document.createElement("p");div_header.className="pop_header news_div_header";div_content.className="pop_content news_div_content";div_wraper.className="news_div_wraper";div_newsBody.className="pop_content news_div_newsBody";p_newsBodyContent.className="news_p_newsBodyContent";var div_links=document.createElement("div");var a_link=document.createElement("a");a_link.className="news_a";a_link.innerHTML="[Ver not&iacute;cia completa]";a_link.target="_blank";a_link.href=poi.URL;var p_locality=document.createElement("p");var p_date=document.createElement("p");var p_hour=document.createElement("p");p_locality.className="news_locality";p_date.className="news_date";p_hour.className="news_hour";p_date.innerHTML=poi.PublicationDate.substr(0,10);p_hour.innerHTML=poi.PublicationDate.substr(11,5);div_header.innerHTML="";div_header.appendChild(p_locality);div_header.appendChild(p_date);div_header.appendChild(p_hour);div_links.appendChild(a_link);div_header.appendChild(div_links);p_newsBodyContent.innerHTML="<strong>"+poi.Name+": </strong>"+poi.Description;div_wraper.style.marginLeft="0px";div_content.style.display="none";div_newsBody.style.display="block";if(div_newsBody.clientHeight>350){div_newsBody.style.height="350px";div_newsBody.style.overflow="auto";}
div_newsBody.appendChild(p_newsBodyContent);div_wraper.appendChild(div_header);div_wraper.appendChild(div_content);div_wraper.appendChild(div_newsBody);return div_wraper;},buildDashboardTraffic:function(traffic){if(!traffic.length){traffic=[traffic];}
var ul_trafficWrapper=document.createElement("ul");ul_trafficWrapper.className="traffic_ul_list";var li_item=null;var img_image=null;var span_description=null;var length=traffic.length>=3?3:traffic.length;for(var i=0;i<length;++i){li_item=document.createElement("li");img_image=document.createElement("img");span_description=document.createElement("span");img_image.width=15;img_image.height=18;switch(Number(traffic[i].DetailXml.Details.Traffic.Category)){case 1:img_image.src="http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Search/categorized/traffic/traffic1.gif";break;case 2:case 3:img_image.src="http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Search/categorized/traffic/traffic2.gif";break;case 4:case 5:img_image.src="http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Search/categorized/traffic/traffic3.gif";break;default:continue;}
span_description.innerHTML="<a>"+SAPO.Maps.Utils.htmlEntityDecode(traffic[i].Description)+"</a>";li_item.appendChild(img_image);li_item.appendChild(span_description);ul_trafficWrapper.appendChild(li_item);var _this=this;if(this.map){li_item.poi=traffic[i];li_item.onclick=function(e){if(!e){e=window.event;}
_this.markers.getMarkers()[0].closePopup();_this.removeDashboardMarker();var poi=this.poi;var image;switch(Number(poi.DetailXml.Details.Traffic.Category)){case 1:image="http://imgs.sapo.pt/fotos_gis/Traffic/light.png";break;case 2:case 3:image="http://imgs.sapo.pt/fotos_gis/Traffic/medium.png";break;case 4:case 5:image="http://imgs.sapo.pt/fotos_gis/Traffic/intense.png";break;}
_this.dashboardMarker=new SAPO.Maps.Marker(new OpenLayers.LonLat(Number(poi.Longitude),Number(poi.Latitude)),{popupAnchor:new OpenLayers.Pixel(0,-31)},{markerImage:image,size:new OpenLayers.Size(17,31),markerAnchor:new OpenLayers.Pixel(-8,-31)});_this.dashboardMarker.registerEvent("popupclosed",_this,_this.removeDashboardMarker);_this.map.addOverlay(_this.dashboardMarker);_this.dashboardMarker.openPopup(_this.getPopupForTraffic(poi),{borders:_this.borders});OpenLayers.Event.stop(e);};}}
return ul_trafficWrapper;},getPopupForTraffic:function(poi){var date=new Date(poi.POISourceId.substring(poi.POISourceId.indexOf(" ")+1,poi.POISourceId.length).replace(/ /g,"T"));return"<p><strong>"+poi.Name+"</strong></p><p><em>&Uacute;ltima actualiza&ccedil&atilde;o: "+SAPO.Maps.Utils.getDefaultDateView(date)+" - "+SAPO.Maps.Utils.getDefaultTimeView(date)+"</em></p><br/><p style=\"width: 320px;\">"+poi.Description+"</p>";},buildDashboardPhotos:function(photos){if(!photos.length){photos=[photos];}
var div_photosWrapper=document.createElement("div");div_photosWrapper.className="fotoslist";var div_image=null;var img_image=null;var length=photos.length>=4?4:photos.length;for(var i=0;i<length;++i){if(!photos[i].DetailXml||!photos[i].DetailXml.Details||!photos[i].DetailXml.Details.Photo||!photos[i].DetailXml.Details.Photo.DirectUrl){continue;}
div_image=document.createElement("div");img_image=document.createElement("img");img_image.width=88;img_image.height=66;img_image.src=photos[i].DetailXml.Details.Photo.DirectUrl;div_image.appendChild(img_image);div_photosWrapper.appendChild(div_image);var _this=this;if(this.map){div_image.poi=photos[i];div_image.onclick=function(e){if(!e){e=window.event;}
_this.markers.getMarkers()[0].closePopup();_this.removeDashboardMarker();var poi=this.poi;_this.dashboardMarker=new SAPO.Maps.Marker(new OpenLayers.LonLat(Number(poi.Longitude),Number(poi.Latitude)),{popupAnchor:new OpenLayers.Pixel(0,-11)},{markerImage:"http://imgs.sapo.pt/fotos_gis/Photos/icon.png",size:new OpenLayers.Size(22,23),markerAnchor:new OpenLayers.Pixel(-11,-11)});_this.dashboardMarker.registerEvent("popupclosed",_this,_this.removeDashboardMarker);_this.dashboardMarker.poi=poi;_this.map.addOverlay(_this.dashboardMarker);_this.dashboardMarker.openPopup(_this.getPopupForPhotos(_this.dashboardMarker),{borders:_this.borders});OpenLayers.Event.stop(e);};}}
return div_photosWrapper;},getPopupForPhotos:function(marker){var isLoaded=false;var toShow=true;var poi=marker.poi;var div_wrapper=document.createElement("div");var div_loader=document.createElement("div");var div_imgWrapper=document.createElement("div");var div_imgArea=document.createElement("div");var img_loader=document.createElement("img");var img_image=document.createElement("img");var h1_title=document.createElement("h1");var p_description=document.createElement("p");var div_link=document.createElement("div");var a_link=document.createElement("a");div_wrapper.className="SapoPhotos";div_loader.className="Loader";div_imgArea.className="ImageArea";div_imgWrapper.className="ImageWrapper";h1_title.className="Title";p_description.className="Description";div_link.className="Link";img_image.onload=function(){if(!toShow){return;}
isLoaded=true;div_loader.style.display="none";div_imgArea.style.display="block";var width=this.naturalWidth?this.naturalWidth:this.width;var height=this.naturalHeight?this.naturalHeight:this.height;var adjustedWidth=width,adjustedHeight=height;if(width>400||height>400){if(height>width){adjustedHeight=400;adjustedWidth=Math.round((adjustedHeight*width)/height);}
if(width>height){adjustedWidth=400;adjustedHeight=Math.round((adjustedWidth*height)/width);}}
this.width=adjustedWidth;this.height=adjustedHeight;p_description.style.width=this.width>300?(this.width+"px"):"300px";if(marker.popup){marker.popup.contentUpdated();}};img_loader.width="111";img_loader.height="82";img_loader.src="http://imgs.sapo.pt/fotos_gis/site/bigwheel.gif";img_image.src=poi.DetailXml.Details.Photo.DirectUrl;h1_title.innerHTML=poi.Name;a_link.href=poi.URL;a_link.target="_blank";a_link.innerHTML="Veja esta fotografia no SAPO fotos";div_loader.appendChild(img_loader);div_imgArea.appendChild(h1_title);div_imgWrapper.appendChild(img_image);div_imgArea.appendChild(div_imgWrapper);if(poi.Description){p_description.innerHTML=poi.Description;div_imgArea.appendChild(p_description);}
div_link.appendChild(a_link);div_imgArea.appendChild(div_link);div_wrapper.appendChild(div_loader);div_wrapper.appendChild(div_imgArea);window.setTimeout(function(){if(!isLoaded){div_imgArea.style.display="none";toShow=false;div_loader.innerHTML="";div_loader.style.width="300px";div_loader.style.height="auto";SAPO.Maps.Utils.displayMessageHTML(div_loader,"Lamentamos mas de momento não é possível apresentar a fotografia.","","",SAPO.Maps.Utils.MessageType.WARNING);if(marker.popup){marker.popup.contentUpdated();}}},3000);return div_wrapper;},buildDashboardVideos:function(videos){if(!videos.length){videos=[videos];}
var div_videosWrapper=document.createElement("div");div_videosWrapper.className="fotoslist";var div_video=null;var img_video=null;var a_link=null;var length=videos.length>=4?4:videos.length;for(var i=0;i<length;++i){div_video=document.createElement("div");a_link=document.createElement("a");img_video=document.createElement("img");img_video.width=88;img_video.height=66;img_video.src=videos[i].DetailXml.Details.Video.Picture;a_link.target="_blank";a_link.href=videos[i].DetailXml.Details.Video.DirectUrl.replace(/(https?:\/\/[\w\d\.]+(?::\d+)?\/[^\/]+?)\/mov\/.*/,"$1");a_link.appendChild(img_video);div_video.appendChild(a_link);div_videosWrapper.appendChild(div_video);}
return div_videosWrapper;},registerEvent:function(eventType,context,func){if(!this.listeners[eventType]){this.listeners[eventType]=[];}
var obj={func:func,context:context};this.listeners[eventType].push(obj);},unRegisterEvent:function(eventType,context,func){var evts=this.listeners[eventType]?this.listeners[eventType]:[];for(var i=0;i<evts.length;++i){if(context==evts[i].context&&func==evts[i].func){evts.splice(i,1);return true;}}
return false;},notifyListeners:function(eventType,args){var evts=this.listeners[eventType]?this.listeners[eventType]:[];args=args?args:[];var func,context;for(var i=0;i<evts.length;++i){func=evts[i].func;context=evts[i].context;func.apply(context,args);}},EVENT_TYPES:['beforeSearch','completed','timeout','selected','beforeSelected','selectedOnMap','selectedOnPanel','unselected','cleanResults','canceled','pageChanged','zoneOpened','zoneClosed','error'],CLASS_NAME:'SAPO.Maps.Search'});SAPO.Maps.Geocoder=OpenLayers.Class({requester:null,url:'http://services.sapo.pt/Maps/SearchJSON',categorizedUrl:'http://services.sapo.pt/Maps/SearchJSON',whatsHereUrl:'http://services.sapo.pt/Maps/GetWhatsHereJSON',initialize:function(){this.requester=SAPO.Maps.Request.prototype.getRequester();},getLocations:function(query,onCompleteCallback,onErrorCallback,opts){var options=OpenLayers.Util.extend({bbox:null,resultsPerPage:10,pageNumber:1,context:null,searchForPOIS:false,searchForStreetsAndLocations:false},opts);var url=this.url+'?version=1.0&q='+encodeURIComponent(query);url+='&recordsPerPage='+options.resultsPerPage+'&pageNumber='+options.pageNumber;if(options.bbox){var bbox=opts.bbox.toArray();url+="&xMin="+bbox[0]+"&yMin="+bbox[1]+"&xMax="+bbox[2]+"&yMax="+bbox[3];}
if(options.searchForPOIS){url+='&f=allpois';}
if(options.searchForStreetsAndLocations){url+="&lf=LocalidadesOuRuas";}
function timeout(){try{onErrorCallback.apply(this,[options.context]);}catch(e3){}}
this.requester.request(url,{timeout:4,onComplete:this.processRequest.bindObj(this),onTimeout:timeout.bindObj(this),optOnComplete:{onComplete:onCompleteCallback,onTimeout:onErrorCallback,options:options}});},getLocationsCategorized:function(query,onCompleteCallback,onErrorCallback,opts){var options=OpenLayers.Util.extend({bbox:null,resultsPerPage:10,pageNumber:1,context:null,searchForPOIS:false,searchForStreetsAndLocations:false,dashboard:true},opts);var url=this.categorizedUrl+'?version=2.0&isRecordsPerPagePerResultType=true&q='+encodeURIComponent(query);url+='&recordsPerPage='+options.resultsPerPage+'&pageNumber='+options.pageNumber;if(options.bbox){var bbox=opts.bbox.toArray();url+="&xMin="+bbox[0]+"&yMin="+bbox[1]+"&xMax="+bbox[2]+"&yMax="+bbox[3];}
if(options.category){url+="&lf="+encodeURIComponent(options.category);}
if(options.dashboard){url+="&dashboard=true";}
if(options.searchForPOIS){url+='&f=allpois';}
if(options.searchForStreetsAndLocations){url+="&lf=LocalidadesOuRuas";}
function timeout(){try{onErrorCallback.apply(this,[options.context]);}catch(e3){}}
this.requester.request(url,{timeout:4,onComplete:this.processRequestCategorized.bindObj(this),onTimeout:timeout.bindObj(this),optOnComplete:{onComplete:onCompleteCallback,onTimeout:onErrorCallback,options:options}});},findWhatsHere:function(lonlat,zoom,onCompleteCallback,onErrorCallback,opts){var options=OpenLayers.Util.extend({context:null},opts);var url=this.whatsHereUrl+'?zoomlevel='+zoom+'&latitude='+lonlat.lat+'&longitude='+lonlat.lon;function timeoutOrError(){try{onErrorCallback.apply(this,[options.context]);}catch(e3){}}
this.requester.request(url,{timeout:4,onComplete:this.processRequestWhatsHere.bindObj(this),onTimeout:timeoutOrError,onError:timeoutOrError,optOnComplete:{onComplete:onCompleteCallback,onTimeout:onErrorCallback,options:options}});},processRequestWhatsHere:function(obj,args){var pois=[];try{pois=obj.GetWhatsHereResponse.GetWhatsHereResult['a:POI'];}
catch(e1){if(args.onComplete){this.notifyCallbacks(args.onComplete,this,[pois,args.options.context,pois.length]);}
return;}
if(!pois){pois=[];}
else{if(!pois.length){pois=[pois];}}
var poisArrAux=[];var poiAux=false;for(var i=0;i<pois.length;++i){poiAux=new SAPO.Maps.Poi();poiAux.loadPOI('a',pois[i]);poisArrAux.push(poiAux);}
if(args.onComplete){this.notifyCallbacks(args.onComplete,this,[poisArrAux,args.options.context,poisArrAux.length]);}},processRequest:function(obj,args){var pois=[],totalResults=0;try{pois=obj.SearchResponse.SearchResult.POI;totalResults=Number(obj.SearchResponse.SearchResult.totalResults);}
catch(e1){if(args.onComplete){this.notifyCallbacks(args.onComplete,this,[pois,args.options.context,totalResults]);}
return;}
if(!pois){pois=[];}
else{if(!pois.length){pois=[pois];}}
if(args.onComplete){this.notifyCallbacks(args.onComplete,this,[pois,args.options.context,totalResults]);}},processRequestCategorized:function(obj,args){var pois=[],totalResults=0;try{pois=obj.SearchResponse.SearchResult.Category;if(!pois.length){pois=[pois];}
totalResults=Number(obj.SearchResponse.SearchResult.totalResults);}
catch(e1){pois=[];if(args.onComplete){this.notifyCallbacks(args.onComplete,this,[pois,args.options.context,totalResults]);}
return;}
if(!pois){pois=[];}
if(args.onComplete){this.notifyCallbacks(args.onComplete,this,[pois,args.options.context,totalResults]);}},notifyCallbacks:function(callback,context,params){if(!callback){return;}
try{callback.apply(context,params);}catch(e){}},CLASS_NAME:'SAPO.Maps.Geocoder'});SAPO.Maps.Directions=OpenLayers.Class({panel:null,map:null,language:null,mode:null,route:null,events:null,syndicationObj:null,status:SAPO.Maps.Request.Status.STOP,request:null,currentStepIdx:0,popup:null,borders:null,polylines:null,displayStartEndMarkers:false,startEndMarkers:null,displayMiddlePointsMarkers:false,middlePoints:null,mousemoveListener:null,mouseupListener:null,keydownListener:null,editableRoute:false,tooltip:null,mapDivOffset:null,imagesURL:{start:"http://js.sapo.pt/Assets/Maps/Images/bandeira_verde.gif",end:"http://js.sapo.pt/Assets/Maps/Images/bandeira_vermelha.gif",left:"http://js.sapo.pt/Assets/Maps/Images/esquerda.gif",right:"http://js.sapo.pt/Assets/Maps/Images/direita.gif",front:"http://js.sapo.pt/Assets/Maps/Images/frente.gif"},initialize:function(map,panel,options){this.events={};this.syndicationObj=new SAPO.Communication.Syndication();this.map=map;if(panel){this.panel=typeof(panel)=='string'?document.getElementById(panel):panel;}
OpenLayers.Util.extend(this,options);if(!this.language){this.language="pt";}
this.mousemoveListener=this.mousemove.bindObj(this);this.mouseupListener=this.mouseup.bindObj(this);this.keydownListener=this.keydown.bindObj(this);},getDirections:function(start,end,options){if(this.status==SAPO.Maps.Request.Status.REQUESTING){throw'SAPO.Maps.Directions: cannot query the server while the last request is waiting';}
if(!options){options={};}
options=OpenLayers.Util.extend({description:'text',adjustBounds:true},options);if(options.mode){this.mode=options.mode;}
else{if(!this.mode){this.mode='fastest';}}
var modesMapping={fastest:'rapido',shortest:'curto',walk:'apeado'};if(!(this.mode in modesMapping)){throw'Unsuported parameter: '+options.mode;}
var mode=modesMapping[this.mode];var requestURL="http://services.sapo.pt/Maps/GetRoute/JSON?mode="+mode
+'&pts='+start.lon+','+start.lat;if(options.middlePoints){var point=null;for(var i=0;i<options.middlePoints.length;++i){point=options.middlePoints[i];requestURL+=','+point.lon+','+point.lat;}}
requestURL+=','+end.lon+','+end.lat;this.route=null;this.request={cancel:false};var reqID=this.syndicationObj.push(requestURL,{timeout:10,onComplete:this.onComplete.bindObj(this),onTimeout:this.onError.bindObj(this),optOnComplete:{status:this.request,description:options.description,mode:mode,showMapCheckbox:options.showMapCheckbox,adjustBounds:options.adjustBounds}});this.status=SAPO.Maps.Request.Status.REQUESTING;this.syndicationObj.run(reqID);try{this.notifyListeners('loading',[]);}catch(e){}
if(this.panel){SAPO.Maps.Utils.displayWaitIcon(this.panel);}
return true;},onComplete:function(obj,args){if(this.status!=SAPO.Maps.Request.Status.REQUESTING||args.status.cancel){return;}
try{if(this.panel){SAPO.Maps.Utils.removeWaitIcon(this.panel);}
var route=obj;if(!route.segs||route.error_code<=0){this.status=SAPO.Maps.Request.Status.ERROR;try{this.notifyListeners('noroute',[this]);}
catch(e4){}
if(this.panel){var elem=document.createElement('div');elem.className='search_results_smapi';SAPO.Maps.Utils.displayMessageHTML(elem,"Não temos informação disponível para o itinerário entre os pontos indicados","","",SAPO.Maps.Utils.MessageType.WARNING);this.panel.appendChild(elem);}}
var steps=[];var lines,points,lonlat;for(var i=0;i<route.segs.length;++i){points=[];lines=route.segs[i].lines;for(var j=0;j<lines.length;++j){lonlat=new OpenLayers.LonLat(lines[j].x,lines[j].y);lonlat.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));points.push(lonlat);}
if(i>0&&route.segs[i].st===""){steps[steps.length-1].distance+=route.segs[i].m;steps[steps.length-1].duration+=route.segs[i].t;steps[steps.length-1].points=(steps[steps.length-1].points).concat(points);continue;}
steps.push(new SAPO.Maps.Directions.Step({points:points,direction:route.segs[i].dir,location:route.segs[i].st.replace('&#65533;','\''),distance:route.segs[i].m,duration:route.segs[i].t}));}
this.route=new SAPO.Maps.Directions.Route(steps);if(args.mode==="apeado"){this.route.duration=obj.total.s;}
if(route.middlePoints){this.middlePoints=[];for(var k=0;k<route.middlePoints.length;++k){lonlat=new OpenLayers.LonLat(route.middlePoints[k].x,route.middlePoints[k].y);lonlat.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));this.middlePoints.push({lonlat:lonlat});}}
this.status=SAPO.Maps.Request.Status.OK;if(this.panel){this.buildHTML(this.panel);if(args.description=="textmap"){for(var a=0;a<this.route.getSteps().length;++a){this.showText(a);this.showMap(a);}}
if(args.description=="text"){for(var b=0;b<this.route.getSteps().length;++b){this.showText(b);}}
if(args.description=="map"){for(var c=0;c<this.route.getSteps().length;++c){this.showMap(c);}}
if(args.showMapCheckbox){for(var d=0;d<this.route.getSteps().length;++d){this.showCheckbox(d);}}}
if(this.map){var bounds=null;this.addPolylines();if(this.displayStartEndMarkers){this.addStartEndMarkers();}
if(this.displayMiddlePointsMarkers){this.addMiddlePointsMarkers();}
if(args.adjustBounds){bounds=this.getBounds();SAPO.Maps.Utils.AdjustBoundsConsideringBorders(this.map,bounds,this.borders);}
try{var navControl=this.map.getControlsByClass('SAPO.Maps.Control.Navigation2')[0];navControl.setContextFunction({func:function(){if(!bounds){bounds=this.getBounds();}
SAPO.Maps.Utils.AdjustBoundsConsideringBorders(this.map,bounds,this.borders);},context:this});}
catch(e6){this.contextFunction=null;}}
try{this.notifyListeners('completed',[this]);}catch(e2){try{this.notifyListeners('error',[this]);}catch(e3){}}}
catch(e1){this.route=null;this.status=SAPO.Maps.Request.Status.ERROR;try{this.notifyListeners('error',[this]);}catch(e5){}}},onError:function(){if(this.status!=SAPO.Maps.Request.Status.REQUESTING){return;}
this.status=SAPO.Maps.Request.Status.ERROR;try{this.notifyListeners('timeout',[this]);if(this.panel){SAPO.Maps.Utils.removeWaitIcon(this.panel);var elem=document.createElement('div');elem.className='search_results_smapi';SAPO.Maps.Utils.displayMessageHTML(elem,"Não temos informação disponível para o itinerário entre os pontos indicados","","",SAPO.Maps.Utils.MessageType.WARNING);this.panel.appendChild(elem);}}
catch(e){}},getStatus:function(){return this.status;},getBounds:function(){if(this.status!=SAPO.Maps.Request.Status.OK){return null;}
var bounds=null;if(this.middlePoints&&this.middlePoints.length>0){bounds=this.polylines[0].getBounds();for(var i=1;i<this.polylines.length;++i){bounds.extend(this.polylines[i].getBounds());}
return bounds;}
return this.route.getBounds();},getPolyline:function(){if(this.status!=SAPO.Maps.Request.Status.OK){return null;}
return this.route.getPolyline();},getStartEndMarkers:function(){return this.startEndMarkers;},getDuration:function(){if(this.status!=SAPO.Maps.Request.Status.OK){return null;}
return this.route.getDuration();},getDistance:function(){if(this.status!=SAPO.Maps.Request.Status.OK){return null;}
return this.route.getDistance();},getRoute:function(){if(this.status!=SAPO.Maps.Request.Status.OK){return null;}
return this.route;},getStartLonLat:function(){if(this.status!=SAPO.Maps.Request.Status.OK){return null;}
return this.route.getSteps()[0].getStart();},getEndLonLat:function(){if(this.status!=SAPO.Maps.Request.Status.OK){return null;}
var steps=this.route.getSteps();return steps[steps.length-1].getEnd();},getDescription:function(){if(this.status!=SAPO.Maps.Request.Status.OK){return null;}
return this.route.getDescription(this.language);},getSummaryHTML:function(){if(this.status!=SAPO.Maps.Request.Status.OK){return null;}
var divNode=document.createElement("div");this.buildHTML(divNode);return divNode;},navigateTo:function(idxStep){try{var tr=this.panel.childNodes[1].childNodes[1].childNodes[this.currentStepIdx+1];if(tr.hasMap&&tr.hasText){tr.className="iti_step_smapi iti_imageandtext_list_smapi";}
else{if(tr.hasMap){tr.className="iti_step_smapi iti_image_list_smapi";}
else{tr.className="iti_step_smapi";}}
if(this.currentStepIdx===-1||this.currentStepIdx===this.route.steps.length){SAPO.Maps.Utils.addClassName(tr,'iti_Points_smapi');}
tr=this.panel.childNodes[1].childNodes[1].childNodes[idxStep+1];if(tr.hasMap&&tr.hasText){tr.className="iti_step_smapi iti_imageandtext_list_smapi iti_selected_smapi";if(OpenLayers.Util.getBrowserName()==='msie'){tr.className+=" iti_selected_smapi_ie";}}
else{if(tr.hasMap){tr.className="iti_step_smapi iti_image_list_smapi iti_selected_smapi";if(OpenLayers.Util.getBrowserName()==='msie'){tr.className+=" iti_selected_smapi_ie";}}
else{tr.className="iti_step_smapi iti_selected_smapi";if(OpenLayers.Util.getBrowserName()==='msie'){tr.className+=" iti_selected_smapi_ie";}}}
if(idxStep===-1||idxStep===this.route.steps.length){SAPO.Maps.Utils.addClassName(tr,'iti_Points_smapi');}}
catch(e2){}
this.currentStepIdx=idxStep;if(!this.map){return;}
var step=this.route.steps[idxStep];if(!step){if(idxStep===-1){step=this.route.steps[0];}
if(idxStep===this.route.steps.length){step=this.route.steps[this.route.steps.length-1];}}
var stepBounds=new OpenLayers.Bounds(step.points[0].lon,step.points[0].lat,step.points[0].lon,step.points[0].lat);for(var i=1;i<step.points.length;++i){stepBounds.extend(step.points[i]);}
stepBounds.transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));var stepZoom=this.map.getZoomForExtent(stepBounds);this.map.zoomTo(stepZoom);var stepLonLat=null;if(idxStep===this.route.steps.length){stepLonLat=step.getEnd().clone().transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));}
else{stepLonLat=step.getStart().clone().transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));}
this.map.panTo(stepLonLat);try{this.notifyListeners('stepSelected',[this,this.currentStepIdx]);}
catch(e1){}},unselectStep:function(){try{var tr=this.panel.childNodes[1].childNodes[1].childNodes[this.currentStepIdx+1];if(tr.hasMap&&tr.hasText){tr.className="iti_step_smapi iti_imageandtext_list_smapi";}
else{if(tr.hasMap){tr.className="iti_step_smapi iti_image_list_smapi";}
else{tr.className="iti_step_smapi";}}
if(this.currentStepIdx===-1||this.currentStepIdx===this.route.steps.length){SAPO.Maps.Utils.addClassName(tr,'iti_Points_smapi');}}
catch(e1){return;}
try{this.notifyListeners('stepUnselected',[this,this.currentStepIdx]);}
catch(e2){}},openPopup:function(idxStep){if(!this.map){return;}
var _this=this;var step=this.route.getSteps()[idxStep];if(!step){if(idxStep<0){idxStep=-1;}
if(idxStep>this.route.steps.length){idxStep=this.route.steps.length;}}
var first=idxStep===-1?true:false;var last=idxStep===this.route.getSteps().length?true:false;if(this.popup){this.closePopup();}
var content=this.getPopupHTML(idxStep,step);var popupAnchor=null;if(step){popupAnchor=step.getStart().clone().transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));}
else{if(idxStep===-1){popupAnchor=this.route.steps[0].getStart().clone().transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));}
if(idxStep===this.route.steps.length){popupAnchor=this.route.steps[this.route.steps.length-1].getEnd().clone().transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));}}
this.popup=new SAPO.Maps.Popup.SapoPopup(popupAnchor.toShortString(),popupAnchor,null,content,true,function(popup){SAPO.Maps.Directions.prototype.closePopup.apply(_this,[]);});this.map.addPopup(this.popup);this.navigateTo(idxStep);try{this.notifyListeners('popupOpened',[this,this.currentStepIdx]);}
catch(e2){}},closePopup:function(){if(!this.map){return;}
if(this.popup){this.map.removePopup(this.popup);this.popup=null;}
this.unselectStep();try{this.notifyListeners('popupClosed',[this,this.currentStepIdx]);}
catch(e){}},showAllMaps:function(){if(this.status!==SAPO.Maps.Request.Status.OK){return;}
var length=this.route.getSteps().length;for(var i=0;i<length;++i){this.showMap(i);}},hideAllMaps:function(){if(this.status!==SAPO.Maps.Request.Status.OK){return;}
var length=this.route.getSteps().length;for(var i=0;i<length;++i){this.hideMap(i);}},showMap:function(idxStep){var tr_step=this.panel.childNodes[1].childNodes[1].childNodes[idxStep+1];var divMapStep=tr_step.childNodes[3].childNodes[1];if(!divMapStep){return;}
divMapStep.id=Math.random().toString();divMapStep.style.display="block";divMapStep.style.width="130px";divMapStep.style.height="130px";if(!divMapStep.mapObject){divMapStep.mapObject=new SAPO.Maps.Map(divMapStep.id);for(var i=0;i<divMapStep.mapObject.controls.length;++i){if(divMapStep.mapObject.controls[i].CLASS_NAME==="SAPO.Maps.Control.Scale"){divMapStep.mapObject.removeControl(divMapStep.mapObject.controls[i]);break;}}
for(var j=0;i<divMapStep.mapObject.controls.length;++i){if(divMapStep.mapObject.controls[i].CLASS_NAME==="SAPO.Maps.Control.PermanentLink"){divMapStep.mapObject.removeControl(divMapStep.mapObject.controls[i]);break;}}
var polyline=this.getPolyline().clone();divMapStep.mapObject.addOverlay(polyline);divMapStep.mapObject.setMapCenter(this.route.getSteps()[idxStep].getStart(),17);}
tr_step.hasMap=true;tr_step.childNodes[3].className="iti_showMap_checkbox";tr_step.childNodes[3].childNodes[0].childNodes[0].checked=true;},hideMap:function(idxStep){var tr_step=this.panel.childNodes[1].childNodes[1].childNodes[idxStep+1];var divMapStep=tr_step.childNodes[3].childNodes[1];if(!divMapStep){return;}
divMapStep.style.display="none";tr_step.hasMap=false;if(!tr_step.hasCheckbox){tr_step.childNodes[3].className="hide";}
tr_step.childNodes[3].childNodes[0].childNodes[0].checked=false;},showText:function(idxStep){var tr_step=this.panel.childNodes[1].childNodes[1].childNodes[idxStep+1];if(!tr_step){return;}
tr_step.hasText=true;tr_step.childNodes[1].className="iti_direction_text_smapi";},hideText:function(idxStep){var tr_step=this.panel.childNodes[1].childNodes[1].childNodes[idxStep+1];if(!tr_step){return;}
tr_step.hasText=false;tr_step.childNodes[1].className="hide";},showCheckbox:function(idxStep){var tr_step=this.panel.childNodes[1].childNodes[1].childNodes[idxStep+1];if(!tr_step){return;}
tr_step.childNodes[3].childNodes[0].style.display="block";tr_step.hasCheckbox=true;tr_step.childNodes[3].className="iti_showMap_checkbox";},hideCheckbox:function(idxStep){var tr_step=this.panel.childNodes[1].childNodes[1].childNodes[idxStep+1];if(!tr_step){return;}
tr_step.childNodes[3].childNodes[0].style.display="none";tr_step.hasCheckbox=false;if(!tr_step.hasMap){tr_step.childNodes[3].className="hide";}},getMiddlePoints:function(){var middlePoints=[];if(this.middlePoints){for(var i=0;i<this.middlePoints.length;++i){middlePoints.push(this.middlePoints[i].lonlat);}}
return middlePoints;},addMiddlePoint:function(lonlat){var start=this.getStartLonLat();var end=this.getEndLonLat();var middlePoints=[];if(this.middlePoints){for(var i=0;i<this.middlePoints.length;++i){middlePoints.push(this.middlePoints[i].lonlat);}}
middlePoints.push(lonlat);this.clear();this.getDirections(start,end,{middlePoints:middlePoints,adjustBounds:false});},removeMiddlePoint:function(lonlat){if(this.middlePoints){var start=this.getStartLonLat();var end=this.getEndLonLat();var middlePoints=[];for(var i=0;i<this.middlePoints.length;++i){if(this.middlePoints[i].lonlat.equals(lonlat)){continue;}
middlePoints.push(this.middlePoints[i].lonlat);}
this.clear();this.getDirections(start,end,{middlePoints:middlePoints,adjustBounds:false});}},addPolylines:function(){this.polylines=[];if(!this.middlePoints||(this.middlePoints&&this.middlePoints.length===0)){this.polylines.push(this.route.getPolyline());}
else{var steps=this.route.getSteps();var points=[];var polyline=null;for(var i=0,j=0;i<steps.length;++i){points=points.concat(steps[i].getPoints());if(j<this.middlePoints.length){if(steps[i].getEnd().equals(this.middlePoints[j].lonlat)){polyline=new SAPO.Maps.Polyline(points,{strokeColor:"#0000FF",strokeOpacity:0.5,strokeWidth:5});this.polylines.push(polyline);points=[];++j;}}}
this.polylines.push(new SAPO.Maps.Polyline(points,{strokeColor:"#0000FF",strokeOpacity:0.5,strokeWidth:5}));}
for(var k=0;k<this.polylines.length;++k){this.polylines[k].index=k;this.map.addOverlay(this.polylines[k]);if(this.editableRoute){this.polylines[k].registerEvent('mouseover',this,this.mouseover);this.polylines[k].registerEvent('mouseout',this,this.mouseout);this.polylines[k].registerEvent('mousedown',this,this.mousedown);}}},removePolylines:function(){if(this.polylines){for(var i=0;i<this.polylines.length;++i){this.map.removeOverlay(this.polylines[i]);this.polylines[i].unRegisterEvent('mouseover',this,this.mouseover);this.polylines[i].unRegisterEvent('mousedown',this,this.mousedown);}
this.polylines=null;}},buildHTML:function(node){if(this.status!=SAPO.Maps.Request.Status.OK){return null;}
var _this=this;while(node.hasChildNodes()){node.removeChild(node.childNodes[0]);}
node.className+=" iti_results_smapi";if(OpenLayers.Util.getBrowserName()==='msie'){node.className+=" iti_results_smapi_ie";}
var steps=this.route.getSteps();var div_header=document.createElement("div");div_header.className="iti_results_header_smapi";var div_estimated_time=document.createElement("div");div_estimated_time.className="iti_estimated_smapi";var p_distance=document.createElement("p");var p_estimated_time=document.createElement("p");p_distance.innerHTML=SAPO.Maps.Lang[this.language].distance+": ";p_estimated_time.innerHTML=SAPO.Maps.Lang[this.language].estimated_time+": ";var route_distance=this.route.getDistance();p_distance.innerHTML+="<span>"+(route_distance>1000?(route_distance/1000).toFixed(1).toString()+"km":route_distance.toString()+"m")+"</span";var route_duration=this.route.getDuration();if(route_duration<60){p_estimated_time.innerHTML+="<span>"+Math.round(route_duration).toString()+"s</span>";}
else{if(route_duration<3600){p_estimated_time.innerHTML+="<span>"+(route_duration/60).toFixed(0).toString()+"min</span>";}
else{var hours=Math.floor(route_duration/3600);var minutes=((route_duration%3600)/60).toFixed(0);p_estimated_time.innerHTML+="<span>"+hours+"h "+minutes+"min</span>";}}
div_estimated_time.appendChild(p_distance);div_estimated_time.appendChild(p_estimated_time);div_header.appendChild(div_estimated_time);node.appendChild(div_header);var table_list=document.createElement("table");table_list.className="iti_result_list_smapi";var tableHeader_list=document.createElement("thead");tableHeader_list.style.height="0px";var tableFooter_list=document.createElement("tfoot");tableFooter_list.style.height="0px";var tableBody_list=document.createElement("tbody");tableBody_list.style.height="0px";table_list.appendChild(tableHeader_list);table_list.appendChild(tableBody_list);table_list.appendChild(tableFooter_list);var tr_start=document.createElement("tr");tr_start.className="iti_Points_smapi";var td_img_start=document.createElement("td");td_img_start.colSpan='5';td_img_start.className="iti_start_image_smapi";var span_start=document.createElement("span");span_start.innerHTML=steps[0].getLocation()!==''?steps[0].getLocation():steps[0].getStartString();td_img_start.appendChild(span_start);tr_start.appendChild(td_img_start);tableBody_list.appendChild(tr_start);tr_start.onclick=function(){this.openPopup(-1);}.bindObj(this);var tr_step,td_step_text_img,img_step_img,td_step_text_description,td_step_text_length,td_step_checkbox_map,input_checkbox,label_checkbox,p_checkbox,div_step_map,a_step,span_step1,span_step2;for(var i=0;i<steps.length;++i){tr_step=document.createElement("tr");tr_step.className="iti_step_smapi";div_step_map=document.createElement("div");div_step_map.className="iti_direction_preview_smapi";td_step_text_img=document.createElement("td");td_step_text_img.className="iti_direction_img_smapi";img_step_img=document.createElement("img");td_step_text_description=document.createElement("td");td_step_text_description.className="iti_direction_text_smapi";td_step_text_length=document.createElement("td");td_step_text_length.className="iti_meters_smapi";a_step=document.createElement("a");a_step.href="#";span_step1=document.createElement("span");span_step2=document.createElement("span");if(OpenLayers.Util.getBrowserName()==='msie'){td_step_text_description.className+=" iti_direction_text_smapi_ie";td_step_text_img.className+=" iti_direction_img_smapi_ie";td_step_text_length.className+=" iti_meters_smapi_ie";}
if(i===0){img_step_img.src="http://imgs.sapo.pt/fotos_gis/site/iti_continue.gif";span_step1.innerHTML=SAPO.Maps.Lang[this.language].directions_go;a_step.appendChild(span_step1);if(steps[i].getLocation()!==""){a_step.innerHTML+=" through ";span_step2.innerHTML=steps[i].getLocation();a_step.appendChild(span_step2);}}
else{switch(steps[i].direction){case 0:img_step_img.src="http://imgs.sapo.pt/fotos_gis/site/iti_continue.gif";span_step1.innerHTML=SAPO.Maps.Lang[this.language].directions_step_forward;a_step.appendChild(span_step1);if(steps[i].getLocation()!==""){a_step.innerHTML+=" "+SAPO.Maps.Lang[this.language].directions_to+" ";span_step2.innerHTML=steps[i].getLocation();a_step.appendChild(span_step2);}
break;case 1:img_step_img.src="http://imgs.sapo.pt/fotos_gis/site/iti_turn_left.gif";span_step1.innerHTML=SAPO.Maps.Lang[this.language].directions_step_left;a_step.appendChild(span_step1);if(steps[i].getLocation()!==""){a_step.innerHTML+=" "+SAPO.Maps.Lang[this.language].directions_to+" ";span_step2.innerHTML=steps[i].getLocation();a_step.appendChild(span_step2);}
break;case-1:img_step_img.src="http://imgs.sapo.pt/fotos_gis/site/iti_turn_right.gif";span_step1.innerHTML=SAPO.Maps.Lang[this.language].directions_step_right;a_step.appendChild(span_step1);if(steps[i].getLocation()!==""){a_step.innerHTML+=" "+SAPO.Maps.Lang[this.language].directions_to+" ";span_step2.innerHTML=steps[i].getLocation();a_step.appendChild(span_step2);}
break;}}
td_step_text_length.innerHTML=steps[i].getDistance()>1000?(steps[i].getDistance()/1000).toFixed(1).toString()+"km":steps[i].getDistance().toString()+"m";td_step_text_description.appendChild(a_step);td_step_checkbox_map=document.createElement("td");p_checkbox=document.createElement("p");td_step_checkbox_map.className="iti_showMap_checkbox";OpenLayers.Event.observe(td_step_checkbox_map,'click',OpenLayers.Event.stop);input_checkbox=document.createElement("input");input_checkbox.id="__SAPO_MAPS_DIRECTIONS_"+(new Date().getTime()).toString();try{label_checkbox=document.createElement('<label for="'+input_checkbox.id+'"></label>');label_checkbox.appendChild(document.createTextNode(" "+SAPO.Maps.Lang[this.language].show_map+" "));}
catch(e1){label_checkbox=document.createElement('label');label_checkbox.setAttribute('for',input_checkbox.id);label_checkbox.appendChild(document.createTextNode(" "+SAPO.Maps.Lang[this.language].show_map+" "));}
label_checkbox.onclick=function(e){OpenLayers.Event.stop(e?e:window.event,true);};input_checkbox.type="checkbox";input_checkbox.idxStep=i;input_checkbox.onclick=function(e){if(this.checked){_this.showMap(this.idxStep);}
else{_this.hideMap(this.idxStep);}
OpenLayers.Event.stop(e?e:window.event,true);};p_checkbox.appendChild(input_checkbox);p_checkbox.appendChild(label_checkbox);p_checkbox.style.display="none";td_step_checkbox_map.appendChild(p_checkbox);td_step_checkbox_map.appendChild(div_step_map);td_step_text_img.appendChild(img_step_img);tr_step.appendChild(td_step_text_img);tr_step.appendChild(td_step_text_description);tr_step.appendChild(td_step_text_length);tr_step.appendChild(td_step_checkbox_map);tableBody_list.appendChild(tr_step);tr_step.idxStep=i;tr_step.onclick=function(){_this.openPopup(this.idxStep);return false;};}
var tr_end=document.createElement("tr");tr_end.className="iti_Points_smapi";var td_img_end=document.createElement("td");td_img_end.colSpan=5;td_img_end.className="iti_end_image_smapi";td_img_end.innerHTML=steps[steps.length-1].getLocation()!==''?steps[steps.length-1].getLocation():steps[steps.length-1].getEndString();tr_end.appendChild(td_img_end);tableBody_list.appendChild(tr_end);tr_end.onclick=function(){this.openPopup(steps.length);}.bindObj(this);node.appendChild(table_list);return node;},getPopupHTML:function(idx,step){var first=(idx===-1);var last=(idx===this.route.getSteps().length);var div_wrapper=document.createElement('div');var div_description=document.createElement('div');var div_prev_next=document.createElement('div');var div_prev=document.createElement('div');var div_next=document.createElement('div');var div_clear=document.createElement('div');div_wrapper.className='iti_popup_wrapper';div_description.className='iti_popup_description';div_prev_next.className='iti_popup_prev_next_smapi';div_prev.className='iti_popup_prev_holder_smapi';div_next.className='iti_popup_next_holder_smapi';div_clear.className='clear';if(step){div_description.innerHTML=step.getDescription("pt",{isFirstStep:first});}
else{if(idx<0){div_description.innerHTML=this.route.steps[0].location!==''?this.route.steps[0].location:this.route.steps[0].getStartString();}
if(idx>this.route.steps.length-1){div_description.innerHTML=this.route.steps[this.route.steps.length-1].location!==''?this.route.steps[this.route.steps.length-1].location:this.route.steps[this.route.steps.length-1].getEndString();}}
div_wrapper.appendChild(div_description);div_wrapper.appendChild(document.createElement('br'));div_prev_next.appendChild(div_prev);div_prev_next.appendChild(div_next);div_wrapper.appendChild(div_prev_next);div_wrapper.appendChild(div_clear);if(!first){if(!last){div_prev.className+=' iti_popup_prev_holder_extra_smapi';}
var prev_image=document.createElement('img');var prev_label=document.createElement('span');prev_image.className='iti_popup_prev_smapi';prev_image.src='http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Directions/prev.gif';prev_label.className='iti_popup_prev_smapi';prev_label.innerHTML='Anterior';div_prev.appendChild(prev_image);div_prev.appendChild(document.createElement('br'));div_prev.appendChild(prev_label);OpenLayers.Event.observe(div_prev,'click',function(){this.navigateTo(idx-1);this.openPopup(idx-1);}.bindObj(this));}
if(!last){if(!first){div_next.className+=' iti_popup_next_holder_extra_smapi';}
var next_image=document.createElement('img');var next_label=document.createElement('span');next_image.className='iti_popup_next_smapi';next_image.src='http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Directions/next.gif';next_label.className='iti_popup_prev_smapi';next_label.innerHTML='Seguinte';div_next.appendChild(next_image);div_next.appendChild(document.createElement('br'));div_next.appendChild(next_label);OpenLayers.Event.observe(div_next,'click',function(){this.navigateTo(idx+1);this.openPopup(idx+1);}.bindObj(this));}
return div_wrapper;},addStartEndMarkers:function(){if(!this.startEndMarkers){this.startEndMarkers={};}
var startStyle={markerImage:'http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Directions/iti_markerA.png',markerAnchor:new OpenLayers.Pixel(-5,-28),size:new OpenLayers.Size(22,28)};var endStyle={markerImage:'http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Directions/iti_markerB.png',markerAnchor:new OpenLayers.Pixel(-5,-28),size:new OpenLayers.Size(22,28)};this.startEndMarkers={start:new SAPO.Maps.Marker(this.getStartLonLat(),{draggable:this.editableRoute},startStyle),end:new SAPO.Maps.Marker(this.getEndLonLat(),{draggable:this.editableRoute},endStyle)};this.startEndMarkers.start.registerEvent('click',this,this.startMarkerClicked);this.startEndMarkers.end.registerEvent('click',this,this.endMarkerClicked);if(this.editableRoute){this.startEndMarkers.start.registerEvent('dragend',this,this.startEndMarkersPositionChanged);this.startEndMarkers.end.registerEvent('dragend',this,this.startEndMarkersPositionChanged);}
this.map.addOverlay(this.startEndMarkers.start);this.map.addOverlay(this.startEndMarkers.end);},startMarkerClicked:function(marker){this.openPopup(-1);},endMarkerClicked:function(marker){this.openPopup(this.route.steps.length);},startEndMarkersPositionChanged:function(marker){var start=this.startEndMarkers.start.getLonLat();var end=this.startEndMarkers.end.getLonLat();var middlePoints=[];if(this.middlePoints){for(var i=0;i<this.middlePoints.length;++i){middlePoints.push(this.middlePoints[i].lonlat);}}
var startChanged=true;if(start.equals(this.getStartLonLat())){startChanged=false;}
try{this.notifyListeners('startEndMarkerMoved',[this,{start:start,end:end},startChanged]);}catch(e){}
this.clear();this.getDirections(start,end,{middlePoints:middlePoints,adjustBounds:false});},addMiddlePointsMarkers:function(){if(!this.middlePoints){return;}
var style={markerImage:'http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Directions/iti_middle_point_marker_white.png',markerAnchor:new OpenLayers.Pixel(-7,-7),size:new OpenLayers.Size(14,14)};for(var i=0;i<this.middlePoints.length;++i){this.middlePoints[i].marker=new SAPO.Maps.Marker(this.middlePoints[i].lonlat,{draggable:this.editableRoute},style);if(this.editableRoute){this.middlePoints[i].marker.registerEvent('dragend',this,this.middlePointsMarkersPositionChanged);}
this.map.addOverlay(this.middlePoints[i].marker);}},middlePointsMarkersPositionChanged:function(marker){var start=this.getStartLonLat();var end=this.getEndLonLat();var middlePoints=[];if(this.middlePoints){for(var i=0;i<this.middlePoints.length;++i){if(this.middlePoints[i].marker===marker){this.middlePoints[i].lonlat=marker.getLonLat();}
middlePoints.push(this.middlePoints[i].lonlat);}}
try{this.notifyListeners('middlePointMarkerMoved',[marker]);}catch(e){}
this.clear();this.getDirections(start,end,{middlePoints:middlePoints,adjustBounds:false});},clear:function(){if(this.status==SAPO.Maps.Request.Status.REQUESTING){throw'Directions: cannot clear the info until the request is pending';}
this.clearStartEndMarkers();this.clearMiddlePointsMarkers();this.clearLine();this.clearPanel();try{this.notifyListeners('clear',[this]);}catch(e){}},clearLine:function(){if(this.map){this.removePolylines();this.closePopup();}},clearPanel:function(){if(this.panel){while(this.panel.hasChildNodes()){this.panel.removeChild(this.panel.childNodes[0]);}
var classes=this.panel.className.split(' ');this.panel.className="";if(classes.length===0){return;}
for(var i=0;i<classes.length;++i){if(classes[i]==="iti_results_smapi"||classes[i]==="iti_results_smapi_ie"){continue;}
this.panel.className+=classes[i];}}},clearStartEndMarkers:function(){if(this.startEndMarkers){this.startEndMarkers.start.unRegisterEvent('click',this,this.startMarkerClicked);this.startEndMarkers.end.unRegisterEvent('click',this,this.endMarkerClicked);if(this.editableRoute){this.startEndMarkers.start.unRegisterEvent('dragend',this,this.startEndMarkersPositionChanged);this.startEndMarkers.end.unRegisterEvent('dragend',this,this.startEndMarkersPositionChanged);}
this.map.removeOverlay(this.startEndMarkers.start);this.map.removeOverlay(this.startEndMarkers.end);this.startEndMarkers=null;}},clearMiddlePointsMarkers:function(){if(this.displayMiddlePointsMarkers&&this.middlePoints){for(var i=0;i<this.middlePoints.length;++i){this.middlePoints[i].marker.unRegisterEvent('dragend',this,this.middlePointsMarkersPositionChanged);this.map.removeOverlay(this.middlePoints[i].marker);}
this.middlePoints=null;}},createTooltip:function(){if(!this.tooltip){this.tooltip=new SAPO.Maps.Control.Tooltip('Arraste para alterar o itinerário',null,{visible:false});}
this.map.addControl(this.tooltip);},removeTooltip:function(){if(this.tooltip){this.tooltip.hide();}},positionTooltip:function(x,y){if(!this.tooltip){this.createTooltip();}
this.tooltip.setPosition(new OpenLayers.Pixel(x,y));this.tooltip.show();},addNewMiddleMarkerIndicatorDivImg:function(x,y){var div=document.createElement('div');var img=document.createElement('img');img.src='http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Directions/iti_middle_point_marker_white.png';img.width=14;img.height=14;div.style.position='absolute';div.style.left=x+'px';div.style.top=y+'px';div.style.zIndex='1000';div.appendChild(img);if(SAPO.Maps.Utils.checkIE6()){div.className+=' search_item_marker_ie6';img.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',src='"+img.src+"')";}
this.newMiddleMarkerIndicatorDivImg=div;this.map.div.appendChild(this.newMiddleMarkerIndicatorDivImg);},adjustNewMiddleMarkerIndicatorDivImg:function(x,y){this.newMiddleMarkerIndicatorDivImg.style.left=x+'px';this.newMiddleMarkerIndicatorDivImg.style.top=y+'px';},mousemove:function(evt){if(!evt){evt=window.event;}
if(!this.mapDivOffset){this.calculateMapDivOffset();}
var x=evt.pageX?evt.pageX:evt.clientX;var y=evt.pageY?evt.pageY:evt.clientY;if(this.newMiddleMarkerIndicator){if(!this.newMiddleMarkerIndicatorDivImg){this.addNewMiddleMarkerIndicatorDivImg(x-this.mapDivOffset.left-5,y-this.mapDivOffset.top+16);}
this.adjustNewMiddleMarkerIndicatorDivImg(x-this.mapDivOffset.left-5,y-this.mapDivOffset.top+16);}
else{this.positionTooltip(x-this.mapDivOffset.left+5,y-this.mapDivOffset.top-20);}
OpenLayers.Event.stop(evt);},calculateMapDivOffset:function(){var offsetLeft=this.map.div.offsetLeft;var offsetTop=this.map.div.offsetTop;var offsetParent=this.map.div.offsetParent;while(offsetParent){offsetLeft+=offsetParent.offsetLeft;offsetTop+=offsetParent.offsetTop;offsetParent=offsetParent.offsetParent;}
this.mapDivOffset={left:offsetLeft,top:offsetTop};},mouseover:function(polyline){this.map.div.style.cursor="pointer";OpenLayers.Event.observe(this.map.div,'mousemove',this.mousemoveListener);},mouseout:function(polyline){OpenLayers.Event.stopObserving(this.map.div,'mousemove',this.mousemoveListener);this.removeTooltip();this.map.div.style.cursor="url(\"http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/openhand.cur\"), pointer";},mousedown:function(polyline){polyline.unRegisterEvent('mouseout',this,this.mouseout);this.removeTooltip();this.newMiddlePointIndex=polyline.index;OpenLayers.Event.observe(this.map.div,'mouseup',this.mouseupListener);this.newMiddleMarkerIndicator=true;this.map.div.style.cursor="url(\"http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/closedhand.cur\"), pointer";if(OpenLayers.Util.getBrowserName()==='msie'){Event.observe(document.body,"keydown",this.keydownListener);}
else{Event.observe(window,"keydown",this.keydownListener);}},mouseup:function(evt){OpenLayers.Event.stopObserving(this.map.div,'mousemove',this.mousemoveListener);if(this.newMiddleMarkerIndicator){if(this.newMiddleMarkerIndicatorDivImg){this.map.div.removeChild(this.newMiddleMarkerIndicatorDivImg);this.newMiddleMarkerIndicatorDivImg=null;}
this.newMiddleMarkerIndicator=false;}
if(OpenLayers.Util.getBrowserName()==='msie'){Event.stopObserving(document.body,"mousedown",this.keydownListener);}
else{Event.stopObserving(window,"mousedown",this.keydownListener);}
OpenLayers.Event.stopObserving(this.map.div,'mouseup',this.mouseupListener);this.map.div.style.cursor="url(\"http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/openhand.cur\"), pointer";if(!evt){this.polylines[this.newMiddlePointIndex].registerEvent('mouseout',this,this.mouseout);return;}
var xy=evt.xy?evt.xy:new OpenLayers.Pixel(evt.clientX,evt.clientY-26);var lonlat=this.map.getLonLatFromContainerPixel(xy);var start=this.getStartLonLat();var end=this.getEndLonLat();var middlePoints=[];if(this.middlePoints){for(var i=0;i<this.middlePoints.length;++i){middlePoints.push(this.middlePoints[i].lonlat);}}
if(this.newMiddlePointIndex===-1||this.newMiddlePointIndex>=middlePoints.length){middlePoints.push(lonlat);}
else{middlePoints.splice(this.newMiddlePointIndex,0,lonlat);}
this.clear();this.getDirections(start,end,{middlePoints:middlePoints,adjustBounds:false});},keydown:function(evt){if(evt.keyCode===Event.KEY_ESC){this.mouseup();Event.stop(evt);}},cancel:function(){if(this.status!=SAPO.Maps.Request.Status.REQUESTING){return;}
this.status=SAPO.Maps.Request.Status.CANCELED;this.request.cancel=true;try{this.notifyListeners('canceled',[this]);}catch(e){}},registerEvent:function(eventType,context,func){if(!this.events[eventType]){this.events[eventType]=[];}
var obj={func:func,context:context};this.events[eventType].push(obj);},unRegisterEvent:function(eventType,context,func){var evts=this.events[eventType]?this.events[eventType]:[];for(var i=0;i<evts.length;++i){if(context==evts[i].context&&func==evts[i].func){evts.splice(i,1);return true;}}
return false;},notifyListeners:function(eventType,args){var evts=this.events[eventType]?this.events[eventType]:[];args=args?args:[];var func,context;for(var i=0;i<evts.length;++i){func=evts[i].func;context=evts[i].context;func.apply(context,args);}},EVENT_TYPES:['completed','error','clear','canceled','noroute','loading','timeout','stepSelected','stepUnselected','popupOpened','popupClosed','startEndMarkerMoved','middlePointMarkerMoved'],CLASS_NAME:'SAPO.Maps.Directions'});SAPO.Maps.Directions.Step=OpenLayers.Class({points:null,distance:0,duration:0,location:null,direction:null,initialize:function(opts){this.direction=opts.direction;this.location=opts.location;this.distance=opts.distance;this.duration=opts.duration;this.points=opts.points;},getPoints:function(){return this.points;},getDescription:function(language,options){var opts=OpenLayers.Util.extend({isFirstStep:false},options);var description=null;if(!language){language="pt";}
if(language==="pt"){if(opts.isFirstStep===true){description=this.location===""?"":SAPO.Maps.Lang.pt.directions_first_step_description+this.location;}
else{switch(this.direction){case 0:description=this.location===""?SAPO.Maps.Lang.pt.directions_step_forward:SAPO.Maps.Lang.pt.directions_step_forward_description+this.location;break;case 1:description=this.location===""?SAPO.Maps.Lang.pt.directions_step_left:SAPO.Maps.Lang.pt.directions_step_left_description+this.location;break;case-1:description=this.location===""?SAPO.Maps.Lang.pt.directions_step_right:SAPO.Maps.Lang.pt.directions_step_right_description+this.location;}}}
if(language==="en"){if(opts.isFirstStep===true){description=this.location===""?"":SAPO.Maps.Lang.en.directions_first_step_description+this.location;}
else{switch(this.direction){case 0:description=this.location===""?SAPO.Maps.Lang.en.directions_step_forward:SAPO.Maps.Lang.en.directions_step_forward_description+this.location;break;case 1:description=this.location===""?SAPO.Maps.Lang.en.directions_step_left:SAPO.Maps.Lang.en.directions_step_left_description+this.location;break;case-1:description=this.location===""?SAPO.Maps.Lang.en.directions_step_right:SAPO.Maps.Lang.en.directions_step_right_description+this.location;}}}
return description;},getDistance:function(){return this.distance;},getDuration:function(){return this.duration;},getLocation:function(){return this.location;},getDirection:function(){return this.direction;},getStart:function(){return this.points[0];},getEnd:function(){return this.points[this.points.length-1];},getStartString:function(){return this.points[0].lat.toFixed(6)+', '+this.points[0].lon.toFixed(6);},getEndString:function(){return this.points[this.points.length-1].lat.toFixed(6)+', '+this.points[this.points.length-1].lon.toFixed(6);},CLASS_NAME:"SAPO.Maps.Directions.Step"});SAPO.Maps.Directions.Route=OpenLayers.Class({steps:null,distance:0,duration:0,polyline:null,initialize:function(steps){this.steps=steps;},getSteps:function(){return this.steps;},getDistance:function(){if(this.distance!==0){return this.distance;}
for(var i=0;i<this.steps.length;++i){this.distance+=this.steps[i].getDistance();}
return this.distance;},getDuration:function(){if(this.duration!==0){return this.duration;}
for(var i=0;i<this.steps.length;++i){this.duration+=this.steps[i].getDuration();}
return this.duration;},getDescription:function(language){var description=[];if(!language){language="pt";}
for(var i=0;i<this.steps.length;++i){description.push(this.steps[i].getDescription(language));}
return description;},getBounds:function(){if(!this.polyline){this.getPolyline();}
return this.polyline.getBounds();},getPolyline:function(){if(this.polyline){return this.polyline;}
var points=[];for(var i=0;i<this.steps.length;++i){points=points.concat(this.steps[i].points);}
this.polyline=new SAPO.Maps.Polyline(points,{strokeColor:"#0000FF",strokeOpacity:0.5,strokeWidth:5});return this.polyline;},CLASS_NAME:"SAPO.Maps.Directions.Route"});SAPO.Maps.Itineraries=OpenLayers.Class({status:null,map:null,panel:null,directions:null,search:null,listeners:null,request:null,from:null,to:null,middlePoints:null,startSelected:false,endSelected:false,language:null,mode:null,description:null,showMapCheckbox:false,borders:null,numberOfPagesShown:5,allowPaging:true,indexToSelect:null,indexToShowDetails:null,div:null,initialize:function(map,panel,options){this.language='pt';this.mode='fastest';OpenLayers.Util.extend(this,options);this.status=SAPO.Maps.Request.Status.STOP;this.map=map;if(panel){this.panel=typeof(panel)=='string'?document.getElementById(panel):panel;}
this.search=new SAPO.Maps.Search(this.map,this.panel,{borders:this.borders,openDetailsWhenClick:false,numberOfPagesShown:this.numberOfPagesShown,showSearchTitleMessage:false});this.directions=new SAPO.Maps.Directions(map,panel,options);this.listeners={};this.directions.registerEvent('completed',this,this.completedDirections);this.directions.registerEvent('timeout',this,this.timeout);this.directions.registerEvent('noroute',this,this.itineraryNotFound);this.directions.registerEvent('popupOpened',this,this.directionsStepSelected);this.directions.registerEvent('popupClosed',this,this.directionsStepUnselected);if(options&&options.displayStartEndMarkers){this.directions.registerEvent('startEndMarkerMoved',this,this.startEndMarkerMoved);}
this.search.registerEvent('completed',this,this.completedSearch);this.search.registerEvent('selectedOnMap',this,this.resultSelectedOnMap);this.search.registerEvent('selectedOnPanel',this,this.resultSelectedOnPanel);this.search.registerEvent('unselected',this,this.unselectSearchResult);this.search.registerEvent('timeout',this,this.timeout);this.search.registerEvent('pageChanged',this,this.pageChanged);},getItinerary:function(from,to,options){if(!from||!to){throw'Itineraries: Invalid arguments';}
if(this.status==SAPO.Maps.Request.Status.REQUESTING){throw'Itineraries: Cannot query the server while the last request is waiting';}
this.prepareRequest();OpenLayers.Util.extend(this,options);this.status=SAPO.Maps.Request.Status.REQUESTING;this.from=from;this.to=to;this.requestPOIS(true);},getStatus:function(){return this.status;},getStartingPOIS:function(){if(!this.startSelected&&this.status===SAPO.Maps.Request.Status.REQUESTING){return this.search.getPOIS();}
return this.startSelected;},getEndingPOIS:function(){if(!this.endSelected&&this.status===SAPO.Maps.Request.Status.REQUESTING){return this.search.getPOIS();}
return this.endSelected;},goToPage:function(page){if(this.search.getStatus()===SAPO.Maps.Request.Status.REQUESTING){return;}
this.search.goToPage(page);},selectStartPOI:function(idx,page){if(this.startSelected){return;}
if(page&&page!==this.search.getCurrentPage()){this.indexToSelect=idx;this.goToPage(page);}else{var pois=this.search.getPOIS();if(idx>=pois.length){return;}
this.startSelected=pois[idx];try{this.notifyListeners('startSelected',[pois[idx],idx,page]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}
this.requestPOIS(false);}},selectEndPOI:function(idx,page){if(this.endSelected){return;}
if(page&&page!==this.search.getCurrentPage()){this.indexToSelect=idx;this.goToPage(page);}else{var pois=this.search.getPOIS();if(idx>=pois.length){return;}
this.endSelected=pois[idx];try{this.notifyListeners('endSelected',[pois[idx],idx,page]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}
this.requestDirections();}},clear:function(silent){if(this.panel&&this.div){this.panel.removeChild(this.div);this.div=null;}
this.search.clear();this.directions.clear();if(!silent){try{this.notifyListeners('clean',[this]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}}},cancel:function(){this.search.cancel();this.directions.cancel();this.status=SAPO.Maps.Request.Status.CANCELED;try{this.notifyListeners('canceled',[this]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}},getDirections:function(){if(this.status==SAPO.Maps.Request.Status.OK){return this.directions;}
return null;},getSearch:function(){return this.search;},selectResult:function(idx,page){if(this.status!==SAPO.Maps.Request.Status.OK&&this.status!==SAPO.Maps.Request.Status.REQUESTING){return;}
if(!this.startSelected||!this.endSelected){if(page&&page!==this.search.getCurrentPage()){this.indexToShowDetails=idx;this.goToPage(page);}else{this.search.openDetails(idx);}
try{this.notifyListeners('resultSelect',[idx,this.search.getCurrentPage()]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}}else{if(this.status===SAPO.Maps.Request.Status.OK){this.directions.openPopup(idx);}}},unselectResult:function(idx){if(this.status!==SAPO.Maps.Request.Status.OK&&this.status!==SAPO.Maps.Request.Status.REQUESTING){return;}
if(this.status===SAPO.Maps.Request.Status.OK){this.directions.closePopup(idx);}else{this.search.unselectResult(idx);try{this.notifyListeners('resultUnselect',[idx]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}}},getResultSelected:function(){if(this.status===SAPO.Maps.Request.Status.OK){return this.directions.currentStepIdx;}
return this.search.getSelectedIndex();},requestPOIS:function(isStart){this.clear(isStart);var query=isStart?this.from:this.to;var isCoords=SAPO.Maps.Utils.checkQuery(query);this.search.search(query,{allowPaging:this.allowPaging,displaySingleResult:false});},requestDirections:function(){this.clear(false);var start=new OpenLayers.LonLat(this.startSelected.Longitude,this.startSelected.Latitude);var end=new OpenLayers.LonLat(this.endSelected.Longitude,this.endSelected.Latitude);this.directions.getDirections(start,end,{language:this.language,mode:this.mode,description:this.description,showMapCheckbox:this.showMapCheckbox,middlePoints:this.middlePoints});},prepareRequest:function(){this.clear(true);this.from=null;this.to=null;this.startSelected=false;this.endSelected=false;this.description="text";this.showMapCheckbox=false;},completedSearch:function(s,pois){var isStart=!this.startSelected;if(pois.length===0){this.status=SAPO.Maps.Request.ERROR;try{this.notifyListeners('noresults',isStart);}
catch(e){try{this.notifyListeners('error',[this,e]);}catch(e1){}}
return;}
if(pois.length>1&&this.panel){var msg=isStart?'Seleccione o ponto de partida':'Seleccione o ponto de chegada';var elem=document.createElement('h1');elem.className='itineraries_results_smapi_h1';elem.innerHTML=msg;this.panel.insertBefore(elem,this.panel.firstChild);this.div=elem;}
var eventType=isStart?'startingPOIS':'endingPOIS';try{this.notifyListeners(eventType,[this,pois]);}
catch(e2){try{this.notifyListeners('error',[this,e2]);}catch(e3){}}
if(pois.length==1){this.resultSelectedOnPanel(this.search,pois[0],0,this.search.getCurrentPage());}},resultSelectedOnMap:function(s,poi,idx,page){s.openDetails(idx);try{this.notifyListeners('resultSelect',[idx,page]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}},resultSelectedOnPanel:function(s,poi,idx,page){var isStart=!this.startSelected;var eventType='';if(isStart){eventType='startSelected';this.startSelected=poi;this.requestPOIS(false);}else{eventType='endSelected';this.endSelected=poi;if(this.startSelected.Latitude===this.endSelected.Latitude&&this.startSelected.Longitude===this.endSelected.Longitude){var elem=document.createElement('div');elem.className='search_results_smapi';SAPO.Maps.Utils.displayMessageHTML(elem,"Não é possível calcular um itinerário com o mesmo ponto de partida e chegada.","","",SAPO.Maps.Utils.MessageType.WARNING);this.panel.appendChild(elem);this.status=SAPO.Maps.Request.Status.ERROR;}else{this.requestDirections();}}
try{this.notifyListeners(eventType,[poi,idx,page]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}},unselectSearchResult:function(s,poi,idx,page){try{this.notifyListeners('resultUnselect',[idx,page]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}},pageChanged:function(s,page){if(this.indexToSelect!==null){if(!this.startSelected){this.selectStartPOI(this.indexToSelect);}
else{this.selectEndPOI(this.indexToSelect);}
this.indexToSelect=null;}
if(this.indexToShowDetails!==null){this.selectResult(this.indexToShowDetails);this.indexToShowDetails=null;}
try{this.notifyListeners('pageChanged',[page]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}},completedDirections:function(){this.status=SAPO.Maps.Request.Status.OK;try{this.notifyListeners('complete',[this.directions]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}},timeout:function(){this.status=SAPO.Maps.Request.Status.ERROR;try{this.notifyListeners('timeout',[this]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}},itineraryNotFound:function(){this.status=SAPO.Maps.Request.Status.ERROR;try{this.notifyListeners('itinerarynotfound',[this]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}},directionsStepSelected:function(directions,StepIdx){this.selectedResult=StepIdx;try{this.notifyListeners('resultSelect',[StepIdx]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}},directionsStepUnselected:function(directions,StepIdx){this.selectedResult=null;try{this.notifyListeners('resultUnselect',[StepIdx]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}},startEndMarkerMoved:function(directions,positions,start){try{this.notifyListeners('startEndMarkerMoved',[this,positions,start]);}
catch(e1){try{this.notifyListeners('error',[this,e1]);}
catch(e2){}}},registerEvent:function(eventType,context,func){if(!this.listeners[eventType]){this.listeners[eventType]=[];}
var obj={func:func,context:context};this.listeners[eventType].push(obj);},unRegisterEvent:function(eventType,context,func){var evts=this.listeners[eventType]?this.listeners[eventType]:[];for(var i=0;i<evts.length;++i){if(context==evts[i].context&&func==evts[i].func){evts.splice(i,1);return true;}}
return false;},notifyListeners:function(eventType,args){var evts=this.listeners[eventType]?this.listeners[eventType]:[];args=args?args:[];var func,context;for(var i=0;i<evts.length;++i){func=evts[i].func;context=evts[i].context;func.apply(context,args);}},EVENT_TYPES:['startingPOIS','endingPOIS','complete','error','timeout','startSelected','endSelected','clean','canceled','noresults','itinerarynotfound','resultSelect','resultUnselect','pageChanged','startEndMarkerMoved'],CLASS_NAME:'SAPO.Maps.Itineraries'});SAPO.Maps.WindowManager=OpenLayers.Class({map:null,windows:null,windowControls:null,borders:null,events:null,id:1,resizeFunction:null,initializing:true,archipelagosWindows:null,windowHeadersVisible:true,windowOpacity:1,windowsColors:null,EVENT_TYPES:["windowopened","windowclosed","windowremoved","windowcreated"],initialize:function(map,options){this.borders={left:0,top:0,right:0,bottom:0};this.map=map;this.events=new OpenLayers.Events(this,this.div,this.EVENT_TYPES,true,null);this.windows=[];this.windowControls=[];this.resizeFunction=OpenLayers.Function.bind(this.calculateDimensionsAndOffsets,this,true);OpenLayers.Event.observe(window,"resize",this.resizeFunction);map.events.register('changebaselayer',this,this.baseLayerChanged);OpenLayers.Util.extend(this,options);this.archipelagosWindows={};map.events.register('ondestroy',this,this.destroy);},destroy:function(){OpenLayers.Event.stopObserving(window,"resize",this.resizeFunction);this.resizeFunction=null;this.removeAllWindows();this.map.events.unregister('ondestroy',this,this.destroy);this.map.events.unregister('changebaselayer',this,this.baseLayerChanged);this.map=null;this.events.destroy();this.events=null;},createWindow:function(windowTitle,lonlat,zoom,percentages,startsVisible){this.initializing=true;var windowId=this.id++;var callbacks={scope:this,endMove:OpenLayers.Function.bind(this.windowMoved,this,windowId),endResize:OpenLayers.Function.bind(this.windowResized,this,windowId),closed:OpenLayers.Function.bind(this.windowClosed,this,windowId),opened:OpenLayers.Function.bind(this.windowOpened,this,windowId)};var div=document.createElement('div');var map=new SAPO.Maps.Map(div,{unloadFirst:true});var func=OpenLayers.Function.bind(this.mapMoved,this,windowId);var destroyFunc=OpenLayers.Function.bind(this.removeWindow,this,windowId);map.events.register('moveend',this,func);map.events.register('ondestroy',this,destroyFunc);SAPO.Maps.Utils.removeMapControls(map);var window=new SAPO.Maps.Control.Window(windowTitle,div,null,callbacks,{hidden:true,headerVisible:this.windowHeadersVisible,opacity:this.windowOpacity,color:this.windowsColors});this.map.addControl(window);var obj={id:windowId,map:map,windowControl:window,percentages:percentages,lonlat:lonlat,zoom:zoom,moveendFunction:func,mapDestroyFunc:destroyFunc};this.windows.push(obj);this.windowControls.push(window);window.getWindow().style.visibility='hidden';this.calculateWindowDimensionsAndOffsets(obj);window.getWindow().style.visibility='visible';if(startsVisible){window.show();this.centerMap(obj);}
var style=this.map.getBaseLayers().TERRITORY_MAP.getLayerStyle();map.getBaseLayers().TERRITORY_MAP.setLayerStyle(style);var layerKey=this.getMapLayerKey();map.setBaseLayer(map.getBaseLayers()[layerKey]);this.initializing=false;this.events.triggerEvent("windowcreated",{id:windowId,window:obj});return obj.id;},createAcoresWindow:function(percentages,startsVisible){if(!this.archipelagosWindows.acores){var perc=OpenLayers.Util.extend({height:0.45,width:0.35,left:0.015,top:0.033},percentages);this.archipelagosWindows.acores=this.createWindow("Arquipélago dos Açores",new OpenLayers.LonLat(-27.748722030467,38.674237550912),6,perc,startsVisible);}
return this.archipelagosWindows.acores;},createMadeiraWindow:function(percentages,startsVisible){if(!this.archipelagosWindows.madeira){var perc=OpenLayers.Util.extend({height:0.45,width:0.35,left:0.015,top:0.50},percentages);this.archipelagosWindows.madeira=this.createWindow("Arquipélago da Madeira",new OpenLayers.LonLat(-17.168888046517,32.765896783951),7,perc,startsVisible);}
return this.archipelagosWindows.madeira;},openWindow:function(id){var window=this.getWindowById(id);window.windowControl.show();this.centerMap(window);this.events.triggerEvent('windowopened',{id:id});},closeWindow:function(id){var window=this.getWindowById(id);window.windowControl.hide();this.events.triggerEvent('windowclosed',{id:id});},removeWindow:function(id){var window=this.getWindowById(id);this.events.triggerEvent("windowremoved",{id:id,window:window});window.map.events.unregister('moveend',this,window.moveendFunction);window.map.events.unregister('moveend',this,window.mapDestroyFunc);if(!window.map.beingDestroyed){window.map.destroy();this.map.removeControl(window.windowControl);window.windowControl.destroy();window.windowControl=null;}else{var mainMap=this.map;var timer=setTimeout(function(){mainMap.removeControl(window.windowControl);window.windowControl.destroy();window.windowControl=null;},0);}
OpenLayers.Util.removeItem(this.windowControls,window.windowControl);window.lonlat=null;window.id=null;window.zoom=null;window.map=null;window.moveendFunction=null;window.mapDestroyFunc=null;OpenLayers.Util.removeItem(this.windows,window);if(this.archipelagosWindows.acores==id){delete this.archipelagosWindows.acores;}
if(this.archipelagosWindows.madeira==id){delete this.archipelagosWindows.madeira;}},openAllWindows:function(){var window=false;for(var i=0,len=this.windows.length;i<len;++i){window=this.windows[i];this.openWindow(window.id);}},closeAllWindows:function(){var window=false;for(var i=0,len=this.windows.length;i<len;++i){window=this.windows[i];this.closeWindow(window.id);}},removeAllWindows:function(){var window=false;for(var i=this.windows.length-1;i>=0;--i){window=this.windows[i];this.removeWindow(window.id);}},getWindowById:function(id){var window=false;for(var i=0,len=this.windows.length;i<len;++i){window=this.windows[i];if(window.id==id){return window;}}
return null;},getAcoresWindow:function(){return this.getWindowById(this.archipelagosWindows.acores);},getMadeiraWindow:function(){return this.getWindowById(this.archipelagosWindows.madeira);},getWindowsWithIds:function(){return this.windows;},getWindows:function(){return this.windowControls;},getAcoresWindowId:function(){return this.archipelagosWindows.acores;},getMadeiraWindowId:function(){return this.archipelagosWindows.madeira;},setWindowsOpacity:function(opacity){this.windowOpacity=opacity;var window=false;for(var i=0,len=this.windowControls.length;i<len;++i){window=this.windowControls[i];window.setWindowOpacity(opacity);}},getWindowsOpacity:function(){return this.windowOpacity;},setWindowsColor:function(color){this.windowsColors=color;var window=false;for(var i=0,len=this.windowControls.length;i<len;++i){window=this.windowControls[i];window.setWindowColor(color);}},getWindowsColor:function(){return this.windowsColors;},toggleHeaderAndFooter:function(show){this.windowHeadersVisible=show;var window=false;for(var i=0,len=this.windowControls.length;i<len;++i){window=this.windowControls[i];if(show){window.showHeaderAndFooter();}else{window.hideHeaderAndFooter();}}},isHeaderAndFooterVisible:function(){return this.windowHeadersVisible;},setBorders:function(borders){this.borders=borders;this.calculateDimensionsAndOffsets();},centerMap:function(window){window.map.setMapCenter(window.lonlat,window.zoom);},calculateWindowDimensionsAndOffsets:function(window){var mapHeight=this.map.div.offsetHeight-this.borders.top-this.borders.bottom,mapWidth=this.map.div.offsetWidth-this.borders.left-this.borders.right,windowHeight=mapHeight*window.percentages.height,windowWidth=mapWidth*window.percentages.width;var windowControl=window.windowControl;window.map.div.style.height=(windowHeight-windowControl.getWindowDefaultSize().h<0?0:windowHeight-windowControl.getWindowDefaultSize().h)+"px";window.map.div.style.width=windowWidth+"px";windowControl.setWindowSize({w:windowWidth,h:windowHeight});this.calculateOffsets(window);},calculateOffsets:function(window){var mapHeight=this.map.div.offsetHeight-this.borders.top-this.borders.bottom,mapWidth=this.map.div.offsetWidth-this.borders.left-this.borders.right,left=(mapWidth*window.percentages.left)+this.borders.left,top=(mapHeight*window.percentages.top)+this.borders.top;var windowControl=window.windowControl;windowControl.setWindowPosition({x:left,y:top});},getMapLayerKey:function(){var selectedLayer=this.map.baseLayer;var layerKey=false;var MapLayers=this.map.getBaseLayers();for(var l in MapLayers){if(selectedLayer.name===MapLayers[l].name){layerKey=l;break;}}
return layerKey;},windowMoved:function(windowId,windowControl,windowPixel){var window=this.getWindowById(windowId);var mapHeight=this.map.div.offsetHeight-this.borders.top-this.borders.bottom,mapWidth=this.map.div.offsetWidth-this.borders.left-this.borders.right;window.percentages.left=(windowControl.getWindow().offsetLeft-this.borders.left)/mapWidth;window.percentages.top=(windowControl.getWindow().offsetTop-this.borders.top)/mapHeight;this.centerMap(window);},windowResized:function(windowId,windowControl,windowSize){var window=this.getWindowById(windowId);var mapHeight=this.map.div.offsetHeight-this.borders.top-this.borders.bottom,mapWidth=this.map.div.offsetWidth-this.borders.left-this.borders.right;window.percentages.width=windowSize.w/mapWidth;window.percentages.height=windowSize.h/mapHeight;window.map.div.style.height=windowSize.h-windowControl.getWindowDefaultSize().h+"px";window.map.div.style.width=windowSize.w+"px";this.centerMap(window);},windowClosed:function(windowId){this.events.triggerEvent('windowclosed',{id:windowId});},windowOpened:function(windowId){var window=this.getWindowById(windowId);this.calculateWindowDimensionsAndOffsets(window);},mapMoved:function(windowId){if(this.initializing){return;}
var window=this.getWindowById(windowId);if(window.windowControl.isHidden()){return;}
window.lonlat=window.map.getMapCenter();window.zoom=window.map.getZoom();},calculateDimensionsAndOffsets:function(){var window=false;for(var i=0,len=this.windows.length;i<len;++i){window=this.windows[i];this.calculateWindowDimensionsAndOffsets(window);}},baseLayerChanged:function(){if(!this.windows){return;}
var layerKey=this.getMapLayerKey();var map=false;for(var i=0,len=this.windows.length;i<len;++i){map=this.windows[i].map;map.setBaseLayer(map.getBaseLayers()[layerKey]);}},CLASS_NAME:'SAPO.Maps.WindowManager'});OpenLayers.Control.Navigation.prototype.currZoom=null;OpenLayers.Control.Navigation.prototype.currCenter=null;OpenLayers.Control.Navigation.prototype.wheelChange=function(evt,deltaZ){if(!this.currZoom){this.currZoom=this.map.getZoom();}
var newZoom=this.currZoom+deltaZ;if(!this.map.isValidZoomLevel(newZoom)){return;}
var size=this.map.getSize();var deltaX=size.w/2-evt.xy.x;var deltaY=evt.xy.y-size.h/2;var newRes=this.map.baseLayer.getResolutionForZoom(newZoom);var zoomPoint=this.map.getLonLatFromPixel(evt.xy);var newCenter=new OpenLayers.LonLat(zoomPoint.lon+deltaX*newRes,zoomPoint.lat+deltaY*newRes);this.currZoom=newZoom;this.currCenter=newCenter;this.initTimerToLoadTiles();};OpenLayers.Control.Navigation.prototype.wheelIdTimer=null;OpenLayers.Control.Navigation.prototype.reloadTime=100;OpenLayers.Control.Navigation.prototype.initTimerToLoadTiles=function(){var _this=this;if(this.wheelIdTimer){return;}
this.wheelIdTimer=window.setTimeout(function(){_this.map.setCenter(_this.currCenter,_this.currZoom);window.clearTimeout(_this.wheelIdTimer);_this.wheelIdTimer=null;_this.currZoom=null;},this.reloadTime);};OpenLayers.Control.Navigation.prototype.borders=null;OpenLayers.Control.Navigation.prototype.initialize=function(options){if(options&&options.borders){this.borders=options.borders;}
else{this.borders={left:0,top:0,bottom:0,right:0};}
this.handlers={};OpenLayers.Control.prototype.initialize.apply(this,arguments);};OpenLayers.Control.Navigation.prototype.defaultDblClick=function(evt){var zoomPoint=this.map.getLonLatFromContainerPixel(evt.xy);this.map.setMapCenter(zoomPoint,this.map.zoom+1);var res=this.map.baseLayer.getResolutionForZoom(this.map.zoom);var deltaLonLat=new OpenLayers.LonLat(((this.borders.left-this.borders.right)/2)*res,((this.borders.top-this.borders.bottom)/2)*res);deltaLonLat.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));var zoomPoint_corrected=new OpenLayers.LonLat(zoomPoint.lon-deltaLonLat.lon,zoomPoint.lat+deltaLonLat.lat);this.map.setMapCenter(zoomPoint_corrected);};OpenLayers.Control.Navigation.prototype.defaultDblRightClick=function(evt){var zoomPoint=this.map.getLonLatFromContainerPixel(evt.xy);this.map.setMapCenter(zoomPoint,this.map.zoom-1);var res=this.map.baseLayer.getResolutionForZoom(this.map.zoom);var deltaLonLat=new OpenLayers.LonLat(((this.borders.left-this.borders.right)/2)*res,((this.borders.top-this.borders.bottom)/2)*res);deltaLonLat.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));var zoomPoint_corrected=new OpenLayers.LonLat(zoomPoint.lon-deltaLonLat.lon,zoomPoint.lat+deltaLonLat.lat);this.map.setMapCenter(zoomPoint_corrected);};OpenLayers.Control.KeyboardDefaults.prototype.destroy=function(){if(this.handler){this.handler.destroy();}
this.handler=null;OpenLayers.Control.prototype.destroy.apply(this,arguments);};OpenLayers.Control.KeyboardDefaults.prototype.borders=null;OpenLayers.Control.KeyboardDefaults.prototype.setFocusFunc=null;OpenLayers.Control.KeyboardDefaults.prototype.remFocusFunc=null;OpenLayers.Control.KeyboardDefaults.prototype.activate=function(){OpenLayers.Control.prototype.activate.apply(this,arguments);this.setFocusFunc=OpenLayers.Function.bindAsEventListener(this.setFocus,this);this.remFocusFunc=OpenLayers.Function.bindAsEventListener(this.remFocus,this);OpenLayers.Event.observe(document.body,'click',this.remFocusFunc,false);OpenLayers.Event.observe(this.map.div,'click',this.setFocusFunc,false);};OpenLayers.Control.KeyboardDefaults.prototype.deactivate=function(){OpenLayers.Control.prototype.deactivate.apply(this,arguments);OpenLayers.Event.stopObserving(document.body,'click',this.remFocusFunc,false);OpenLayers.Event.stopObserving(this.map.div,'click',this.setFocusFunc,false);};OpenLayers.Control.KeyboardDefaults.prototype.focus=true;OpenLayers.Control.KeyboardDefaults.prototype.setFocus=function(e){document.activeElement.blur();this.map.div.focus();this.focus=true;OpenLayers.Event.stop(e);};OpenLayers.Control.KeyboardDefaults.prototype.remFocus=function(e){this.focus=false;};OpenLayers.Control.KeyboardDefaults.prototype.defaultKeyPress=function(evt){if(!this.focus||(document.body!==document.activeElement&&this.map.div!=document.activeElement)){return;}
var size=false;switch(evt.keyCode){case OpenLayers.Event.KEY_LEFT:this.map.pan(-this.slideFactor,0);OpenLayers.Event.stop(evt);break;case OpenLayers.Event.KEY_RIGHT:this.map.pan(this.slideFactor,0);OpenLayers.Event.stop(evt);break;case OpenLayers.Event.KEY_UP:this.map.pan(0,-this.slideFactor);OpenLayers.Event.stop(evt);break;case OpenLayers.Event.KEY_DOWN:this.map.pan(0,this.slideFactor);OpenLayers.Event.stop(evt);break;case 33:size=this.map.getSize();this.map.pan(0,-0.75*size.h);OpenLayers.Event.stop(evt);break;case 34:size=this.map.getSize();this.map.pan(0,0.75*size.h);OpenLayers.Event.stop(evt);break;case 35:size=this.map.getSize();this.map.pan(0.75*size.w,0);OpenLayers.Event.stop(evt);break;case 36:size=this.map.getSize();this.map.pan(-0.75*size.w,0);OpenLayers.Event.stop(evt);break;case 43:case 61:case 187:case 107:this.wheelChange(1);OpenLayers.Event.stop(evt);break;case 45:case 109:case 189:case 95:this.wheelChange(-1);OpenLayers.Event.stop(evt);break;}};OpenLayers.Control.KeyboardDefaults.prototype.wheelChange=function(deltaZ){var newZoom=this.map.getZoom()+deltaZ;if(!this.map.isValidZoomLevel(newZoom)){return;}
if(!this.borders){this.map.zoomTo(newZoom);return;}
var size=this.map.getSize();var right=size.w-this.borders.right;var bottom=size.h-this.borders.bottom;var pixel_center_x=((right-this.borders.left)/2)+this.borders.left;var pixel_center_y=((bottom-this.borders.top)/2)+this.borders.top;var mapCenterConsideringBorders=new OpenLayers.Pixel(pixel_center_x,pixel_center_y);var deltaX=size.w/2-pixel_center_x;var deltaY=pixel_center_y-size.h/2;var newRes=this.map.baseLayer.getResolutionForZoom(newZoom);var zoomPoint=this.map.getLonLatFromPixel(mapCenterConsideringBorders);var newCenter=new OpenLayers.LonLat(zoomPoint.lon+deltaX*newRes,zoomPoint.lat+deltaY*newRes);this.map.setCenter(newCenter,newZoom);};OpenLayers.Renderer.VML.prototype.drawLine=function(node,geometry,closeLine){this.setNodeDimension(node,geometry);var resolution=this.getResolution();var numComponents=geometry.components.length;var parts=new Array(numComponents);var comp,x,y,lastx=false,lasty=false;var bounds=this.map.getExtent();var bounds=this.map.getExtent();var w=(bounds.right-bounds.left)/2;var h=(bounds.top-bounds.bottom)/2;bounds.left-=w;bounds.right+=w
bounds.top+=h;bounds.bottom-=h;var prev_out=true;var drawAll=true;var comp2=false;var extent=this.map.getExtent();for(var i=0;i<numComponents;i++){comp=geometry.components[i];x=(comp.x/resolution-this.offset.x);y=(comp.y/resolution-this.offset.y);if((lastx!==false&&lasty!==false)&&(Math.abs(lastx-x)<5&&Math.abs(lasty-y)<5)){continue;}
if(bounds.containsLonLat({lon:comp.x,lat:comp.y})==false){if(!prev_out){prev_out=true;}else{if(i+1>=numComponents)continue;comp2=geometry.components[i+1];if(bounds.containsLonLat({lon:comp2.x,lat:comp2.y})==false){drawAll=false;continue;}}}else{prev_out=false;}
lastx=x;lasty=y;parts[i]=" "+x.toFixed()+","+y.toFixed()+" l ";}
var end=(closeLine)?" x e":" e";node.path="m"+parts.join("")+end;return drawAll?node:null;};OpenLayers.Handler.Click.prototype.rightclick=function(evt){if(this.passesTolerance(evt)){if(this.rightclickTimerId!==null){this.clearTimer();if(this.rightclickTimerId!==null){window.clearTimeout(this.rightclickTimerId);this.rightclickTimerId=null;}
this.callback('dblrightclick',[evt]);return!this.stopDouble;}else{var clickEvent=this.double?OpenLayers.Util.extend({},evt):this.callback('rightclick',[evt]);var delayedRightCall=OpenLayers.Function.bind(this.delayedRightCall,this,clickEvent);this.rightclickTimerId=window.setTimeout(delayedRightCall,this.delay);}}
return!this.stopSingle;};OpenLayers.Renderer.SVG.prototype.drawText=function(featureId,style,location){var resolution=this.getResolution();var x=(location.x/resolution+this.left)+(style.labelXOffset?style.labelXOffset:0);var y=(location.y/resolution-this.top)-(style.labelYOffset?style.labelYOffset:0);var label=this.nodeFactory(featureId+this.LABEL_ID_SUFFIX,"text");var tspan=this.nodeFactory(featureId+this.LABEL_ID_SUFFIX+"_tspan","tspan");label.setAttributeNS(null,"x",x);label.setAttributeNS(null,"y",-y);label.setAttributeNS(null,"pointer-events","none");label.setAttributeNS(null,"opacity",style.labelOpacity);if(style.fontColor){label.setAttributeNS(null,"fill",style.fontColor);}
if(style.fontFamily){label.setAttributeNS(null,"font-family",style.fontFamily);}
if(style.fontSize){label.setAttributeNS(null,"font-size",style.fontSize);}
if(style.fontWeight){label.setAttributeNS(null,"font-weight",style.fontWeight);}
var align=style.labelAlign||"cm";label.setAttributeNS(null,"text-anchor",OpenLayers.Renderer.SVG.LABEL_ALIGN[align[0]]||"middle");if(this.isGecko){label.setAttributeNS(null,"dominant-baseline",OpenLayers.Renderer.SVG.LABEL_ALIGN[align[1]]||"central");}
else{tspan.setAttributeNS(null,"baseline-shift",OpenLayers.Renderer.SVG.LABEL_VSHIFT[align[1]]||"-35%");}
tspan.textContent=style.label;if(!label.parentNode){label.appendChild(tspan);this.textRoot.appendChild(label);}};OpenLayers.Renderer.VML.prototype.drawText=function(featureId,style,location){var label=this.nodeFactory(featureId+this.LABEL_ID_SUFFIX,"olv:rect");var textbox=this.nodeFactory(featureId+this.LABEL_ID_SUFFIX+"_textbox","olv:textbox");var resolution=this.getResolution();label.style.left=(location.x/resolution-this.offset.x-(style.labelXOffset?style.labelXOffset:0)).toFixed()+"px";label.style.top=(location.y/resolution-this.offset.y-(style.labelYOffset?style.labelYOffset:0)).toFixed()+"px";label.style.flip="y";textbox.innerText=style.label;textbox.style.filter="alpha(opacity="+(style.labelOpacity*100)+")";if(style.fillColor){textbox.style.color=style.fontColor;}
if(style.fontFamily){textbox.style.fontFamily=style.fontFamily;}
if(style.fontSize){textbox.style.fontSize=style.fontSize;}
if(style.fontWeight){textbox.style.fontWeight=style.fontWeight;}
textbox.style.whiteSpace="nowrap";textbox.inset="1px,0px,0px,0px";if(!label.parentNode){label.appendChild(textbox);this.textRoot.appendChild(label);}
var align=style.labelAlign||"cm";var xshift=textbox.clientWidth*(OpenLayers.Renderer.VML.LABEL_SHIFT[align.substr(0,1)]);var yshift=textbox.clientHeight*(OpenLayers.Renderer.VML.LABEL_SHIFT[align.substr(1,1)]);label.style.left=parseInt(label.style.left)-xshift-1+"px";label.style.top=parseInt(label.style.top)+yshift+"px";};OpenLayers.Tile.Image.prototype.destroy=function(){if(this.imgDiv){if(this.layerAlphaHack){OpenLayers.Event.stopObservingElement(this.imgDiv.childNodes[0].id);}
OpenLayers.Event.stopObservingElement(this.imgDiv);if(this.imgDiv.parentNode==this.frame){this.frame.removeChild(this.imgDiv);this.imgDiv.map=null;}
this.imgDiv.urls=null;this.imgDiv.src=OpenLayers.Util.getImagesLocation()+"blank.gif";}
this.imgDiv=null;if(this.frame&&(this.frame.parentNode==this.layer.div)){this.layer.div.removeChild(this.frame);}
this.frame=null;if(this.backBufferTile){this.backBufferTile.destroy();this.backBufferTile=null;}
this.layer.events.unregister("loadend",this,this.resetBackBuffer);OpenLayers.Tile.prototype.destroy.apply(this,arguments);};OpenLayers.Size.prototype.equals=function(sz){var equals=false;if(sz){equals=((this.w==sz.w&&this.h==sz.h)||(isNaN(this.w)&&isNaN(this.h)&&isNaN(sz.w)&&isNaN(sz.h)))||(isNaN(this.w)&&isNaN(sz.w)&&this.h==sz.h)||(isNaN(this.h)&&isNaN(sz.h)&&this.w==sz.w);}
return equals;};SAPO.Maps.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=!isNaN(parseInt(this.div.style.width))?parseInt(this.div.style.width):size.w;size.h=!isNaN(parseInt(this.div.style.height))?parseInt(this.div.style.height):size.h;}
return size;};OpenLayers.Layer.TileCache.prototype.getURL=function(bounds){var res=this.map.getResolution();var bbox=this.maxExtent;var size=this.tileSize;var tileX=Math.round((bounds.left-bbox.left)/(res*size.w));var tileY=Math.round((bounds.bottom-bbox.bottom)/(res*size.h));var tileZ=this.serverResolutions!==null?OpenLayers.Util.indexOf(this.serverResolutions,res):this.map.getZoom();function zeroPad(number,length){number=String(number);var zeros=[];for(var i=0;i<length;++i){zeros.push('0');}
return zeros.join('').substring(0,length-number.length)+number;}
var components=[this.layername,zeroPad(tileZ,2),zeroPad(parseInt(tileX/1000000),3),zeroPad((parseInt(tileX/1000)%1000),3),zeroPad((parseInt(tileX)%1000),3),zeroPad(parseInt(tileY/1000000),3),zeroPad((parseInt(tileY/1000)%1000),3),zeroPad((parseInt(tileY)%1000),3)+'.'+this.extension];var path=components.join('/');var url=this.url;if(url instanceof Array){url=this.selectUrl(path,url);}
url=(url.charAt(url.length-1)=='/')?url:url+'/';return url+path+'?new';};if(typeof(SAPO)=='undefined'){window.SAPO={};}else{window.SAPO=window.SAPO;}
SAPO.namespace=function(ns){if(!ns||!ns.length){return null;}
var levels=ns.split(".");var nsobj=SAPO;for(var i=(levels[0]=="SAPO")?1:0;i<levels.length;++i){nsobj[levels[i]]=nsobj[levels[i]]||{};nsobj=nsobj[levels[i]];}
return nsobj;};SAPO.verify=function(ns,minVersion){if(!ns){return;}
var levels=ns.split(".");var nsobj=SAPO;for(var k=levels[0]=='SAPO'?1:0,m=levels.length;k<m;k++){nsobj=nsobj[levels[k]];if(!nsobj)
throw new Error('SAPO.verify: '+ns+' not found');}
if(!minVersion)
return;if(typeof nsobj=='function')
nsobj=nsobj.prototype;var lhs=String(nsobj.version).match(/\d+/g)||[0];var rhs=String(minVersion).match(/\d+/g)||[0];for(var k=0,m=Math.min(lhs.length,rhs.length);k<m;k++){if(lhs[k]<rhs[k])
throw new Error('SAPO.verify: '+ns+' has low version ('+nsobj.version+' < '+minVersion+')');}
if(lhs.length<rhs.length)
throw new Error('SAPO.verify: '+ns+' has low version ('+nsobj.version+' < '+minVersion+')');};SAPO.Class=function(name,baseClass,properties){var derivedFunction=function(){if(this.__dont_init)
return;if(this==window||!this)
throw new Error('Call "new '+name+'(...);"');if(derivedFunction.abstract)
throw new Error("Abstract class: don't instantiate");if(baseClass){var abstractBackup=baseClass.abstract;if(abstractBackup)
baseClass.abstract=false;baseClass.apply(this,arguments);if(abstractBackup)
baseClass.abstract=abstractBackup;}
if(properties&&typeof properties.init=='function')
properties.init.apply(this,arguments);};derivedFunction.name=derivedFunction.displayName=name;derivedFunction.abstract=properties.abstract;if(baseClass){baseClass.prototype.__dont_init=1;derivedFunction.prototype=new baseClass();delete baseClass.prototype.__dont_init;}
derivedFunction.prototype.toString=function(){return'[object '+name+']';}
if(properties)
SAPO.extendObj(derivedFunction.prototype,properties);return derivedFunction;};SAPO.safeCall=function(object,listener){function rethrow(exception){setTimeout(function(){if(exception.message){exception.message+='\n'+(exception.stacktrace||exception.stack||'');}
throw exception;},1);}
if(object==null){object=window;}
if(typeof listener=='string'&&typeof object[listener]=='function'){try{return object[listener].apply(object,[].slice.call(arguments,2));}catch(ex){rethrow(ex);}}else if(typeof listener=='function'){try{return listener.apply(object,[].slice.call(arguments,2));}catch(ex){rethrow(ex);}}else if(typeof object=='function'){try{return object.apply(window,[].slice.call(arguments,1));}catch(ex){rethrow(ex);}}};function s$(element)
{if(arguments.length>1){for(var i=0,elements=[],length=arguments.length;i<length;i++){elements.push(s$(arguments[i]));}
return elements;}
if(typeof(element)=='string'){element=document.getElementById(element);}
return element;}
Function.prototype.bindObj=function(){if(arguments.length<2&&arguments[0]===undefined){return this;}
var __method=this;var args=[];for(var i=0,total=arguments.length;i<total;i++){args.push(arguments[i]);}
var object=args.shift();var fn=function(){return __method.apply(object,args.concat(function(tmpArgs){var args2=[];for(var j=0,total=tmpArgs.length;j<total;j++){args2.push(tmpArgs[j]);}
return args2;}(arguments)));};fn.toString=function(){return String(__method);}
fn.name=fn.displayName=__method.name;return fn;};Function.prototype.bindObjEvent=function(){var __method=this;var args=[];for(var i=0;i<arguments.length;i++){args.push(arguments[i]);}
var object=args.shift();return function(event){return __method.apply(object,[event||window.event].concat(args));};};Object.extend=function(destination,source){for(var property in source){destination[property]=source[property];}
return destination;};SAPO.extendObj=function(destination,source){if(source){for(var property in source){if(source.hasOwnProperty(property)){destination[property]=source[property];}}}
return destination;};if(typeof(SAPO.Browser)=='undefined'){SAPO.Browser={IE:false,GECKO:false,OPERA:false,SAFARI:false,KONQUEROR:false,CHROME:false,model:false,version:false,userAgent:false,init:function()
{this.detectBrowser();this.setDimensions();this.setReferrer();},setDimensions:function()
{var myWidth=0,myHeight=0;if(typeof(window.innerWidth)=='number'){myWidth=window.innerWidth;myHeight=window.innerHeight;}else if(document.documentElement&&(document.documentElement.clientWidth||document.documentElement.clientHeight)){myWidth=document.documentElement.clientWidth;myHeight=document.documentElement.clientHeight;}else if(document.body&&(document.body.clientWidth||document.body.clientHeight)){myWidth=document.body.clientWidth;myHeight=document.body.clientHeight;}
this.windowWidth=myWidth;this.windowHeight=myHeight;},setReferrer:function()
{this.referrer=document.referrer!==undefined?document.referrer.length>0?escape(document.referrer):false:false;},detectBrowser:function()
{var sAgent=navigator.userAgent;this.userAgent=sAgent;sAgent=sAgent.toLowerCase();if((new RegExp("applewebkit\/")).test(sAgent)){if((new RegExp("chrome\/")).test(sAgent)){this.CHROME=true;this.model='chrome';this.version=sAgent.replace(new RegExp("(.*)chrome\/([^\\s]+)(.*)"),"$2");}else{this.SAFARI=true;this.model='safari';this.version=sAgent.replace(new RegExp("(.*)applewebkit\/([^\\s]+)(.*)"),"$2");}}else if((new RegExp("opera")).test(sAgent)){this.OPERA=true;this.model='opera';this.version=sAgent.replace(new RegExp("(.*)opera.([^\\s$]+)(.*)"),"$2");}else if((new RegExp("konqueror")).test(sAgent)){this.KONQUEROR=true;this.model='konqueror';this.version=sAgent.replace(new RegExp("(.*)konqueror\/([^;]+);(.*)"),"$2");}else if((new RegExp("msie\ ")).test(sAgent)){this.IE=true;this.model='ie';this.version=sAgent.replace(new RegExp("(.*)\\smsie\\s([^;]+);(.*)"),"$2");}else if((new RegExp("gecko")).test(sAgent)){this.GECKO=true;var re=new RegExp("(camino|chimera|epiphany|minefield|firefox|firebird|phoenix|galeon|iceweasel|k\-meleon|seamonkey|netscape|songbird|sylera)");if(re.test(sAgent)){this.model=sAgent.match(re)[1];this.version=sAgent.replace(new RegExp("(.*)"+this.model+"\/([^;\\s$]+)(.*)"),"$2");}else{this.model='mozilla';var reVersion=new RegExp("(.*)rv\:([^\)]+)(.*)");if(reVersion.test(sAgent)){this.version=sAgent.replace(reVersion,"$2");}}}},debug:function()
{var str="known browsers: (ie, gecko, opera, safari, konqueror) \n";str+=[this.IE,this.GECKO,this.OPERA,this.SAFARI,this.KONQUEROR]+"\n";str+="model -> "+this.model+"\n";str+="version -> "+this.version+"\n";str+="\n";str+="original UA -> "+this.userAgent;alert(str);}};SAPO.Browser.init();}
SAPO.logReferer=function(classURL){var thisOptions=SAPO.extendObj({s:'js.sapo.pt',swakt:'59a97a5f-0924-3720-a62e-0c44d9ea4f16',pg:false,swasection:false,swasubsection:'',dc:'',ref:false,etype:'libsapojs-view',swav:'1',swauv:'1',bcs:'1',bsr:'1',bul:'1',bje:'1',bfl:'1',debug:false},arguments[1]||{});if(typeof(classURL)!='undefined'&&classURL!=null){if(!thisOptions.pg){thisOptions.pg=classURL;}
if(!thisOptions.swasection){thisOptions.swasection=classURL;}
if(!thisOptions.ref){thisOptions.ref=location.href;}
var waURI='http://wa.sl.pt/wa.gif?';var waURISSL='https://ssl.sapo.pt/wa.sl.pt/wa.gif?';var aQuery=['pg='+encodeURIComponent(thisOptions.pg),'swasection='+encodeURIComponent(thisOptions.swasection),'swasubsection='+encodeURIComponent(thisOptions.swasubsection),'dc='+encodeURIComponent(thisOptions.dc),'s='+thisOptions.s,'ref='+encodeURIComponent(thisOptions.ref),'swakt='+thisOptions.swakt,'etype='+encodeURIComponent(thisOptions.etype),'swav='+encodeURIComponent(thisOptions.swav),'swauv='+encodeURIComponent(thisOptions.swauv),'bcs='+encodeURIComponent(thisOptions.bcs),'bsr='+encodeURIComponent(thisOptions.bsr),'bul='+encodeURIComponent(thisOptions.bul),'bje='+encodeURIComponent(thisOptions.bje),'bfl='+encodeURIComponent(thisOptions.bfl),''];if(location.protocol=='https:'){var waLogURI=waURISSL;}else{var waLogURI=waURI;}
var img=new Image();img.src=waLogURI+aQuery.join('&');}};SAPO._require=function(uri,callBack)
{if(typeof(uri)!='string'){return;}
var script=document.createElement('script');script.type='text/javascript';var aHead=document.getElementsByTagName('HEAD');if(aHead.length>0){aHead[0].appendChild(script);}
if(document.addEventListener){script.onload=function(e){if(typeof(callBack)!='undefined'){callBack();}};}else{script.onreadystatechange=function(e){if(this.readyState=='loaded'){if(typeof(callBack)!='undefined'){callBack();}}};}
script.src=uri;};SAPO.require=function(reqArray,callBack)
{var objectsToCheck=[];var uriToAdd=[];var _isSAPOObject=function(param){if(typeof(param)=='string'){if(/^SAPO\./.test(param)){return true;}}
return false;};var _isObjectUri=function(param){if(typeof(param)=='object'&&param.constructor==Object){if(typeof(param.uri)=='string'){return true;}}
return false;};var _isObjectArray=function(param){if(typeof(param)=='object'&&param.constructor==Array){return true;}
return false;};var _parseSAPOObject=function(param){var aSAPO=param.split('.');var sapoURI=aSAPO.join('/');return'http://js.sapo.pt/'+sapoURI+'/';};var _parseObjectUri=function(param){return param.uri;};var _objectExists=function(objStr,ver){if(typeof(objStr)!='undefined'){var aStrObj=objStr.split('.');var objParent=window;for(var k=0,aStrObjLength=aStrObj.length;k<aStrObjLength;k++){if(typeof(objParent[aStrObj[k]])!='undefined'){objParent=objParent[aStrObj[k]];}else{return false;}}
if(typeof(ver)!='undefined'&&ver!==null){if(typeof(objParent.version)!='undefined'){if(objParent.version==ver){return true;}else{return false;}}else{return true;}}
return true;}};var requestRecursive=function()
{if(uriToAdd.length>1){SAPO._require(uriToAdd[0],requestRecursive);uriToAdd.splice(0,1);}else if(uriToAdd.length==1){if(typeof(callBack)!='undefined'){SAPO._require(uriToAdd[0],callBack);}else{SAPO._require(uriToAdd[0]);}
uriToAdd.splice(0,1);}else if(uriToAdd.length===0){if(typeof(callBack)!='undefined'){callBack();}}};if(typeof(reqArray)!='undefined'){var cur=false;var curURI=false;if(typeof(reqArray)=='string'){if(_isSAPOObject(reqArray)){if(!_objectExists(reqArray)){uriToAdd.push(_parseSAPOObject(reqArray));}}else{uriToAdd.push(reqArray);}}else{for(var i=0,reqArrayLength=reqArray.length;i<reqArrayLength;i++){cur=reqArray[i];if(_isSAPOObject(cur)){if(!_objectExists(cur)){objectsToCheck.push(cur);uriToAdd.push(_parseSAPOObject(cur));}}else if(_isObjectArray(cur)){if(cur.length>0){if(_isSAPOObject(cur[0])){if(!_objectExists(cur[0])){if(cur.length===2){uriToAdd.push(_parseSAPOObject(cur[0])+cur[1]+'/');}else{uriToAdd.push(_parseSAPOObject(cur[0]));}}}}}else{if(typeof(cur)=='string'){uriToAdd.push(cur);}else{if(_isObjectUri(cur)){if(typeof(cur.check)=='string'){if(typeof(cur.version)=='string'){if(!_objectExists(cur.check,cur.version)){uriToAdd.push(_parseObjectUri(cur));}}else{if(!_objectExists(cur.check)){uriToAdd.push(_parseObjectUri(cur));}}}else{uriToAdd.push(_parseObjectUri(cur));}}}}}}
if(arguments.length==3){if(typeof(arguments[2])=='boolean'){if(arguments[2]===true){for(var l=0,uriToAddLength=uriToAdd.length;l<uriToAddLength;l++){SAPO._require(uriToAdd[l]);}
if(typeof(callBack)!='undefined'){callBack();}
return;}}
requestRecursive();}else{requestRecursive();}}};if(!SAPO.Communication||SAPO.Communication===undefined){SAPO.namespace('Communication');}
SAPO.Communication.Syndication=function(url,options){this.init(url,options);};SAPO.Communication.Syndication.version='0.1';SAPO.Communication.Syndication.prototype={init:function(url,opts){this.feeds=[];if(url&&typeof(url)==='string'){var id=this.push(url,opts||{});if(id!==false&&typeof(id)!='undefined'){this.run(id);}}
this._doDebug=false;},push:function(url,opts)
{if(url===undefined){if(this.exception){this.exception.log('Missed URL');}
throw"Missed URL in SAPO.Communication.Syndication";}
try{var options=Object.extend({objectName:false,onComplete:false,onLoading:false,onTimeout:false,onExit:false,timeout:10,optOnComplete:false,optOnLoading:false,optOnTimeout:false,optOnExit:false,charset:'utf-8'},opts||{});this.feeds.push({});this.onStart=false;this.onEnd=false;var id=this.feeds.length-1;this.feeds[id].u=url;this.feeds[id].onComplete=options.onComplete;this.feeds[id].onLoading=options.onLoading;this.feeds[id].onTimeout=options.onTimeout;this.feeds[id].onExit=options.onExit;if(options.objectName){this.feeds[id].obj=options.objectName;}else{if(typeof(SAPO.Utility)!=='undefined'&&typeof(SAPO.Utility.Crypto)!=='undefined'){this.feeds[id].obj='json'+SAPO.Utility.Crypto.md5(this.feeds[id].u);}else{this.feeds[id].obj='json'+Math.round(1000000*Math.random());}}
this.feeds[id].urlJSON=false;this.feeds[id].urlImage=false;this.feeds[id].req=0;this.feeds[id].limitReq=parseInt((options.timeout*1000)/100,10);this.feeds[id].stoReq=false;this.feeds[id].charset=options.charset;this.feeds[id].optionsOnLoading=options.optOnLoading||false;this.feeds[id].optionsOnComplete=options.optOnComplete||false;this.feeds[id].optionsOnTimeout=options.optOnTimeout||false;this.feeds[id].optionsOnExit=options.optOnExit||false;return id;}catch(e){if(this.exception){this.exception.log(e,'push');}}
return false;},run:function(id){if(id!==false&&typeof(id)!='undefined'){try{if(this.feeds[id].onLoading){if(this.feeds[id].optionsOnLoading){this.feeds[id].onLoading(this.feeds[id].optionsOnLoading);}else{this.feeds[id].onLoading();}}
this._setUrl(id);this._createScriptTag(id);}catch(e){this.exception.log(e,'run (ID: '+id+')');}}},runAll:function(onStart,onEnd){if(this.feeds.length>0){this.onStart=onStart||false;if(this.onStart){this.onStart();}
var argToOnEnd=onEnd||false;this.iter=0;this.setInter=setInterval(function(){this.run(this.iter);if(this.iter===(this.feeds.length-1)){this.onEnd=argToOnEnd;}
this.iter++;if(this.iter===this.feeds.length){clearInterval(this.setInter);}}.bindObj(this),300);}},remove:function(id){if(typeof(this.feeds[id])!=='undefined'&&this.feeds[id]!==null){try{this.feeds[id]=null;}catch(e){this.exception.log(e,'delete (ID: '+id+')');}}},removeAll:function(){if(this.feeds.length>0){for(var i=0;i<this.feeds.length;++i){this.remove(i);}}},destroy:function(){for(var i in this){this[i]=null;}},_setUrl:function(id){if(-1<this.feeds[id].u.indexOf('?')){this.feeds[id].urlJSON=this.feeds[id].u+'&jsonTag='+this.feeds[id].obj;}
else{this.feeds[id].urlJSON=this.feeds[id].u+'?jsonTag='+this.feeds[id].obj;}},_createScriptTag:function(id){try{var is_html=!document.documentElement||!document.documentElement.namespaceURI||document.documentElement.namespaceURI=='http://www.w3.org/1999/xhtml';this.feeds[id].script=document.createElement('script');if(is_html){this.feeds[id].script.type='text/javascript';this.feeds[id].script.src=this.feeds[id].urlJSON;this.feeds[id].script.charset=this.feeds[id].charset;(document.getElementsByTagName('head')[0]||document.documentElement).appendChild(this.feeds[id].script);}
else{this.feeds[id].script.setAttributeNS('http://www.w3.org/1999/xlink','href',this.feeds[id].urlJSON);document.documentElement.appendChild(this.feeds[id].script);}
this._callBack(id);}catch(e){if(this.exception){this.exception.log(e,'_createScriptTag');}}},_callBack:function(id){try{if(this.feeds[id].req<this.feeds[id].limitReq){if(this.feeds[id].onComplete){if(this.feeds[id].optionsOnComplete){this.feeds[id].optionsOnComplete.__id=id;this.feeds[id].onComplete(eval(this.feeds[id].obj),this.feeds[id].optionsOnComplete);this._removeScript(id);}
else{this.feeds[id].onComplete(eval(this.feeds[id].obj));this._removeScript(id);}}
if(this.feeds[id].onExit){if(this.feeds[id].optionsOnExit){this.feeds[id].onExit(this.feeds[id].optionsOnExit);}
else{this.feeds[id].onExit();}}
if(this.onEnd&&id==(this.feeds.length-1)){this.onEnd();}}
else{throw"Time out ";}}catch(e){if(this.feeds[id].req<this.feeds[id].limitReq){if(this.feeds[id].stoReq){clearTimeout(this.feeds[id].stoReq);}
this.feeds[id].req++;this.feeds[id].stoReq=setTimeout(function(){this._callBack(id);}.bindObj(this),100);}
else{if(this.exception){this.exception.log(e+' - URI: '+this.feeds[id].urlJSON,'_callBack');}
if(this.feeds[id].onTimeout){if(this.feeds[id].optionsOnTimeout){this.feeds[id].onTimeout(this.feeds[id].optionsOnTimeout);}
else{this.feeds[id].onTimeout();}}
this._removeScript(id);if(this.feeds[id].onExit){if(this.feeds[id].optionsOnExit){this.feeds[id].onExit(this.feeds[id].optionsOnExit);}
else{this.feeds[id].onExit();}}}}},_removeScript:function(id){try{if(this.feeds[id].script.parentNode&&typeof(this.feeds[id].script.parentNode)!='undefined'){this.feeds[id].script.parentNode.removeChild(this.feeds[id].script);}}catch(e){if(this.exception){this.exception.log(e,'_removeScript');}}},_debug:function(txt){if(this._doDebug&&document.getElementById('debug')){document.getElementById('debug').innerHTML+=txt+'<br/>';}}};if(!SAPO.Utility||typeof(SAPO.Utility)=='undefined'){SAPO.namespace('Utility');}
SAPO.Utility.Serialize={_convertToUnicode:true,_toUnicode:function(theString)
{if(!this._convertToUnicode){var _m={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};if(/["\\\x00-\x1f]/.test(theString)){theString=theString.replace(/([\x00-\x1f\\"])/g,function(a,b){var c=_m[b];if(c){return c;}
c=b.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);});}
return theString;}else{var unicodeString='';var inInt=false;var theUnicode=false;var i=0;var charCount=0;var total=theString.length;while(i<total){inInt=theString.charCodeAt(i);if((inInt>=32&&inInt<=126)||inInt==8||inInt==9||inInt==10||inInt==12||inInt==13||inInt==32||inInt==34||inInt==47||inInt==58||inInt==92){if(inInt==34||inInt==92||inInt==47){theUnicode='\\'+theString.charAt(i);}else if(inInt==8){theUnicode='\\b';}else if(inInt==9){theUnicode='\\t';}else if(inInt==10){theUnicode='\\n';}else if(inInt==12){theUnicode='\\f';}else if(inInt==13){theUnicode='\\r';}else{theUnicode=theString.charAt(i);}}else{if(this._convertToUnicode){theUnicode=theString.charCodeAt(i).toString(16)+''.toUpperCase();while(theUnicode.length<4){theUnicode='0'+theUnicode;}
theUnicode='\\u'+theUnicode;}else{theUnicode=theString.charAt(i);}}
unicodeString+=theUnicode;i++;}
return unicodeString;}},_serialize:function(param)
{var formated='';if(typeof(param)=='object'&&param!==null){if(param.constructor==Array){formated='['+this._removeLastComma(this._format(param))+']';}else if(param.constructor==Object){formated='{'+this._removeLastComma(this._format(param))+'}';}
return formated;}else{return param;}},_format:function(param)
{var formated='';var tmpValue=false;var hasKey=false;if(typeof(param)=='object'&&param!==null&&param.constructor==Object){hasKey=true;}
for(var key in param){if(param.hasOwnProperty(key)){tmpValue=param[key];if(tmpValue===null){if(hasKey){formated+='"'+key+'": null,';}else{formated+='null,';}}else if(typeof(tmpValue)=='string'){if(hasKey){formated+='"'+key+'": "'+this._toUnicode(tmpValue)+'",';}else{formated+='"'+this._toUnicode(tmpValue)+'",';}}else if(typeof(tmpValue)=='number'){if(hasKey){formated+='"'+key+'": '+tmpValue+',';}else{formated+=''+tmpValue+',';}}else if(tmpValue===true||tmpValue===false){if(hasKey){formated+='"'+key+'": '+(tmpValue?'true':'false')+',';}else{formated+=''+(tmpValue?'true':'false')+',';}}else if(typeof(tmpValue)=='object'&&tmpValue!==null&&tmpValue.constructor==Array){if(hasKey){formated+='"'+key+'": ['+this._removeLastComma(this._format(tmpValue))+'],';}else{formated+='['+this._removeLastComma(this._format(tmpValue))+'],';}}else if(typeof(tmpValue)=='object'&&tmpValue!==null&&tmpValue.constructor==Object){if(hasKey){formated+='"'+key+'": {'+this._removeLastComma(this._format(tmpValue))+'},';}else{formated+='{'+this._removeLastComma(this._format(tmpValue))+'},';}}}}
return formated;},_removeLastComma:function(string)
{var len=string.length;if(string.substring((len-1),len)==','){return string.substring(0,(len-1));}
return string;},get:function(jsObject,convertToUnicode)
{if(typeof(convertToUnicode)!='undefined'){if(convertToUnicode===false){this._convertToUnicode=false;}else{this._convertToUnicode=true;}}
if(!this._convertToUnicode&&typeof JSON!=="undefined"){return JSON.stringify(jsObject);}
return this._serialize(jsObject);},debug:function(param){}};window.setTimeout(function(){SAPO.logReferer("http://js.sapo.pt/Bundles/SAPOMapsAPI-1.1.js",{s:location.hostname,swakt:"78C1133C-9BF2-41EE-A58D-F5A8B49C2B1A",etype:"libsapojs-maps-view"});},1000);
SAPO.Maps.StatisticsSearch=OpenLayers.Class(SAPO.Maps.GenericSearcher,{getStatisticsBySearch:function(providerUrl,query,pageNumber,recordsPerPage,callbacks){var url=SAPO.Maps.Utils.composeUrl(SAPO.Maps.Statistics.Config.getEndpoint('search'),{providerUrl:encodeURIComponent(providerUrl),text:query,pageNumber:pageNumber,recordsperPage:recordsPerPage});this.request(url,callbacks,true);},getStatisticsThemes:function(providerUrl,callbacks){var url=SAPO.Maps.Utils.composeUrl(SAPO.Maps.Statistics.Config.getEndpoint('themes'),{providerUrl:encodeURIComponent(providerUrl),themeLevel:1});return this.request(url,callbacks);},getSubThemes:function(providerUrl,themeCode,callbacks){var url=SAPO.Maps.Utils.composeUrl(SAPO.Maps.Statistics.Config.getEndpoint('themes'),{providerUrl:encodeURIComponent(providerUrl),themeLevel:2,parentThemeCode:themeCode});return this.request(url,callbacks);},getStatisticsByTheme:function(providerUrl,themeCode,callbacks){var url=SAPO.Maps.Utils.composeUrl(SAPO.Maps.Statistics.Config.getEndpoint('indicatorsByTheme'),{providerUrl:encodeURIComponent(providerUrl),themeCode:themeCode});return this.request(url,callbacks);},CLASS_NAME:'SAPO.Maps.StatisticsRequester'});SAPO.Maps.Statistics=OpenLayers.Class({indicadors:null,tabPanel:null,requester:null,requestId:null,id:1,nameIdGenerator:1,map:null,panel:null,labelsControl:null,labelsControlOpened:true,statisticsShape:null,floatWindowsStatisticsShape:null,EVENT_TYPES:['indicatorRemoved',"indicatorAdded","selectIndicator","labelOpened","labelClosed","panelHidden",'changeIndicator','configureTerritory','popupOpened'],events:null,maxIndicators:2,layerParameters:null,legendDiv:null,buildingPopup:false,windowManager:null,showConfigTerritoryDiv:false,showChangeIndicatorLink:true,showAddIndicatorTab:true,useMessageBoard:true,wroteMessage:false,popup:null,mainMapClickListener:null,floatWindowsClickListeners:null,currentPopupTabIndicator:null,showTemporalDimensionOnPieCharts:true,initialize:function(map,panel,windowManager,options){this.map=map;this.panel=typeof(panel)=='string'?document.getElementById(panel):panel;this.windowManager=windowManager;if(this.panel){var callbacks={scope:this,newTab:this.newTab,tabRemoved:this.removeIndicator};this.tabPanel=new SAPO.Maps.Statistics.Tabs(callbacks,this.panel,{dummyHeader:this.showAddIndicatorTab});}
this.indicators={};this.events=new OpenLayers.Events(this,this.div,this.EVENT_TYPES,true,null);this.requester=SAPO.Maps.Request.prototype.getRequester();if(!this.statisticsShape){this.createShapeTracker();}
this.mainMapClickListener=OpenLayers.Function.bind(this.mapClicked,this,map,this.statisticsShape);map.events.register('addlayer',this,this.setChartsZIndex);map.events.register('removelayer',this,this.setChartsZIndex);map.events.register('click',this,this.mainMapClickListener);if(this.windowManager){this.windowManager.events.register('windowcreated',this,this.newWindowMapAdded);this.windowManager.events.register('windowremoved',this,this.removedWindowMap);this.registerFloatMapsClickEvents();}
this.layerParameters={outlineColor:'0,0,0',showLabels:false};OpenLayers.Util.extend(this,options);map.events.registerPriority('ondestroy',this,this.destroy);if(this.useMessageBoard){this.map.getMessageBoardControl().events.register('closed',this,this.messageBoardClosed);}},destroy:function(){this.map.events.unregister('addlayer',this,this.setChartsZIndex);this.map.events.unregister('removelayer',this,this.setChartsZIndex);this.map.events.unregister('ondestroy',this,this.destroy);this.map.events.unregister('click',this,this.mainMapClickListener);this.mainMapClickListener=null;for(var indicator in this.indicadors){this.removeIndicator(indicator);}
if(this.statisticsShape){this.statisticsShape.destroy();this.statisticsShape=null;}
if(this.floatWindowsStatisticsShape){var statisticShape=false;for(var shapeID in this.floatWindowsStatisticsShape){statisticShape=this.floatWindowsStatisticsShape[shapeID];statisticShape.destroy();delete this.floatWindowsStatisticsShape[shapeID];}
this.floatWindowsStatisticsShape=null;}
if(this.labelsControl){this.map.removeControl(this.labelsControl);this.labelsControl.destroy();this.labelsControl=null;}
if(this.tabPanel){this.tabPanel.destroy();this.tabPanel=null;}
if(this.windowManager){this.windowManager.events.unregister('windowcreated',this,this.newWindowMapAdded);this.windowManager.events.unregister('windowremoved',this,this.removedWindowMap);this.unregisterFloatMapsClickEvents();}
if(this.useMessageBoard){this.map.getMessageBoardControl().events.unregister('closed',this,this.messageBoardClosed);}
this.windowManager=null;this.requester.destroy();this.requester=null;this.map=null;this.panel=null;this.windowManager=null;},addIndicator:function(providerUrl,indicatorID,indicatorOptions){if(!providerUrl){providerUrl=SAPO.Maps.Statistics.Config.currentProvider.endpoint;}
var nrIndicators=SAPO.Maps.Utils.numberOfProperties(this.indicators);if(nrIndicators==this.maxIndicators){var indicatorToReplace=this.getSelectedIndicator();indicatorToReplace.changeIndicator(indicatorID,indicatorOptions);return;}
if(nrIndicators==this.maxIndicators-1&&this.panel){this.tabPanel.removeDummyHeader();}
var panel=false;if(this.panel){panel=document.createElement('div');}
if(!this.labelsControl){this.createLabelsControl();}
var id=this.id++;var nameId=this.nameIdGenerator++;var indicatorName="Indicador "+nameId;var options=OpenLayers.Util.extend({color:this.getIndicatorDifferentColor(),showChangeIndicatorLink:this.showChangeIndicatorLink,showConfigTerritoryDiv:this.showConfigTerritoryDiv,providerUrl:providerUrl,useMessageBoard:this.useMessageBoard,showTemporalDimensionOnPieCharts:this.showTemporalDimensionOnPieCharts},indicatorOptions);var indicator=new SAPO.Maps.Indicator(this.map,panel,indicatorName,indicatorID,this.windowManager,this.labelsControl,options);indicator.setLayerStyle(this.layerParameters);indicator.events.register('changedRepresentation',this,this.checkShapeState);indicator.events.register('indicatorDetailsComplete',this,this.openLabelsControl);indicator.events.register('indicatorDetailsComplete',this,this.addPopupTab);indicator.events.register('changedRepresentation',this,this.checkShapeState);indicator.events.register('resizePopup',this,this.resizePopup);indicator.events.register('chartClicked',this,this.chartClicked);indicator.events.register('indicatorInformationComplete',this,this.indicatorInformationComplete);indicator.events.register('changeIndicatorClicked',this,this.changeIndicator);indicator.events.register('configureTerritoryClicked',this,this.configureTerritory);if(this.useMessageBoard){indicator.events.register('changedRepresentation',this,this.checkRepresentationForMessageBoard);indicator.events.register('colorsChanged',this,this.checkColorsForMessageBoard);}
if(this.tabPanel){id=this.tabPanel.addTab(indicatorName,panel,null,true);this.tabPanel.show();}
this.indicators[id]=indicator;var shapeUrl=SAPO.Maps.Statistics.Config.getEndpoint('shape');if(shapeUrl){this.checkShapeState();}
this.events.triggerEvent('indicatorAdded',{id:indicatorID,indicator:this.indicators[id]});indicator._id=id;return id;},removeIndicator:function(indicatorID){var indicator=this.indicators[indicatorID];indicator.events.unregister('changedRepresentation',this,this.checkShapeState);indicator.events.unregister('indicatorDetailsComplete',this,this.openLabelsControl);indicator.events.unregister('indicatorDetailsComplete',this,this.addPopupTab);indicator.events.unregister('changedRepresentation',this,this.checkShapeState);indicator.events.unregister('resizePopup',this,this.resizePopup);indicator.events.unregister('chartClicked',this,this.chartClicked);indicator.events.unregister('indicatorInformationComplete',this,this.indicatorInformationComplete);indicator.events.unregister('changeIndicatorClicked',this,this.changeIndicator);indicator.events.unregister('configureTerritoryClicked',this,this.configureTerritory);if(this.useMessageBoard){indicator.events.unregister('changedRepresentation',this,this.checkRepresentationForMessageBoard);indicator.events.unregister('colorsChanged',this,this.checkColorsForMessageBoard);}
this.indicators[indicatorID].destroy();delete this.indicators[indicatorID];if(this.tabPanel&&this.tabPanel.hasTabId(indicatorID)){this.tabPanel.removeTab(indicatorID);if(!SAPO.Maps.Utils.hasProperties(this.indicators)){this.events.triggerEvent('panelHidden');this.tabPanel.hide();}}
--this.nameIdGenerator;this.renameIndicators();if(!SAPO.Maps.Utils.hasProperties(this.indicators)){this.labelsControl.hide(true);this.labelsControl.hideMinimizedWindowControl();this.id=1;this.nameIdGenerator=1;}
this.checkShapeState();this.events.triggerEvent('indicatorRemoved',{id:indicatorID,indicator:indicator});this.tabPanel.addDummyHeader();this.removePopupTab(indicator);this.checkRepresentationForMessageBoard();this.checkColorsForMessageBoard();},removeAllIndicators:function(){for(var indicatorID in this.indicators){this.removeIndicator(indicatorID);}},isLabelsControlOpened:function(){return this.labelsControlOpened;},toggleLabelsControl:function(show){this.labelsControlOpened=show;if(show){this.labelsControl.show();}else{this.labelsControl.hide();}
var evt=show?"labelOpened":"labelClosed";this.events.triggerEvent(evt);},getIndicator:function(indicatorID){return this.indicators[indicatorID];},getSelectedIndicator:function(visible){var id=false;if(this.tabPanel){id=this.tabPanel.getSelectedTabId();}else{id=SAPO.Maps.Utils.getLastKey(this.indicators);}
if(!id){return null;}
return this.indicators[id];},getNrIndicators:function(){return SAPO.Maps.Utils.numberOfProperties(this.indicators);},getIndicators:function(){return SAPO.Maps.Utils.object2Array(this.indicators);},setOutlineColor:function(color){this.layerParameters.outlineColor=color;var indicator=false;for(var indicatorID in this.indicators){indicator=this.indicators[indicatorID];indicator.setLayerStyle(this.layerParameters);}},setTerritoryNamesVisibility:function(visible){this.layerParameters.showLabels=visible;var indicator=false;for(var indicatorID in this.indicators){indicator=this.indicators[indicatorID];indicator.setLayerStyle(this.layerParameters);}},setTerritoryCentroid:function(showInCentroid){this.layerParameters.showLabelsInCentroid=showInCentroid;var indicator=false;for(var indicatorID in this.indicators){indicator=this.indicators[indicatorID];indicator.setLayerStyle(this.layerParameters);}},showTerritoryIcons:function(show,url){this.layerParameters.showIcons=show;if(show){this.layerParameters.iconUrl=url;}
var indicator=false;for(var indicatorID in this.indicators){indicator=this.indicators[indicatorID];indicator.setLayerStyle(this.layerParameters);}},openPopup:function(lonlat,selectedIndicator){if(!selectedIndicator){var indicatorKey=SAPO.Maps.Utils.getFirstKey(this.indicators);selectedIndicator=this.indicators[indicatorKey];}
this.openPopupInformation(this.map,lonlat,selectedIndicator);},closePopup:function(){this.removePopup();},isPopupOpened:function(){return this.popup?true:false;},getPopupLonLat:function(){if(this.popup){return this.popup._lonlat;}
return null;},getPopupIndicatorSelected:function(){for(var i in this.indicators){if(this.indicators[i].getIsSelectedTab()){return this.indicators[i];}}
return null;},renameIndicators:function(){var indicator=false,name=false,id=1;for(var indicatorID in this.indicators){indicator=this.indicators[indicatorID];name="Indicador "+id++;if(name==indicator.getIndicatorName()){continue;}
indicator.changeIndicatorName(name);this.tabPanel.renameTab(indicatorID,name);if(this.popup){this.popup._tabs.renameTab(indicator._popupTabId,name);}}},getIndicatorDifferentColor:function(){var color=false;var startColor=false;var endColor=false;var colorKey=false;var helperColorsObj=OpenLayers.Util.extend({},SAPO.Maps.Statistics.Panel.Territory.customColors);for(var indicatorID in this.indicators){color=this.indicators[indicatorID].getLayerColors();startColor=color.startColor.replace('#','');endColor=color.endColor.replace('#','');for(var colorKeys in SAPO.Maps.Statistics.Panel.Territory.customColors){var customColor=SAPO.Maps.Statistics.Panel.Territory.customColors[colorKeys];if(startColor==customColor.startColor&&endColor==customColor.endColor&&helperColorsObj[colorKeys]){delete helperColorsObj[colorKeys];}}}
if(!SAPO.Maps.Utils.hasProperties(helperColorsObj)){color=SAPO.Maps.Statistics.Panel.Territory.customColors.red;}else{colorKey=SAPO.Maps.Utils.getFirstKey(helperColorsObj);color=helperColorsObj[colorKey];}
return color;},createLabelsControl:function(title,labels){this.labelsControl=new SAPO.Maps.Statistics.StatisticLabels({scope:this,closed:this.labelsClosed,opened:this.labelsOpened},{hidden:true,div:this.legendDiv});this.map.addControl(this.labelsControl);},createShapeTracker:function(){var options={shapeEndpoint:SAPO.Maps.Statistics.Config.getEndpoint('shape')};this.statisticsShape=new SAPO.Maps.StatisticsShape(this.map,options);if(this.windowManager){this.floatWindowsStatisticsShape={};var windows=this.windowManager.getWindowsWithIds(),shape=false,window=false;for(var i=0,len=windows.length;i<len;++i){window=windows[i];shape=new SAPO.Maps.StatisticsShape(window.map,options);this.floatWindowsStatisticsShape[window.id]=shape;}}},activateStatisticsShape:function(){this.statisticsShape.activate();if(this.floatWindowsStatisticsShape){for(var shapeID in this.floatWindowsStatisticsShape){this.floatWindowsStatisticsShape[shapeID].activate();}}},deactivateStatisticsShape:function(){this.statisticsShape.deactivate();if(this.floatWindowsStatisticsShape){for(var shapeID in this.floatWindowsStatisticsShape){this.floatWindowsStatisticsShape[shapeID].deactivate();}}},removePopup:function(){this.clearIndicatorsPopupsInfo();if(!this.popup){return;}
this.popup._map.removePopup(this.popup);this.popup._tabs.destroy();this.popup._map=null;this.popup._tabs=null;this.popup._lonlat=null;this.popup=null;if(this.currentPopupTabIndicator){this.currentPopupTabIndicator.setIsSelectedTab(false);this.currentPopupTabIndicator=null;}},clearIndicatorsPopupsInfo:function(){var indicator=false;for(var id in this.indicators){indicator=this.indicators[id];indicator.clearIndicatorPopup();}},registerFloatMapsClickEvents:function(){if(!this.windowManager){return;}
this.floatWindowsClickListeners={};var windows=this.windowManager.getWindowsWithIds(),listener=false,map=false,statisticsShape=false,window=false;for(var i=0,len=windows.length;i<len;++i){window=windows[i];map=window.map;if(this.floatWindowsStatisticsShape){statisticsShape=this.floatWindowsStatisticsShape[window.id];}
listener=OpenLayers.Function.bind(this.mapClicked,this,map,statisticsShape);this.floatWindowsClickListeners[window.id]=listener;map.events.register('click',this,listener);}},unregisterFloatMapsClickEvents:function(){if(!this.windowManager||!this.floatWindowsClickListeners){return;}
var windows=this.windowManager.getWindowsWithIds(),listener=false,map=false,window=false;for(var i=0,len=windows.length;i<len;++i){window=windows[i];listener=this.floatWindowsClickListeners[window.id];map=window.map;map.events.unregister('click',this,listener);delete this.floatWindowsClickListeners[window.id];}
this.floatWindowsClickListeners=null;},getNrIndicatorsWithTerritoryRepresentation:function(){var count=0,representationTypes=SAPO.Maps.Indicator.representationTypes;for(var indicatorID in this.indicators){indicator=this.indicators[indicatorID];if(indicator.getIndicatorRepresentationType()==representationTypes.territory){++count;}}
return count;},checkShapeState:function(){if(!this.statisticsShape){return;}
var enable=this.getNrIndicatorsWithTerritoryRepresentation()>0,indicator=false;if(enable){this.activateStatisticsShape();}else{this.deactivateStatisticsShape();}},setChartsZIndex:function(){var highest=0,currZIndex=0,indicator=null;for(var indicatorID in this.indicators){indicator=this.indicators[indicatorID];currZIndex=Number(indicator.getTerritoryLayerZIndex());if(highest<currZIndex){highest=Number(indicator.getTerritoryLayerZIndex());}}
if(highest===0){return;}
highest+=5;for(indicatorID in this.indicators){indicador=this.indicators[indicatorID];indicador.setChartLayerZIndex(highest);}},addPopupTab:function(evt){if(!this.popup||evt.refresh){return;}
var indicator=evt.indicator;var indicatorID=indicator._id;var tabId=this.popup._tabs.addTab(indicator.getIndicatorName(),indicator.getPopupHolder(),indicatorID);indicator._popupTabId=tabId;},removePopupTab:function(indicator){if(!this.popup){return;}
if(this.currentPopupTabIndicator==indicator){this.currentPopupTabIndicator=null;}
this.popup._tabs.removeTab(indicator._popupTabId);indicator._popupTabId=null;if(!SAPO.Maps.Utils.hasProperties(this.indicators)){this.removePopup();}},openPopupInformation:function(map,lonlat,selectedIndicator,isChartClick){if(this.popup){this.removePopup();}
this.buildingPopup=true;var callbacks={scope:this,tabSelected:this.popupTabSelected};var content=document.createElement('div'),popupTabs=new SAPO.Maps.Statistics.Tabs(callbacks,content,{visible:true,scrollInContent:false}),indicator=false,tabId=false,tabToSelect=false,indicatorSelected=false;content.className='popup_content';for(var id in this.indicators){indicator=this.indicators[id];tabId=popupTabs.addTab(indicator.getIndicatorName(),indicator.getPopupHolder(),id);if(indicator==selectedIndicator){tabToSelect=tabId;indicatorSelected=indicator;}
indicator._popupTabId=tabId;}
if(!tabToSelect){tabToSelect=SAPO.Maps.Utils.getLastKey(this.indicators);indicatorSelected=this.indicators[tabToSelect];}
popupTabs.selectTab(tabToSelect);indicatorSelected.drawIndicatorPopup(map,lonlat,isChartClick);var popup_lonlat=lonlat.clone().transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));this.popup=new SAPO.Maps.Popup.SapoPopup(null,popup_lonlat,null,content,true,this.removePopup.bindObj(this),null,map.borders?map.borders:{left:0,top:0,right:0,bottom:0},true,new OpenLayers.Size(660,600));this.popup._map=map;this.popup._tabs=popupTabs;this.popup._lonlat=lonlat;map.addPopup(this.popup);this.events.triggerEvent('popupOpened');this.buildingPopup=false;},labelsClosed:function(){this.labelsControlOpened=false;this.events.triggerEvent("labelClosed");},labelsOpened:function(){this.labelsControlOpened=true;this.events.triggerEvent("labelOpened");},mapClicked:function(map,statisticsShape,evt){this.removePopup();var nrTabs=this.getNrIndicatorsWithTerritoryRepresentation();if(!SAPO.Maps.Utils.hasProperties(this.indicators)||nrTabs===0){return;}
var lonlat=map.getLonLatFromPixel(evt.xy);var convertedLonlat=lonlat.clone().transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));var hasStats=statisticsShape&&statisticsShape.hasStatistic(convertedLonlat);if(!hasStats||hasStats==SAPO.Maps.StatisticsShape.shapeHasStatisticsResult.Dont){return;}
var selectedIndicator=this.tabPanel?this.indicators[this.tabPanel.getSelectedTabId()]:null;if(hasStats==SAPO.Maps.StatisticsShape.shapeHasStatisticsResult.Maybe){selectedIndicator.drawIndicatorPopup(map,convertedLonlat);return;}
this.openPopupInformation(map,convertedLonlat,selectedIndicator);},messageBoardClosed:function(){this.wroteMessage=false;},openLabelsControl:function(){if(this.labelsControlOpened){this.labelsControl.show();}else{this.labelsControl.showMinimizedWindowControl();}},resizePopup:function(){if(this.popup){this.popup.contentUpdated();}},chartClicked:function(evt){this.clearIndicatorsPopupsInfo();this.openPopupInformation(evt.map,evt.lonlat,evt.indicator,true);},indicatorInformationComplete:function(evt){if(!this.popup){this.openPopupInformation(evt.map,evt.lonlat,evt.indicator);}},changeIndicator:function(evt){this.events.triggerEvent("changeIndicator",evt);},configureTerritory:function(evt){this.events.triggerEvent("configureTerritory",evt);},checkRepresentationForMessageBoard:function(){if(!this.useMessageBoard){return;}
if(this.wroteMessage==SAPO.Maps.Statistics.MessageBoardWarnings.charts){this.wroteMessage=false;this.map.getMessageBoardControl().hideMessage();}
var previousIndicator=false,currIndicator=false;for(var indicatorID in this.indicators){currIndicator=this.indicators[indicatorID];if(previousIndicator&&previousIndicator.getIndicatorRepresentationType()==currIndicator.getIndicatorRepresentationType()&&previousIndicator.getIndicatorRepresentationType()!=SAPO.Maps.Indicator.representationTypes.territory)
{this.map.getMessageBoardControl().showMessage("Tem dois indicadores em modo gráfico. Podem estar sobrepostos",{anchorText:'Alterar',anchorCallback:{scope:this,callback:function(){currIndicator.changeRepresentationType(SAPO.Maps.Indicator.representationTypes.territory);}}});this.wroteMessage=SAPO.Maps.Statistics.MessageBoardWarnings.charts;break;}
previousIndicator=currIndicator;}
this.checkColorsForMessageBoard();},checkColorsForMessageBoard:function(){if(!this.useMessageBoard){return;}
if(this.wroteMessage==SAPO.Maps.Statistics.MessageBoardWarnings.colors){this.wroteMessage=false;this.map.getMessageBoardControl().hideMessage();}
if(this.getNrIndicatorsWithTerritoryRepresentation()<2){return;}
var p_color=false;var p_startColor=false;var p_endColor=false;for(var indicatorID in this.indicators){var color=this.indicators[indicatorID].getLayerColors();var startColor=color.startColor.replace('#','');var endColor=color.endColor.replace('#','');if(p_color){if(p_startColor==startColor&&p_endColor==endColor){this.map.getMessageBoardControl().showMessage("Tem dois indicadores representados com a mesma cor.",{anchorText:'Alterar',anchorCallback:{scope:this,callback:function(){var color=this.getIndicatorDifferentColor();this.indicators[indicatorID].setLayerColors(color);}}});this.wroteMessage=SAPO.Maps.Statistics.MessageBoardWarnings.colors;break;}}
p_color=color;p_startColor=startColor;p_endColor=endColor;}},newWindowMapAdded:function(evt){var map=evt.window.map;var statisticsShape=false;if(this.floatWindowsStatisticsShape){statisticsShape=new SAPO.Maps.StatisticsShape(map,{shapeEndpoint:SAPO.Maps.Statistics.Config.getEndpoint('shape')});this.floatWindowsStatisticsShape[evt.id]=statisticsShape;if(this.statisticsShape.isActive()){statisticsShape.activate();}}
var listener=OpenLayers.Function.bind(this.mapClicked,this,map,statisticsShape);this.floatWindowsClickListeners[evt.id]=listener;map.events.register('click',this,listener);},removedWindowMap:function(evt){var map=evt.window.map;var listener=this.floatWindowsClickListeners[evt.id];map.events.unregister('click',this,listener);delete this.floatWindowsClickListeners[evt.id];if(this.floatWindowsStatisticsShape){var shape=this.floatWindowsStatisticsShape[evt.id];shape.destroy();delete this.floatWindowsStatisticsShape[evt.id];}},newTab:function(){this.events.triggerEvent("selectIndicator");},popupTabSelected:function(tabId,indicatorID){if(this.currentPopupTabIndicator){this.currentPopupTabIndicator.setIsSelectedTab(false);}
this.currentPopupTabIndicator=this.indicators[indicatorID];this.currentPopupTabIndicator.setIsSelectedTab(true);if(!this.buildingPopup){this.indicators[indicatorID].drawIndicatorPopup(this.popup.map,this.popup._lonlat);this.resizePopup();}},CLASS_NAME:'SAPO.Maps.Statistics'});SAPO.Maps.Statistics.MessageBoardWarnings={charts:1,colors:2,chartsRequest:3,territoryRequest:4,unavailableData:5};SAPO.Maps.Statistics.Config={serviceEndpoint:'http://services.sapo.pt/GIS/Statistics/',operations:{shape:'GetStatisticShapesByBoundingBox',details:'GetStatisticDetails',information:'GetStatisticInformation',graphics:'GetGraphicsByBoundingBox',themes:'GetStatisticThemes',indicatorsByTheme:'GetStatisticsByTheme',search:'GetStatisticsBySearch'},knownProviders:{ine:'http://services.sapo.pt/Statistics/INE'},providers:[{name:'Instituto nacional de estatísticas',abbr:'INE',endpoint:'http://services.sapo.pt/Statistics/INE'}],smartZoom:{Parish:8,Municipality:4,Distric:4,Nuts3:4,Nuts2:4,Nuts1:4,Country:4},currentProvider:null,init:function(){this.currentProvider=this.providers[0];},addProvider:function(providerInfo){this.providers.push(providerInfo);},getSelectedProvider:function(){return this.currentProvider;},getEndpoint:function(operation){if(!this.operations[operation]){return null;}
return this.serviceEndpoint+this.operations[operation];}};(function(){SAPO.Maps.Statistics.Config.init();})();SAPO.Maps.Indicator=OpenLayers.Class({map:null,panel:null,panelRenderers:null,popupRenderer:null,isPopupOpened:false,requester:null,requestDetailsId:null,requestInformationId:null,windowManager:null,labelsControl:null,indicatorID:null,indicatorName:null,nrClasses:7,color:null,currentRepresentationType:null,currentDataType:null,chartLayer:null,floatMapsChartLayers:null,territoryLayer:null,floatMapsfloatMapsTerritoryLayers:null,territoryLayersParameters:null,EVENT_TYPES:['changedRepresentation','canceledIndicatorRequest','indicatorDetailsComplete','indicatorDetailsTimeout','changeIndicatorClicked','selectedDimensionsChanged','opacityChanged','colorsChanged','nrClassesChanged','selectedAxisDimensionsChanged','chartsSizeChanged','indicatorInformationComplete','indicatorInformationTimeout','resizePopup','chartClicked','configureTerritoryClicked'],events:null,providerUrl:null,layerOpacity:0.5,useMessageBoard:true,indicatorTitle:null,credits:null,dimensions:null,selectedDimensions:null,selectedAxisDimension:null,chartHeight:60,chartWidth:60,isSelectedPopupTab:false,nrSlices:5,showChangeIndicatorLink:true,showConfigTerritoryDiv:true,chartZIndex:0,initializing:true,currentPopupTab:null,changingIndicator:false,indicatorState:null,showTemporalDimensionOnPieCharts:true,initialize:function(map,panel,indicatorName,indicatorID,windowManager,labelsControl,options){this.map=map;this.panel=typeof(panel)=='string'?document.getElementById(panel):panel;this.indicatorName=indicatorName;this.indicatorID=indicatorID;this.windowManager=windowManager;this.labelsControl=labelsControl;this.currentRepresentationType=SAPO.Maps.Indicator.representationTypes.territory;this.currentDataType=SAPO.Maps.Indicator.dataTypes.pie;this.color=SAPO.Maps.Statistics.Panel.Territory.customColors.red;this.currentPopupTab=SAPO.Maps.Indicator.dataTypes.table;OpenLayers.Util.extend(this,options);this.events=new OpenLayers.Events(this,this.div,this.EVENT_TYPES,true,null);this.popupRenderer=new SAPO.Maps.Statistics.BallonRenderer({scope:this,onTabChanged:this.popupTabChanged,onAxisDimensionChange:this.popupAxisDimensionChange,onDimensionTableChange:this.tableDimensionChange,popupResized:this.popupResized},{currentTab:this.currentPopupTab,showTemporalDimensionOnPieCharts:this.showTemporalDimensionOnPieCharts});this.requester=SAPO.Maps.Request.prototype.getRequester();this.map.events.register('zoomend',this,this.smartZoom);this.indicatorState=new SAPO.Maps.IndicatorState();if(this.windowManager){this.windowManager.events.register('windowcreated',this,this.newWindowMapAdded);this.windowManager.events.register('windowremoved',this,this.removedWindowMap);}
if(this.useMessageBoard){this.map.getMessageBoardControl().events.register('closed',this,this.messageBoardClosed);}
this.requestDetails(this.selectedDimensions,true);},destroy:function(){this.events.destroy();this.events=null;this.map.events.unregister('zoomend',this,this.smartZoom);if(this.windowManager){this.windowManager.events.unregister('windowcreated',this,this.newWindowMapAdded);this.windowManager.events.unregister('windowremoved',this,this.removedWindowMap);}
var layer=false;this.removeTerritoryLayersFromMaps();if(this.territoryLayer){if(this.floatMapsTerritoryLayers){layer=false;for(var floatMapLayer in this.floatMapsTerritoryLayers){layer=this.floatMapsTerritoryLayers[floatMapLayer];layer.destroy();delete this.floatMapsTerritoryLayers[floatMapLayer];}
this.floatMapsTerritoryLayers=null;}
this.territoryLayer.destroy();this.territoryLayer=null;}
if(this.chartLayer){if(this.floatMapsChartLayers){layer=false;for(var chartLayer in this.floatMapsChartLayers){layer=this.floatMapsChartLayers[chartLayer];this.chartLayer.unRegisterEvent('chartClicked',this,this.chartClicked);layer.destroy();delete this.floatMapsChartLayers[chartLayer];}
this.floatMapsChartLayers=null;}
this.chartLayer.deactivate();this.chartLayer.destroy();this.chartLayer=null;}
if(this.popupRenderer){this.popupRenderer.destroy();this.popupRenderer=null;}
if(this.useMessageBoard){this.map.getMessageBoardControl().events.unregister('closed',this,this.messageBoardClosed);if(this.wroteMessage){this.map.getMessageBoardControl().hideMessage();this.wroteMessage=null;}}
this.labelsControl.removeLabel(this.indicatorName);this.requester.destroy();this.requester=null;this.map=null;this.panel=null;this.windowManager=null;this.labelsControl=null;},changeIndicator:function(indicatorID,indicatorOptions){if(this.indicatorID==indicatorID){return;}
this.resetIndicator();if(this.currentRepresentationType==SAPO.Maps.Indicator.representationTypes.territory&&this.territoryLayer){this.territoryLayer.setVisibility(false);}else{if(this.chartLayer){this.chartLayer.deactivate();}}
this.changingIndicator=true;this.indicatorID=indicatorID;OpenLayers.Util.extend(this,indicatorOptions);this.clearCurrentPanel();this.requestDetails(this.selectedDimensions,true);this.popupRenderer.clear();if(this.isPopupOpened&&this.isSelectedPopupTab){var selectedTab=this.popupRenderer.getSelectedTab();this.popupRenderer.showWaitIcon(selectedTab);this.events.triggerEvent('resizePopup',{indicator:this});}},changeRepresentationType:function(representation){if(this.currentRepresentationType==representation){return;}
var oldRepresentation=this.currentRepresentationType;this.currentRepresentationType=representation;if(SAPO.Maps.Indicator.representationTypes.territory==representation){if(!this.territoryLayer){this.createTerritoryLayers();}
this.territoryLayer.setVisibility(false);this.addTerritoryLayersToMaps();if(this.chartLayer){this.chartLayer.deactivate();}
this.requestDetails(this.selectedDimensions,false);}else{if(!this.chartLayer){this.createChartLayers();}
var chart=representation==SAPO.Maps.Indicator.representationTypes.pieCharts?SAPO.Maps.Indicator.dataTypes.pie:SAPO.Maps.Indicator.dataTypes.bars;this.chartLayer.setChartType(chart);this.chartLayer.setStatisticId(encodeURIComponent(this.providerUrl),this.indicatorID);this.chartLayer.setDimensions(this.dimensionsToString(this.selectedDimensions));this.chartLayer.setChartAxisDimension(this.dimensionAxisToString(this.selectedAxisDimension));this.labelsControl.clearLabelsContent(this.indicatorName);if(oldRepresentation==SAPO.Maps.Indicator.representationTypes.territory){this.chartLayer.activate();this.removeTerritoryLayersFromMaps();}}
if(this.panel){var representationEnum=SAPO.Maps.Indicator.representationTypes;var clearPanel=this.getPanelRenderer(oldRepresentation);clearPanel.clear();var showPanel=this.getPanelRenderer(representation);showPanel.draw(this.indicatorTitle,this.dimensions,this.selectedDimensions,this.credits,this.indicatorID);this.checkDimensionsToHidePieCharts(showPanel);if(representation!=representationEnum.territory){showPanel.selectAxisDimension(this.selectedAxisDimension);}
clearPanel.setRepresentation(representation);showPanel.setRepresentation(representation);}
this.events.triggerEvent('changedRepresentation',{indicator:this,representationType:representation});},setIsSelectedTab:function(selected){this.isSelectedPopupTab=selected;},getIsSelectedTab:function(){return this.isSelectedPopupTab;},getCurrentPopupTab:function(){return this.currentPopupTab;},changeIndicatorName:function(newIndicatorName){if(this.indicatorName==newIndicatorName){return;}
this.labelsControl.renameLabel(this.indicatorName,newIndicatorName);this.indicatorName=newIndicatorName;if(this.chartLayer){this.chartLayer.setIndicatorKey(newIndicatorName);}},getPanel:function(){return this.panel;},getIndicatorName:function(){return this.indicatorName;},getIndicatorRepresentationType:function(){return this.currentRepresentationType;},getIndicatorId:function(){return this.indicatorID;},getDimensions:function(){return this.dimensions;},getSelectedDimensions:function(){return this.selectedDimensions;},getChartSize:function(){return{width:this.chartWidth,height:this.chartHeight};},getGeographicView:function(){return this.getGeographicDimension().territoryView;},getGeographicDimension:function(){var dimension=false;for(var i=0,len=this.selectedDimensions.length;i<len;++i){dimension=this.selectedDimensions[i];if(dimension.type=='Geo'){return dimension;}}
return null;},getSelectedAxisDimension:function(){return this.selectedAxisDimension;},setLayerOpacity:function(opacity){this.layerOpacity=opacity;if(this.territoryLayer){this.territoryLayer.setOpacity(opacity);}
if(this.panel){var panel=this.getPanelRenderer(SAPO.Maps.Indicator.representationTypes.territory);panel.setOpacity(opacity);}
this.events.triggerEvent('selectedDimensionsChanged',{indicator:this,layerOpacity:opacity});},getLayerOpacity:function(){return this.layerOpacity;},setLayerColors:function(colors){this.color={startColor:colors.startColor.replace('#',''),endColor:colors.endColor.replace('#','')};if(this.territoryLayer&&this.currentRepresentationType==SAPO.Maps.Indicator.representationTypes.territory){this.requestDetails(this.selectedDimensions,false);}
if(this.panel){var panel=this.getPanelRenderer(SAPO.Maps.Indicator.representationTypes.territory);panel.setColors(colors);}
this.events.triggerEvent('colorsChanged',{indicator:this,startColor:this.color.startColor,endColor:this.color.endColor});},getLayerColors:function(){return this.color;},setNrClasses:function(nrClasses){this.nrClasses=nrClasses;if(this.territoryLayer&&this.currentRepresentationType==SAPO.Maps.Indicator.representationTypes.territory){this.requestDetails(this.selectedDimensions,false);}
if(this.panel){var panel=this.getPanelRenderer(SAPO.Maps.Indicator.representationTypes.territory);panel.setNrClasses(nrClasses);}
this.events.triggerEvent('nrClassesChanged',{indicator:this,nrClasses:nrClasses});},getNrClasses:function(){return this.nrClasses;},setChartSize:function(width,height){this.chartWidth=width;this.chartHeight=height;if(this.panel){for(var panel in this.panelRenderers){if(this.panelRenderers[panel].setChartSize){this.panelRenderers[panel].setChartSize(width,height);}}}
if(this.chartLayer){this.chartLayer.setSize(width,height);}
this.events.triggerEvent('chartsSizeChanged',{indicator:this,width:width,height:height});},selectDimensions:function(dimensions){this.selectedDimensions=dimensions;this.smartZoom();if(this.panelRenderers){for(var panel in this.panelRenderers){this.panelRenderers[panel].selectDimensions(dimensions);}}
if(this.territoryLayer&&this.currentRepresentationType==SAPO.Maps.Indicator.representationTypes.territory){this.requestDetails(this.selectedDimensions,false);}
if(this.chartLayer){this.chartLayer.setDimensions(this.dimensionsToString(dimensions));}
if(this.isPopupOpened){this.popupRenderer.clear();var selectedTab=this.popupRenderer.getSelectedTab();this.requestPopupInformation(this.popupRenderer._lonlat,selectedTab);this.events.triggerEvent('resizePopup',{indicator:this});}
this.events.triggerEvent('selectedDimensionsChanged',{indicator:this,dimensions:dimensions});},selectAxisDimension:function(axisDimension){this.selectedAxisDimension=axisDimension;if(this.panel){for(var panel in this.panelRenderers){if(this.panelRenderers[panel].selectAxisDimension){this.panelRenderers[panel].selectAxisDimension(axisDimension);}}}
if(this.chartLayer){this.chartLayer.setChartAxisDimension(this.dimensionAxisToString(axisDimension));}
this.events.triggerEvent('selectedAxisDimensionsChanged',{indicator:this,axisDimension:axisDimension});},setLayerStyle:function(parameters){this.territoryLayersParameters=parameters;if(this.territoryLayer){this.territoryLayer.setLayerStyle(this.territoryLayersParameters);}},getTerritoryLayerZIndex:function(){if(this.territoryLayer){return this.territoryLayer.getZIndex();}
return 0;},setChartLayerZIndex:function(zIndex){this.chartZIndex=zIndex;if(this.chartLayer){this.chartLayer.setZIndex(zIndex);}},drawIndicatorPopup:function(map,lonlat,isChartClick){this.popupRenderer._lonlat=lonlat;var selectedTab=this.popupRenderer.getSelectedTab();if(!this.showTemporalDimensionOnPieCharts&&selectedTab==SAPO.Maps.Indicator.dataTypes.pie&&this.hasOnlyTemporalDimension())
{this.popupRenderer.selectTab(SAPO.Maps.Indicator.dataTypes.bars);return;}
if(isChartClick&&this.currentRepresentationType!=SAPO.Maps.Indicator.representationTypes.territory){selectedTab=this.chartLayer.getCurrentChartType();this.popupRenderer.selectTab(selectedTab);this.popupRenderer.selectAxisDimension(this.selectedAxisDimension);}
var drawn=this.popupRenderer.isDrawn(selectedTab);if(!drawn){this.requestPopupInformation(lonlat,selectedTab,map);}
this.isPopupOpened=true;},getPopupHolder:function(){return this.popupRenderer.getHolder();},clearIndicatorPopup:function(){if(this.requestInformationId){this.requester.cancel(this.requestInformationId);this.requestInformationId=null;}
this.popupRenderer.clear();this.popupRenderer._lonlat=null;this.isPopupOpened=false;this.isSelectedPopupTab=false;},requestDetails:function(dimensions,includeDimensions){this.cancelDetailsRequest();var dimensionsStr="";if(dimensions){dimensionsStr=this.dimensionsToString(dimensions);}
var repaint=!includeDimensions;if(!repaint&&this.panel){this.clearCurrentPanel();SAPO.Maps.Utils.displayWaitIcon(this.panel);}
if(repaint&&this.useMessageBoard){this.map.getMessageBoardControl().showMessage("A transferir os dados estatísticos...");this.wroteMessage=SAPO.Maps.Statistics.MessageBoardWarnings.territoryRequest;}
var startColor=SAPO.Maps.Utils.convertHexToRGB(this.color.startColor);var endColor=SAPO.Maps.Utils.convertHexToRGB(this.color.endColor);var url=SAPO.Maps.Utils.composeUrl(SAPO.Maps.Statistics.Config.getEndpoint('details'),{providerUrl:encodeURIComponent(this.providerUrl),statisticId:this.indicatorID,startColor:startColor,endColor:endColor,nrClasses:this.nrClasses,dimensionsId:dimensionsStr,includeDimensions:includeDimensions});this.requestDetailsId=this.requester.request(url,{timeout:8,onComplete:this.gettingTerritoryDetails.bindObj(this),onTimeout:function(){var lastState=this.indicatorState.getLastState();if(lastState){var panel=this.getPanelRenderer(this.currentRepresentationType);panel.selectDimensions(this.indicatorState.getLastState());}
this.requestDetailsId=null;if(!repaint&&this.panel){SAPO.Maps.Utils.removeWaitIcon(this.panel);var a=document.createElement('a');a.innerHTML="Pretende voltar a tentar?";a.onclick=function(){this.requestDetails(dimensions,includeDimensions);return false;}.bindObj(this);SAPO.Maps.Utils.displayMessageToRetry(this.panel,"Lamentamos mas de momento não é possível apresentar o indicador. ",a,SAPO.Maps.Utils.MessageType.WARNING);}
if(repaint&&this.useMessageBoard){this.map.getMessageBoardControl().showMessageDelay("Não foi possível obter os dados estatístos...",2000);}
this.events.triggerEvent('indicatorDetailsTimeout',{indicator:this,refresh:true});}.bindObj(this),optOnComplete:repaint});},requestPopupInformation:function(lonlat,tab,map,dimensions){if(this.requestInformationId){this.requester.cancel(this.requestInformationId);this.requestInformationId=null;}
this.popupRenderer.showWaitIcon(tab);var axis=this.popupRenderer.getSelectedAxisDimension();if(!axis){axis=this.selectedAxisDimension;}
if(!dimensions){dimensions=this.selectedDimensions;}
var url=SAPO.Maps.Utils.composeUrl(SAPO.Maps.Statistics.Config.getEndpoint('information'),{providerUrl:encodeURIComponent(this.providerUrl),statisticId:this.indicatorID,latitude:lonlat.lat,longitude:lonlat.lon,colors:'',chartType:tab,nrSlices:this.nrSlices,dimensionsId:this.dimensionsToString(dimensions),chartAxisDimensionType:this.dimensionAxisToString(axis)});this.requestInformationId=this.requester.request(url,{timeout:8,onComplete:this.gettingPopupInformation.bindObj(this),onTimeout:function(){this.popupRenderer.removeWaitIcon(tab);var a=document.createElement('a');a.innerHTML="Pretende voltar a tentar?";a.onclick=function(){this.popupRenderer.removeErrorMessge(tab);this.requestPopupInformation(lonlat,tab,map,dimensions);this.events.triggerEvent('resizePopup',{indicator:this});}.bindObj(this);this.popupRenderer.showErrorMessage(tab,"Lamentamos mas de momento não é possível apresentar informação estatística. ",a);this.requestInformationId=null;this.events.triggerEvent('indicatorInformationTimeout',{indicator:this,tab:tab});this.events.triggerEvent('resizePopup',{indicator:this});}.bindObj(this),optOnComplete:{tab:tab,lonlat:lonlat,map:map}});},createTerritoryLayers:function(){var territoryMapLayer=this.map.getBaseLayers().TERRITORY_MAP;territoryMapLayer.setLayerStyle(this.territoryLayersParameters);this.territoryLayer=territoryMapLayer.clone();this.territoryLayer.opacity=this.layerOpacity;this.territoryLayer.isBaseLayer=false;this.territoryLayer.visibility=false;if(!this.windowManager){return;}
this.floatMapsTerritoryLayers={};var windows=this.windowManager.getWindowsWithIds(),layer=false,window=false;for(var i=0,len=windows.length;i<len;++i){window=windows[i];layer=this.territoryLayer.clone();this.territoryLayer.addLayer(layer);layer.visibility=false;this.floatMapsTerritoryLayers[window.id]=layer;}},createChartLayers:function(){var mapping=["Pie","Bars"];this.chartLayer=new SAPO.Maps.Statistics.Charts(this.map,{statisticId:this.indicatorID,dimensionsId:this.dimensionsToString(this.selectedDimensions),chartAxisDimensionType:this.dimensionAxisToString(this.selectedAxisDimension),chartType:mapping[this.currentRepresentationType-1],height:this.chartHeight,width:this.chartWidth,providerUrl:encodeURIComponent(this.providerUrl)},this.indicatorName,this.labelsControl,{baseAddress:SAPO.Maps.Statistics.Config.getEndpoint('graphics'),useMessageBoard:this.useMessageBoard});this.chartLayer.registerEvent('chartClicked',this,this.chartClicked);if(!this.windowManager){return;}
this.floatMapsChartLayers={};var windows=this.windowManager.getWindowsWithIds(),layer=false,window=false;for(var i=0,len=windows.length;i<len;++i){window=windows[i];layer=this.chartLayer.clone();layer.useMessageBoard=false;this.chartLayer.addLayer(layer);this.floatMapsChartLayers[window.id]=layer;layer.setMap(window.map);layer.registerEvent('chartClicked',this,this.chartClicked);}},cancelDetailsRequest:function(){if(this.requestDetailsId){this.requester.cancel(this.requestDetailsId);this.requestDetailsId=null;this.events.triggerEvent('canceledIndicatorRequest',{indicator:this});}},resetIndicator:function(){this.indicatorID=null;this.dimensions=null;this.selectedDimensions=null;if(this.wroteMessage){this.map.getMessageBoardControl().hideMessage();this.wroteMessage=null;}},dimensionsToString:function(dimensions){if(!dimensions){return"";}
var str="";for(var i=0,len=dimensions.length;i<len;++i){str+=dimensions[i].type+"-"+dimensions[i].order+":"+dimensions[i].id;if(dimensions[i].territoryView){str+=','+dimensions[i].territoryView;}
str+=';';}
str=str.slice(0,str.length-1);return str;},dimensionAxisToString:function(axisObject){if(!axisObject){return"";}
var str=axisObject.type+"-"+axisObject.order+":";for(var i=0,len=axisObject.ids.length;i<len;++i){str+=axisObject.ids[i].Id+",";}
str=str.slice(0,str.length-1);return str;},extractSelectedDimensions:function(dimensions){this.selectedDimensions=[];var serverDimension=false,value=false,selectedId=false,territoryView=false,d=false;for(var i=0,len=dimensions.length;i<len;++i){serverDimension=dimensions[i];for(var j=0,vlen=serverDimension.Values.length;j<vlen;++j){value=serverDimension.Values[j];if(value.IsSelected){selectedId=value.Id;territoryView=value.TerritoryView;break;}}
d={id:selectedId,territoryView:territoryView,type:serverDimension.DimensionType,order:serverDimension.Order};this.selectedDimensions.push(d);}
if(!this.initializing||(this.initializing&&!this.selectedAxisDimension)){this.extractSelectedAxisDimensions(dimensions);}},extractSelectedAxisDimensions:function(dimensions){var dimension=false,selectedAxis={};for(var i=0,len=dimensions.length;i<len;++i){dimension=dimensions[i];if(dimension.DimensionType=="Geo"){continue;}
selectedAxis.type=dimension.DimensionType;selectedAxis.order=dimension.Order;selectedAxis.ids=dimension.Values;if(dimension.DimensionType!="Year"){break;}}
this.selectedAxisDimension=selectedAxis;},hasOnlyTemporalDimension:function(){for(var i=0,len=this.dimensions.length;i<len;++i){var dimension=this.dimensions[i];if(dimension.DimensionType!="Geo"&&dimension.DimensionType!="Year"){return false;}}
return true;},removeTerritoryLayersFromMaps:function(){if(!this.territoryLayer||!this.territoryLayer.map){return;}
this.map.removeLayer(this.territoryLayer);if(this.floatMapsTerritoryLayers){var layer=false;for(var layerKey in this.floatMapsTerritoryLayers){layer=this.floatMapsTerritoryLayers[layerKey];layer.map.removeLayer(layer);}}},addTerritoryLayersToMaps:function(){if(!this.territoryLayer||this.territoryLayer.map){return;}
this.map.addLayer(this.territoryLayer);if(this.windowManager){var windows=this.windowManager.getWindowsWithIds(),layer=false,window=false;for(var i=0,len=windows.length;i<len;++i){window=windows[i];layer=this.floatMapsTerritoryLayers[window.id];layer.visibility=false;window.map.addLayer(layer);}}},getPanelRenderer:function(representation){if(!this.panelRenderers){this.panelRenderers={};}
var panel=false,callbacks=false,options=false;if(representation==SAPO.Maps.Indicator.representationTypes.territory){if(!this.panelRenderers.territory){callbacks={scope:this,dimensionChange:this.selectDimensions,opacityChange:this.setLayerOpacity,colorsChange:this.setLayerColors,classesChange:this.setNrClasses,indicatorChange:this.changeIndicatorClicked,configureTerritory:this.configureTerritoryClicked,representationChange:this.changeRepresentationType};options={opacityValue:this.layerOpacity*100,colors:this.color,nrClasses:this.nrClasses,representation:this.currentRepresentationType,showConfigTerritoryDiv:this.showConfigTerritoryDiv,showChangeIndicatorLink:this.showChangeIndicatorLink,showTemporalDimensionOnPieCharts:this.showTemporalDimensionOnPieCharts};this.panelRenderers.territory=new SAPO.Maps.Statistics.Panel.Territory(this.panel,callbacks,options);}
panel=this.panelRenderers.territory;}else{callbacks={scope:this,dimensionChange:this.selectDimensions,axisChange:this.selectAxisDimension,sizeChange:this.setChartSize,indicatorChange:this.changeIndicatorClicked,configureTerritory:this.configureTerritoryClicked,representationChange:this.changeRepresentationType};options={height:this.chartHeight,width:this.chartWidth,representation:this.currentRepresentationType,showConfigTerritoryDiv:this.showConfigTerritoryDiv,showChangeIndicatorLink:this.showChangeIndicatorLink};if(representation==SAPO.Maps.Indicator.representationTypes.pieCharts){if(!this.panelRenderers.pie){options.showTemporalDimensionOnPieCharts=this.showTemporalDimensionOnPieCharts;this.panelRenderers.pie=new SAPO.Maps.Statistics.Panel.Graphics(this.panel,callbacks,options);}
panel=this.panelRenderers.pie;}else{if(!this.panelRenderers.bar){this.panelRenderers.bar=new SAPO.Maps.Statistics.Panel.Graphics(this.panel,callbacks,options);}
panel=this.panelRenderers.bar;}}
return panel;},clearCurrentPanel:function(){if(this.panel){SAPO.Maps.Utils.removeErrorMessage(this.panel);}
if(this.panelRenderers){for(var panel in this.panelRenderers){this.panelRenderers[panel].clear();}}},adjustRepresentationType:function(){if(!this.showTemporalDimensionOnPieCharts&&this.hasOnlyTemporalDimension()&&this.currentRepresentationType==SAPO.Maps.Indicator.representationTypes.pieCharts)
{this.currentRepresentationType=SAPO.Maps.Indicator.representationTypes.barCharts;}},checkDimensionsToHidePieCharts:function(panel){if(!this.showTemporalDimensionOnPieCharts){if(this.hasOnlyTemporalDimension()){panel.disablePieChartSelection();}
else{panel.enablePieChartSelection();}}},gettingTerritoryDetails:function(details,state){var repaint=state;if(!repaint){if(this.panel){SAPO.Maps.Utils.removeWaitIcon(this.panel);}
if(details.Dimensions){this.dimensions=details.Dimensions;this.indicatorTitle=details.Title;this.credits={source:details.Source,sourceUrl:details.SourceUrl};this.extractSelectedDimensions(details.Dimensions);this.adjustRepresentationType();var panel=false;if(this.panel){panel=this.getPanelRenderer(this.currentRepresentationType);panel.draw(details.Title,details.Dimensions,this.selectedDimensions,this.credits,this.indicatorID);this.checkDimensionsToHidePieCharts(panel);}
if(this.currentRepresentationType==SAPO.Maps.Indicator.representationTypes.territory){this.labelsControl.addLabel(this.indicatorName,details.Title,details.Labels,false,true);}else{if(this.panel){panel.selectAxisDimension(this.selectedAxisDimension);}}
this.popupRenderer.setDimensions(details.Dimensions,this.selectedAxisDimension);if(this.changingIndicator&&this.isPopupOpened&&this.isSelectedPopupTab){this.changingIndicator=false;var selectedTab=this.popupRenderer.getSelectedTab();if(!this.showTemporalDimensionOnPieCharts&&selectedTab==SAPO.Maps.Indicator.dataTypes.pie&&this.hasOnlyTemporalDimension())
{this.popupRenderer.selectTab(SAPO.Maps.Indicator.dataTypes.bars);}else{this.requestPopupInformation(this.popupRenderer._lonlat,selectedTab);}}}}else{if(this.useMessageBoard&&this.wroteMessage==SAPO.Maps.Statistics.MessageBoardWarnings.territoryRequest)
{this.map.getMessageBoardControl().hideMessage();this.wroteMessage=false;}
if(this.currentRepresentationType==SAPO.Maps.Indicator.representationTypes.territory){this.labelsControl.replaceLabel(this.indicatorName,details.Title,details.Labels,false,true);}}
this.requestDetailsId=null;if(this.currentRepresentationType==SAPO.Maps.Indicator.representationTypes.territory){if(!this.territoryLayer){this.createTerritoryLayers();}
this.addTerritoryLayersToMaps();this.territoryLayer.setCustomColorsGuid(details.ImagesParameters);this.territoryLayer.setShapeType(this.getGeographicView());this.territoryLayer.setVisibility(true);}else{if(!this.chartLayer){this.createChartLayers();}
this.removeTerritoryLayersFromMaps();var chart=this.currentRepresentationType==SAPO.Maps.Indicator.representationTypes.pieCharts?SAPO.Maps.Indicator.dataTypes.pie:SAPO.Maps.Indicator.dataTypes.bars;this.chartLayer.setChartType(chart);this.chartLayer.setStatisticId(encodeURIComponent(this.providerUrl),this.indicatorID);this.chartLayer.setDimensions(this.dimensionsToString(this.selectedDimensions));this.chartLayer.setChartAxisDimension(this.dimensionAxisToString(this.selectedAxisDimension));this.chartLayer.activate();}
this.initializing=false;if(!this.isPopupOpened&&!this.isSelectedPopupTab){this.events.triggerEvent('indicatorDetailsComplete',{indicator:this,refresh:state,dimensions:this.getSelectedDimensions()});}
if(details.UnavailableData&&this.useMessageBoard){this.wroteMessage=SAPO.Maps.Statistics.MessageBoardWarnings.unavailableData;this.map.getMessageBoardControl().showMessage("Não existem dados disponíveis para o conjunto de selecções que efectuou.");}
this.indicatorState.setState(this.getSelectedDimensions());},gettingPopupInformation:function(information,state){this.popupRenderer.removeWaitIcon(state.tab);this.requestInformationId=null;this.popupRenderer.drawTabElement(state.tab,information,this.credits);this.popupRenderer._lonlat=state.lonlat;this.events.triggerEvent('indicatorInformationComplete',{indicator:this,tab:state.tab,lonlat:state.lonlat,map:state.map});this.events.triggerEvent('resizePopup',{indicator:this});},popupTabChanged:function(tab,drawn){this.currentPopupTab=tab;if(!drawn){this.requestPopupInformation(this.popupRenderer._lonlat,tab);}
this.events.triggerEvent('resizePopup',{indicator:this});},popupAxisDimensionChange:function(tab,axisDimension){this.requestPopupInformation(this.popupRenderer._lonlat,tab);this.events.triggerEvent('resizePopup',{indicator:this});},tableDimensionChange:function(selectedDimensions){selectedDimensions.splice(1,0,this.getGeographicDimension());this.popupRenderer.clearTab(SAPO.Maps.Indicator.dataTypes.table);this.requestPopupInformation(this.popupRenderer._lonlat,SAPO.Maps.Indicator.dataTypes.table,null,selectedDimensions);this.events.triggerEvent('resizePopup',{indicator:this});},popupResized:function(){this.events.triggerEvent('resizePopup',{indicator:this});},chartClicked:function(map,lonlat){this.events.triggerEvent('chartClicked',{indicator:this,map:map,lonlat:lonlat});},newWindowMapAdded:function(evt){var layer=false;if(this.territoryLayer){layer=this.territoryLayer.clone();this.floatMapsTerritoryLayers[evt.id]=layer;this.territoryLayer.addLayer(layer);}
if(this.chartLayer){layer=this.chartLayer.clone();layer.map=evt.window.map;layer.useMessageBoard=false;this.floatMapsChartLayers[evt.id]=layer;this.chartLayer.addLayer(layer);layer.registerEvent('chartClicked',this,this.chartClicked);}
if(this.currentRepresentationType==SAPO.Maps.Indicator.representationTypes.territory){evt.window.map.addLayer(this.floatMapsTerritoryLayers[evt.id]);}else{this.floatMapsChartLayers[evt.id].activate();}},removedWindowMap:function(evt){var layer=false;if(this.floatMapsTerritoryLayers&&this.floatMapsTerritoryLayers[evt.id]){layer=this.floatMapsTerritoryLayers[evt.id];if(this.currentRepresentationType==SAPO.Maps.Indicator.representationTypes.territory){evt.window.map.removeLayer(layer);}
this.territoryLayer.removeLayer(layer);layer.destroy();delete this.floatMapsTerritoryLayers[evt.id];}
if(this.floatMapsChartLayers&&this.floatMapsChartLayers[evt.id]){layer=this.floatMapsChartLayers[evt.id];if(this.currentRepresentationType!=SAPO.Maps.Indicator.representationTypes.territory){layer.deactivate();}
this.chartLayer.removeLayer(layer);this.chartLayer.unRegisterEvent('chartClicked',this,this.chartClicked);layer.destroy();delete this.floatMapsChartLayers[evt.id];}},changeIndicatorClicked:function(){this.events.triggerEvent('changeIndicatorClicked',{indicator:this});},configureTerritoryClicked:function(){this.events.triggerEvent('configureTerritoryClicked',{indicator:this});},messageBoardClosed:function(){this.wroteMessage=false;},smartZoom:function(){var territoryView=this.getGeographicView();if(SAPO.Maps.Statistics.Config.smartZoom[territoryView]){var zoomLevel=SAPO.Maps.Statistics.Config.smartZoom[territoryView];if(this.map.getZoom()<zoomLevel){this.map.getMessageBoardControl().showMessageDelay("Não é possível apresentar esta informação neste nível de zoom. O mapa foi aproximado.",2000);SAPO.Maps.Utils.zoomMapConsideringBorders(this.map,zoomLevel);}}},CLASS_NAME:'SAPO.Maps.Indicator'});SAPO.Maps.Indicator.representationTypes={territory:0,pieCharts:1,barCharts:2};SAPO.Maps.Indicator.dataTypes={table:'Table',pie:'Pie',bars:'Bars'};SAPO.Maps.IndicatorState=OpenLayers.Class({laststate:null,initialize:function(){},getLastState:function(){return this.laststate;},setState:function(state){this.laststate=state;},clearState:function(){this.laststate=null;},CLASS_NAME:'SAPO.Maps.IndicatorState'});SAPO.Maps.Statistics.Charts=OpenLayers.Class(SAPO.Maps.Layer.Custom,{markers:null,parameters:null,events:null,baseAddress:null,chartLayers:null,currentLabels:null,labelsControl:null,indicatorKey:null,timeout:8,fullLoad:true,wroteMessage:false,useMessageBoard:true,initialize:function(map,parameters,indicatorKey,labelsControl,options){SAPO.Maps.Layer.Custom.prototype.initialize.apply(this,[map,options]);this.parameters=OpenLayers.Util.extend({bbox:null,statisticId:null,dimensionsId:null,chartAxisDimensionType:null,chartType:null,width:120,height:120,nrSlices:5},parameters);this.markers={};this.events={};this.indicatorKey=indicatorKey;this.labelsControl=labelsControl;OpenLayers.Util.extend(this,options);if(this.useMessageBoard){this.map.getMessageBoardControl().events.register('closed',this,this.closedMessageBoard);}},destroy:function(){this.removeMarkers();this.parameters=null;this.markers=null;this.events=null;this.chartLayers=null;this.labelsControl=null;this.currentLabels=null;this.indicatorKey=null;if(this.useMessageBoard){this.map.getMessageBoardControl().events.unregister();if(this.wroteMessage){this.wroteMessage=false;this.map.getMessageBoardControl().hideMessage();}}
SAPO.Maps.Layer.Custom.prototype.destroy.apply(this,arguments);},activate:function(){SAPO.Maps.Layer.Custom.prototype.activate.apply(this,arguments);this.propagateState('activate',arguments);},deactivate:function(){SAPO.Maps.Layer.Custom.prototype.deactivate.apply(this,arguments);this.propagateState('deactivate',arguments);if(this.currentLabels){this.labelsControl.removeSetOfLabels(this.indicatorKey,this.currentLabels);this.currentLabels=null;}
this.removeMarkers();this.fullLoad=true;if(this.useMessageBoard&&this.wroteMessage){this.map.getMessageBoardControl().hideMessage();this.wroteMessage=null;}},setIndicatorKey:function(indicatorKey){this.indicatorKey=indicatorKey;this.propagateState('setIndicatorsKey',arguments);},setStatisticId:function(providerUrl,statisticId){this.parameters.providerUrl=providerUrl;this.parameters.statisticId=statisticId;this.propagateState('setStatisticId',arguments);this.reload();},setDimensions:function(dimensions){this.parameters.dimensionsId=dimensions;this.propagateState('setDimensions',arguments);this.reload();},setChartAxisDimension:function(chartAxisDim){this.parameters.chartAxisDimensionType=chartAxisDim;this.propagateState('setChartAxisDimension',arguments);this.reload();},setChartType:function(chartType){this.parameters.chartType=chartType;this.propagateState('setChartType',arguments);this.reload();},getCurrentChartType:function(){return this.parameters.chartType;},setSize:function(width,height){this.parameters.width=width;this.parameters.height=height;this.propagateState('setSize',arguments);for(var m in this.markers){this.markers[m].setStyle({size:new OpenLayers.Size(width,height),markerAnchor:new OpenLayers.Pixel(-width/2,-height/2)});}},addLayer:function(chartLayer){if(!this.chartLayers){this.chartLayers=[];}
this.chartLayers.push(chartLayer);},removeLayer:function(chartLayer){if(!this.chartLayers){return;}
OpenLayers.Util.removeItem(this.chartLayers,chartLayer);},clone:function(){return new SAPO.Maps.Statistics.Charts(this.map,OpenLayers.Util.extend({},this.parameters),this.indicatorKey,this.labelsControl,{baseAddress:this.baseAddress,useMessageBoard:this.useMessageBoard});},getZIndex:function(){if(!this.map||!this.map.getOverlaysContainer()){return 0;}
return this.map.getOverlaysContainer().getZIndex();},setZIndex:function(zIndex){if(!this.map||!this.map.getOverlaysContainer()){return 0;}
this.map.getOverlaysContainer().setZIndex(zIndex);},registerEvent:function(eventType,context,func){if(!this.events[eventType]){this.events[eventType]=[];}
var obj={func:func,context:context};this.events[eventType].push(obj);},unRegisterEvent:function(eventType,context,func){var evts=this.events[eventType]?this.events[eventType]:[];for(var i=0;i<evts.length;++i){if(context==evts[i].context&&func==evts[i].func){evts.splice(i,1);return true;}}
return false;},reload:function(){this.fullLoad=true;if(this.isActive()){this.removeMarkers();this.refresh(true);}},getURL:function(){var bounds=this.map.getExtent();this.parameters.bbox=bounds.left+","+bounds.bottom+","+bounds.right+","+bounds.top;var url=SAPO.Maps.Utils.composeUrl(this.baseAddress,this.parameters);return url;},removeMarkersOutsideViewport:function(){var bounds=this.map.getBounds();for(var m in this.markers){if(!bounds.containsLonLat(this.markers[m].getLonLat())){this.map.removeOverlay(this.markers[m]);this.markers[m].unRegisterEvent("click",this,this.chartClicked);this.markers[m].destroy();delete this.markers[m];}}},removeMarkers:function(){for(var m in this.markers){this.map.removeOverlay(this.markers[m]);this.markers[m].unRegisterEvent("click",this,this.chartClicked);this.markers[m].destroy();delete this.markers[m];}},notifyListeners:function(eventType,args){var evts=this.events[eventType]?this.events[eventType]:[];args=args?args:[];var func,context;for(var i=0;i<evts.length;++i){func=evts[i].func;context=evts[i].context;func.apply(context,args);}},propagateState:function(func,params){if(!this.chartLayers){return;}
var chartLayer=false;for(var i=0,len=this.chartLayers.length;i<len;++i){chartLayer=this.chartLayers[i];chartLayer[func].apply(chartLayer,params);}},startRequest:function(){if(this.fullLoad&&this.useMessageBoard){this.map.getMessageBoardControl().showMessage("A carregar gráficos...");this.wroteMessage=SAPO.Maps.Statistics.MessageBoardWarnings.chartsRequest;}},onComplete:function(obj,opts){if(!this.isActive()){return;}
SAPO.Maps.Layer.Custom.prototype.onComplete.apply(this,arguments);if(this.fullLoad&&this.useMessageBoard){this.fullLoad=false;if(this.wroteMessage==SAPO.Maps.Statistics.MessageBoardWarnings.chartsRequest){this.map.getMessageBoardControl().hideMessage();this.wroteMessage=false;}
if(obj.UnavailableData&&this.useMessageBoard){this.map.getMessageBoardControl().showMessage("Não existem dados disponíveis para o conjunto de selecções que efectuou.");this.wroteMessage=SAPO.Maps.Statistics.MessageBoardWarnings.unavailableData;}}
if(opts&&opts.forced){this.removeMarkers();}
else{this.removeMarkersOutsideViewport();}
var indicatorName=obj.IndicatorName;labels=obj.Labels;obj=obj.Graphics;var length=obj.length;var graph,marker,lon,lat;for(var i=0;i<length;++i){graph=obj[i];lon=graph.Coordinates.Lon;lat=graph.Coordinates.Lat;if(this.markers[lon+","+lat]){continue;}
marker=new SAPO.Maps.Marker(new OpenLayers.LonLat(lon,lat),null,{markerImage:graph.URL,size:new OpenLayers.Size(this.parameters.width,this.parameters.height),markerAnchor:new OpenLayers.Pixel(-this.parameters.width/2,-this.parameters.height/2),radius:0});this.markers[lon+","+lat]=marker;marker.registerEvent("click",this,this.chartClicked);this.map.addOverlay(marker);}
if(this.currentLabels){this.labelsControl.removeSetOfLabels(this.indicatorKey,this.currentLabels);}
this.currentLabels=labels;this.labelsControl.appendSetOfLabels(this.indicatorKey,indicatorName,labels,true,false);},onTimeout:function(){SAPO.Maps.Layer.Custom.prototype.onTimeout.apply(this,arguments);if(this.fullLoad&&this.useMessageBoard)
{this.map.getMessageBoardControl().showMessageDelay("Não foi possível carregar os gráficos",2000);this.fullLoad=false;this.wroteMessage=SAPO.Maps.Statistics.MessageBoardWarnings.chartsRequest;}},chartClicked:function(marker){try{this.notifyListeners("chartClicked",[this.map,marker.getLonLat()]);}
catch(e){}},closedMessageBoard:function(){this.wroteMessage=false;},EVENT_TYPES:["chartClicked","labelsArrived"],CLASS_NAME:"SAPO.Maps.Statistics.Charts"});SAPO.Maps.Statistics.StatisticLabels=OpenLayers.Class(SAPO.Maps.Control.Window,{labelsInUse:null,labelsDOMElements:null,labelsSize:null,divHolder:null,borders:null,resizeListener:null,closedDiv:null,initialize:function(callbacks,options){this.labelsSize=new OpenLayers.Size(0,0);this.borders={top:140,left:30,right:0,bottom:45};this.buildHTML();this.labelsInUse={};this.resizeListener=OpenLayers.Function.bind(this.onResize,this);OpenLayers.Event.observe(window,"resize",this.resizeListener);options=OpenLayers.Util.extend({minimumWindowSize:new OpenLayers.Size(200,100),size:this.labelsSize,showMinimizedControl:true},options);this.minimizedControl=new SAPO.Maps.Control.MinimizedLabels(null,this);SAPO.Maps.Control.Window.prototype.initialize.apply(this,["Legenda",this.divHolder,"",callbacks,options]);},destroy:function(){OpenLayers.Event.stopObserving(window,"resize",this.resizeListener);SAPO.Maps.Control.Window.prototype.destroy.apply(this,arguments);this.labelsDOMElements=null;this.resizeListener=null;this.divHolder=null;this.labelsInUse=null;},draw:function(px){this.labelsSize.w=250;this.labelsSize.h=this.map.size.h-this.borders.top-this.borders.bottom;SAPO.Maps.Control.Window.prototype.draw.apply(this,arguments);this.setWindowSize(this.labelsSize);var pos=px;if(!pos){pos=this.getDefaultPosition();}
this.div.style.left=pos.x+"px";this.div.style.top=pos.y+"px";this.contentUser.style.overflow="auto";return this.div;},getDefaultPosition:function(){var pos=new OpenLayers.Pixel(0,0);pos.x=this.map.getSize().w-this.labelsSize.w-this.borders.left;pos.y=this.borders.top;return pos;},addLabel:function(name,title,label,insertInOrder,includeUnits){if(this.labelsDOMElements[name]){this.replaceLabel(name,title,label,insertInOrder,includeUnits);return;}
this.labelsDOMElements[name]={};this.labelsInUse[name]={};this.labelsDOMElements[name].header=this.buildHeader(name);this.labelsDOMElements[name].title=this.buildTitle(title);this.labelsDOMElements[name].content=this.buildContent(name,title,label,insertInOrder,includeUnits);this.divHolder.appendChild(this.labelsDOMElements[name].header);this.divHolder.appendChild(this.labelsDOMElements[name].title);this.divHolder.appendChild(this.labelsDOMElements[name].content);},renameLabel:function(oldName,newName){this.labelsDOMElements[newName]=this.labelsDOMElements[oldName];delete this.labelsDOMElements[oldName];this.labelsInUse[newName]=this.labelsInUse[oldName];delete this.labelsInUse[oldName];var newHeader=this.buildHeader(newName);var oldHeader=this.labelsDOMElements[newName].header;this.divHolder.replaceChild(newHeader,oldHeader);this.labelsDOMElements[newName].header=newHeader;},removeLabel:function(name){if(this.labelsDOMElements[name]){this.divHolder.removeChild(this.labelsDOMElements[name].header);this.divHolder.removeChild(this.labelsDOMElements[name].title);this.divHolder.removeChild(this.labelsDOMElements[name].content);delete this.labelsDOMElements[name];delete this.labelsInUse[name];}},clearLabelsContent:function(name){var labels=this.labelsInUse[name];for(var color in labels){if(color=='listElement'){continue;}
this.labelsInUse[name].listElement.removeChild(this.labelsInUse[name][color].element);delete this.labelsInUse[name][color];}},replaceLabel:function(name,title,label,insertInOrder,includeUnits){var newHeader=this.buildHeader(name);this.divHolder.replaceChild(newHeader,this.labelsDOMElements[name].header);this.labelsDOMElements[name].header=newHeader;this.replaceTitle(name,title);this.labelsInUse[name]={};var newContent=this.buildContent(name,title,label,insertInOrder,includeUnits);this.divHolder.replaceChild(newContent,this.labelsDOMElements[name].content);this.labelsDOMElements[name].content=newContent;},replaceTitle:function(name,title){var newTitle=this.buildTitle(title);this.divHolder.replaceChild(newTitle,this.labelsDOMElements[name].title);this.labelsDOMElements[name].title=newTitle;},appendSetOfLabels:function(name,title,labels,insertInOrder,includeUnits){if(!this.labelsDOMElements[name]){this.addLabel(name,title,labels,insertInOrder);return;}
this.replaceTitle(name,title);var label=false,li=false,othersLi=false;for(var i=0,len=labels.length;i<len;++i){label=labels[i];if(!(label.Color in this.labelsInUse[name])){if(insertInOrder){li=this.insertInOrder(name,this.labelsInUse[name].listElement,label,includeUnits);}else{li=this.buildLabelLine(label,includeUnits);this.labelsInUse[name].listElement.appendChild(li);}
this.labelsInUse[name][label.Color]={element:li,occurrences:1};}else{this.labelsInUse[name][label.Color].occurrences+=1;}}},removeSetOfLabels:function(name,labels){if(!this.labelsDOMElements[name]){return;}
var label=false;for(var i=0,len=labels.length;i<len;++i){label=labels[i];if(!this.labelsInUse[name][label.Color]){continue;}
if(this.labelsInUse[name][label.Color].occurrences>1){this.labelsInUse[name][label.Color].occurrences-=1;continue;}
this.labelsInUse[name].listElement.removeChild(this.labelsInUse[name][label.Color].element);delete this.labelsInUse[name][label.Color];}},openLabel:function(name){if(!this.labelsDOMElements[name]){return;}
this.labelsDOMElements[name].content.style.display="block";this.labelsDOMElements[name].title.style.display="block";this.labelsDOMElements[name].header.childNodes[0].className="smapi_slideUpbtn";this.labelsDOMElements[name].header.childNodes[0].onclick=function(){this.closeLabel(name);}.bindObj(this);},closeLabel:function(name){if(!this.labelsDOMElements[name]){return;}
this.labelsDOMElements[name].content.style.display="none";this.labelsDOMElements[name].title.style.display="none";this.labelsDOMElements[name].header.childNodes[0].className="smapi_slideDownbtn";this.labelsDOMElements[name].header.childNodes[0].onclick=function(){this.openLabel(name);}.bindObj(this);},buildHTML:function(){this.labelsDOMElements={};if(this.divHolder!==null){this.divHolder.innerHTML="";}
else{this.divHolder=document.createElement("div");this.divHolder.className="smaps_window_content_position_legend";}},buildHeader:function(name){var div_header=document.createElement("div");var div_btn=document.createElement("div");var h2_title=document.createElement("h2");div_header.className="smapi_zone_header";div_btn.className="smapi_slideUpbtn";h2_title.appendChild(document.createTextNode(name));div_btn.onclick=function(){this.closeLabel(name);}.bindObj(this);div_header.appendChild(div_btn);div_header.appendChild(h2_title);return div_header;},buildTitle:function(title){var h1=document.createElement('h1');h1.className='legend_title';h1.appendChild(document.createTextNode(title));return h1;},buildContent:function(name,title,labels,insertInOrder,includeUnits){var ul_list=document.createElement("ul");ul_list.className="legend_colors";var li=null;var span=null;for(var i=0;i<labels.length;++i){if(insertInOrder){li=this.insertInOrder(name,ul_list,labels[i]);}else{li=this.buildLabelLine(labels[i],includeUnits);ul_list.appendChild(li);}
this.labelsInUse[name][labels[i].Color]={element:li,occurrences:1};}
this.labelsInUse[name].listElement=ul_list;return ul_list;},insertInOrder:function(name,holder,label,includeUnits){var li=this.buildLabelLine(label,includeUnits);var currChild=false,childs=holder.childNodes;if(label.Label!="Outros"){for(var i=0,len=childs.length;i<len;++i){if(childs[i].childNodes[1].data=='Outros'){currChild=child[i];break;}
if(childs[i].childNodes[1].data>li.childNodes[1].data){currChild=childs[i];break;}}}
if(!currChild){holder.appendChild(li);}else{holder.insertBefore(li,currChild);}
return li;},buildLabelLine:function(label,includeUnits){var li=document.createElement("li");var span=document.createElement("span");span.innerHTML="Intervalo: &nbsp";if(label.Color){span.style.background="#"+label.Color;span.style.color="#"+label.Color;}
li.appendChild(span);li.innerHTML+=" "+label.Label;if(label.Label=="Outros"){li.innerHTML+=" (Incluí os restantes valores da dimensão seleccionada)";}
if(includeUnits&&label.Unit){li.innerHTML+=" ("+label.Unit+")";}
return li;},onResize:function(){var pos=this.getDefaultPosition();this.div.style.left=pos.x+"px";this.div.style.top=pos.y+"px";}});SAPO.Maps.Control.MinimizedLabels=OpenLayers.Class(SAPO.Maps.Control.MinimizedWindow,{imageUrl:'http://imgs.sapo.pt/fotos_gis/Stats/legenda.png',draw:function(px){OpenLayers.Control.prototype.draw.apply(this,arguments);var img=document.createElement('img');img.width=25;img.height=82;img.src=this.imageUrl;this.div.appendChild(img);this.div.className="smaps_window_minimized";if(!this.visible){this.hide();}
this.clickFunction=OpenLayers.Function.bind(this.clickHandler,this);OpenLayers.Event.observe(this.div,'click',this.clickFunction);OpenLayers.Event.observe(this.div,'mousedown',OpenLayers.Event.stop);OpenLayers.Event.observe(this.div,'click',OpenLayers.Event.stop);OpenLayers.Event.observe(this.div,'dblclick',OpenLayers.Event.stop);return this.div;},CLASS_NAME:'SAPO.Maps.Control.MinimizedLabels'});SAPO.Maps.StatisticsShape=OpenLayers.Class({map:null,_isActive:false,boundsToExclude:null,onlyThisBounds:null,tileEvents:null,requester:null,requestId:null,shape:null,shapeEndpoint:null,dragging:false,initialize:function(map,options){this.map=map;OpenLayers.Util.extend(this,options);this.tileEvents=new SAPO.Maps.Map.TileEvents(map,{mouseover:this.request.bindObj(this)});this.requester=SAPO.Maps.Request.prototype.getRequester();},destroy:function(){this.deactivate();this.requester.destroy();this.tileEvents.destroy();},activate:function(){if(this._isActive){return;}
this._isActive=true;this.map.events.register('mousemove',this,this.mousemove);this.map.events.register('movestart',this,this.startDrag);this.map.events.register('moveend',this,this.endDrag);this.tileEvents.activate();},isActive:function(){return this._isActive;},deactivate:function(){if(!this._isActive){return;}
this._isActive=false;this.map.div.style.cursor="";this.map.events.unregister('mousemove',this,this.mousemove);this.map.events.unregister('movestart',this,this.startDrag);this.map.events.unregister('moveend',this,this.endDrag);this.tileEvents.deactivate();},setStatisticShapeEndpoint:function(endpoint){this.cancel();this.shapeEndpoint=endpoint;this.shape=null;this.tileEvents.activate();},resetStatisticsEndpoint:function(){this.cancel();this.shapeEndpoint=null;this.shape=null;this.tileEvents.deactivate();},hasStatistic:function(lonlat){if(!this.checkIsInTheBounds(lonlat)){return SAPO.Maps.StatisticsShape.shapeHasStatisticsResult.Dont;}
if(this.shape!==null){if(this.containsPoint(lonlat)){return SAPO.Maps.StatisticsShape.shapeHasStatisticsResult.Has;}
return SAPO.Maps.StatisticsShape.shapeHasStatisticsResult.Dont;}
return SAPO.Maps.StatisticsShape.shapeHasStatisticsResult.Maybe;},startDrag:function(){this.dragging=true;},endDrag:function(){this.dragging=false;},request:function(bounds){if(!this.shapeEndpoint){return;}
this.cancel();this.shape=null;bounds=bounds.clone();bounds.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));var url=this.shapeEndpoint+"?latitude1="+bounds.bottom+"&longitude1="+bounds.left+"&latitude2="+bounds.top+"&longitude2="+bounds.right+"&zoomLevel="+this.map.getZoom();this.requestId=this.requester.request(url,{timeout:8,onComplete:this.processShape.bindObj(this)});},mousemove:function(evt){if(this.dragging){return;}
var ll=this.map.getLonLatFromContainerPixel(evt.xy);var hasStat=this.hasStatistic(ll);if(hasStat==SAPO.Maps.StatisticsShape.shapeHasStatisticsResult.Has){this.map.div.style.cursor="pointer";}else{this.map.div.style.cursor="";}},processShape:function(obj){this.shape=obj;var ll=this.map.getLonLatFromContainerPixel(this.tileEvents.getLastMousePixel());var hasStat=this.hasStatistic(ll);if(hasStat==SAPO.Maps.StatisticsShape.shapeHasStatisticsResult.Has){this.map.div.style.cursor="pointer";}},checkIsInTheBounds:function(lonlat){if(this.boundsToExclude!==null&&this.boundsToExclude.contains(lonlat.lon,lonlat.lat)){return false;}
if(this.onlyThisBounds!==null&&!this.onlyThisBounds.contains(lonlat.lon,lonlat.lat)){return false;}
return true;},cancel:function(){if(this.requestId!==null){this.requester.cancel(this.requestId);this.requestId=null;}},containsPoint:function(lonlat){if(!this.shape){return true;}
var contained=false;for(var i=0;i<this.shape.length;++i){contained=this.contains(this.shape[i],lonlat);if(contained){return true;}}
return false;},contains:function(shape,lonlat){var approx=OpenLayers.Number.limitSigDigs;var digs=14;var px=approx(lonlat.lon,digs);var py=approx(lonlat.lat,digs);function getX(y,x1,y1,x2,y2){return(((x1-x2)*y)+((x2*y1)-(x1*y2)))/(y1-y2);}
var numSeg=shape.length-1;var start,end,x1,y1,x2,y2,cx,cy;var crosses=0;for(var i=0;i<numSeg;++i){start=shape[i];x1=approx(start.Lon,digs);y1=approx(start.Lat,digs);end=shape[i+1];x2=approx(end.Lon,digs);y2=approx(end.Lat,digs);if(y1==y2){if(py==y1){if(x1<=x2&&(px>=x1&&px<=x2)||x1>=x2&&(px<=x1&&px>=x2)){crosses=-1;break;}}
continue;}
cx=approx(getX(py,x1,y1,x2,y2),digs);if(cx==px){if(y1<y2&&(py>=y1&&py<=y2)||y1>y2&&(py<=y1&&py>=y2)){crosses=-1;break;}}
if(cx<=px){continue;}
if(x1!=x2&&(cx<Math.min(x1,x2)||cx>Math.max(x1,x2))){continue;}
if(y1<y2&&(py>=y1&&py<y2)||y1>y2&&(py<y1&&py>=y2)){++crosses;}}
var contained=(crosses==-1)?1:!!(crosses&1);return contained;},CLASS_NAME:'SAPO.Maps.StatisticsShape'});SAPO.Maps.StatisticsShape.shapeHasStatisticsResult={Dont:1,Has:2,Maybe:3};SAPO.Maps.Map.TileEvents=OpenLayers.Class({map:null,currentTileBounds:null,currentPx:null,callbacks:null,active:false,initialize:function(map,callbacks){this.map=map;this.callbacks=callbacks;},destroy:function(){this.deactivate();this.map.events.unregister("movestart",this,this.deactivate);this.map.events.unregister("moveend",this,this.activate);},activate:function(){if(this.isActive()){return;}
this.active=true;this.map.events.register("movestart",this,this.deactivateMouseMoveEvent);this.map.events.register("moveend",this,this.activateMouseMoveEvent);this.activateMouseMoveEvent();},deactivate:function(){if(!this.isActive()){return;}
this.active=false;this.map.events.unregister("movestart",this,this.deactivateMouseMoveEvent);this.map.events.unregister("moveend",this,this.activateMouseMoveEvent);this.deactivateMouseMoveEvent();},isActive:function(){return this.active;},getLastMousePixel:function(){return this.currentPx;},mouseMove:function(evt){this.currentPx=evt.xy;if(!this.callbacks){return;}
var bounds=this.map.baseLayer.getTileBounds(evt.xy);if(this.currentTileBounds===null){this.triggerEvent(this.callbacks.mouseover,this.callbacks.context,[bounds]);}else{if(this.currentTileBounds!==null&&!this.currentTileBounds.equals(bounds)){this.triggerEvent(this.callbacks.mouseout,this.callbacks.context,[this.currentTileBounds]);this.triggerEvent(this.callbacks.mouseover,this.callbacks.context,[bounds]);}}
this.currentTileBounds=bounds;},triggerEvent:function(func,context,params){if(!func){return;}
if(!context){context=this;}
func.apply(context,params);},activateMouseMoveEvent:function(){this.map.events.register('mousemove',this,this.mouseMove);},deactivateMouseMoveEvent:function(){this.map.events.unregister('mousemove',this,this.mouseMove);},CLASS_NAME:'SAPO.Maps.Map.TileEvents'});SAPO.Maps.Statistics.Tabs=OpenLayers.Class({panel:null,tabsHeaderHolder:null,tabsBodyHolder:null,tabs:null,listeners:null,id:1,selectedTabId:null,dummyHeaderNode:null,callbacks:null,dummyHeader:false,scrollInContent:true,visible:false,initialize:function(callbacks,panel,options){this.callbacks=callbacks;this.panel=panel;this.tabs={};this.listeners={};OpenLayers.Util.extend(this,options);this.buildTabSystem();},destroy:function(){if(this.dummyHeader){this.tabsHeaderHolder.removeChild(this.dummyHeaderNode);OpenLayers.Event.stopObserving(this.dummyHeaderNode,'click',this.listeners.dummyHeader);delete this.listeners.dummyHeader;this.dummyHeaderNode=null;}
var tab=false,listener=false;for(var tabid in this.tabs){tab=this.tabs[tabid];listener=this.listeners[tabid];OpenLayers.Event.stopObserving(tab.header,'click',listener);if(tab.closeBtn){OpenLayers.Event.stopObserving(tab.closeBtn,'click',tab.closeListener);tab.closeListener=null;tab.closeBtn=null;}
this.tabsHeaderHolder.removeChild(tab.header);this.tabsBodyHolder.removeChild(tab.divElement);delete this.listeners[tabid];delete this.tabs[tabid];}
this.hide();this.tabsHeaderHolder=null;this.tabsBodyHolder=null;this.panel=null;},addTab:function(name,div,callbackOpts,showCloseButton){var id=this.id++;var header=document.createElement('a');var tabNameSpan=document.createElement('span');tabNameSpan.className='smapi_tabName';tabNameSpan.appendChild(document.createTextNode(name));header.appendChild(tabNameSpan);header.href="#";this.listeners[id]=OpenLayers.Function.bind(this.selectTab,this,id);OpenLayers.Event.observe(header,'click',this.listeners[id]);this.tabs[id]={tabName:name,divElement:div,header:header,callbackOpts:callbackOpts};if(showCloseButton){header.style.width="90px";var closeBt=document.createElement("span");closeBt.className='smapi_tabCloseBt';header.appendChild(closeBt);var func=OpenLayers.Function.bind(this.tabClosed,this,id);OpenLayers.Event.observe(closeBt,'click',func);this.tabs[id].closeListener=func;this.tabs[id].closeBtn=closeBt;}
this.tabsBodyHolder.appendChild(div);if(this.dummyHeader){this.tabsHeaderHolder.insertBefore(header,this.dummyHeaderNode);}else{this.tabsHeaderHolder.appendChild(header);}
this.selectTab(id);return id;},removeTab:function(id){if(id==this.selectedTabId){var lastTabId=SAPO.Maps.Utils.getLastKey(this.tabs,id);if(lastTabId){this.selectTab(lastTabId);}else{this.selectedTabId=null;}}
var tab=this.tabs[id];var listener=this.listeners[id];OpenLayers.Event.stopObserving(tab.header,'click',listener);this.tabsHeaderHolder.removeChild(tab.header);this.tabsBodyHolder.removeChild(tab.divElement);if(tab.closeBtn){OpenLayers.Event.stopObserving(tab.closeBtn,'click',tab.closeListener);tab.closeListener=null;tab.closeBtn=null;}
delete this.listeners[id];delete this.tabs[id];},renameTab:function(id,name){this.tabs[id].tabName=name;var span=this.tabs[id].header.childNodes[0];span.removeChild(span.childNodes[0]);span.appendChild(document.createTextNode(name));},selectTab:function(id,evt){if(this.selectedTabId==id){return;}
if(this.selectedTabId){this.tabs[this.selectedTabId].divElement.style.display='none';SAPO.Maps.Utils.removeClassName(this.tabs[this.selectedTabId].header,'smapi_current');this.selectedTabId=null;}
SAPO.Maps.Utils.addClassName(this.tabs[id].header,'smapi_current');this.tabs[id].divElement.style.display='block';this.selectedTabId=id;if(evt&&evt.preventDefault){evt.preventDefault();}
if(this.callbacks&&this.callbacks.tabSelected){var args=[id,this.tabs[id].callbackOpts];this.callbacks.tabSelected.apply(this.callbacks.scope,args);}
return false;},getTabContent:function(id){return this.tabs[id].divElement;},removeDummyHeader:function(){if(this.dummyHeader){this.dummyHeader=false;this.tabsHeaderHolder.removeChild(this.dummyHeaderNode);}},addDummyHeader:function(){if(!this.dummyHeader){this.dummyHeader=true;this.tabsHeaderHolder.appendChild(this.dummyHeaderNode);}},show:function(){if(this.visible){return;}
this.visible=true;this.panel.appendChild(this.tabsHeaderHolder);this.panel.appendChild(this.tabsBodyHolder);},hide:function(){if(!this.visible){return;}
this.visible=false;this.panel.removeChild(this.tabsHeaderHolder);this.panel.removeChild(this.tabsBodyHolder);},showTabById:function(id){this.tabs[id].header.style.display="block";},hideTabById:function(id){this.tabs[id].header.style.display="none";},hasTabId:function(id){return this.tabs.hasOwnProperty(id);},getNrTabs:function(){var count=0;for(var tab in this.tabs){++count;}
return count;},getSelectedTabId:function(){return this.selectedTabId;},buildTabSystem:function(){this.tabsHeaderHolder=document.createElement('div');this.tabsHeaderHolder.className='smapi_mapas_tabsystem';this.tabsBodyHolder=document.createElement('div');this.tabsBodyHolder.className='smapi_mapas_contentHolder';if(this.scrollInContent){this.tabsBodyHolder.className+=" smapi_stats_sidebar";}
if(this.dummyHeader){this.dummyHeaderNode=document.createElement('a');this.dummyHeaderNode.innerHTML="Comparar indicador";this.dummyHeaderNode.href="#";this.dummyHeaderNode.className='smapi_newTab';this.listeners.dummyHeader=OpenLayers.Function.bind(this.dummyElementClicked,this);OpenLayers.Event.observe(this.dummyHeaderNode,'click',this.listeners.dummyHeader);this.tabsHeaderHolder.appendChild(this.dummyHeaderNode);}
if(this.visible){this.panel.appendChild(this.tabsHeaderHolder);this.panel.appendChild(this.tabsBodyHolder);}},tabClosed:function(id,evt){if(this.callbacks&&this.callbacks.tabRemoved){this.callbacks.tabRemoved.apply(this.callbacks.scope,[id]);}
if(evt&&evt.preventDefault){evt.preventDefault();}
return false;},dummyElementClicked:function(evt){if(this.callbacks&&this.callbacks.newTab){this.callbacks.newTab.apply(this.callbacks.scope,[]);}
if(evt.preventDefault){evt.preventDefault();}
return false;},CLASS_NAME:'SAPO.Maps.Statistics.Tabs'});SAPO.Maps.Statistics.Panel=OpenLayers.Class({metaInfoUrl:'http://mapas.sapo.pt/MetaInformation.aspx',panel:null,holder:null,elements:null,callbacks:null,elementsObserved:null,allSelects:null,silentDimensionChangedEvt:false,representation:null,showConfigTerritoryDiv:true,showChangeIndicatorLink:true,showTemporalDimensionOnPieCharts:true,pieChartSelectionEnabled:true,initialize:function(panel,callbacks,options){this.panel=panel;this.callbacks=callbacks;OpenLayers.Util.extend(this,options);this.elements={};this.elementsObserved=[];},destroy:function(){this.removeEventHandlers();this.callbacks=null;this.allSelects=null;},removeEventHandlers:function(elements){if(elements){for(var i=0;i<this.elements.length;++i){OpenLayers.Event.stopObservingElement(this.elements[i]);}}
else{for(var j=0;j<this.elementsObserved.length;++j){OpenLayers.Event.stopObservingElement(this.elementsObserved[j]);}
this.elementsObserved=[];}},getSelectByOrder:function(order){var select=false;for(var i=0,len=this.allSelects.length;i<len;++i){select=this.allSelects[i];if(order==select.order){return select;}}
return null;},draw:function(indicatorName,dimensions,selectedDimensions,creditsObj,statisticId){if(!this.holder){this.holder=document.createElement("div");this.holder.className="smapi_stats_results smapi_stats_sidebar";}
this.redraw(indicatorName,dimensions,selectedDimensions);if(!this.holder.parentNode||!this.holder.parentElement){this.panel.appendChild(this.holder);}
if(!this.elements.footer){this.elements.footer=this.buildFooter(statisticId,creditsObj);}else{this.elements.credits_anchor.href=creditsObj.sourceUrl;this.elements.metainfo_anchor.href=SAPO.Maps.Utils.composeUrl(this.metaInfoUrl,{statisticId:statisticId});}
this.holder.appendChild(this.elements.footer);},redraw:function(indicatorName,dimensions,selectedDimensions){if(this.elements.header){this.removeEventHandlers(this.elements.header.childNodes);}
this.elements.header=this.buildHeader(indicatorName);if(this.elements.dimensions){this.removeEventHandlers(this.elements.dimensions.childNodes);}
this.elements.dimensions=this.buildDimensions(dimensions);if(selectedDimensions){this.selectDimensions(selectedDimensions);}
for(var i=this.holder.childNodes.length-1;i>=0;--i){this.holder.removeChild(this.holder.childNodes[i]);}
this.holder.appendChild(this.elements.header);this.holder.appendChild(this.elements.dimensions);},isPieChartSelectionEnabled:function(){return this.pieChartSelectionEnabled;},enablePieChartSelection:function(){if(this.isPieChartSelectionEnabled()){return;}
var pie=this.getPieChartElement();pie.style.display='block';this.pieChartSelectionEnabled=true;},disablePieChartSelection:function(){if(!this.isPieChartSelectionEnabled()){return;}
var pie=this.getPieChartElement();pie.style.display='none';this.pieChartSelectionEnabled=false;},clear:function(){if(!this.holder||!this.holder.parentNode||this.holder.parentNode!=this.panel){return;}
this.panel.removeChild(this.holder);},selectDimensions:function(dimensions){if(!this.allSelects){return;}
this.silentDimensionChangedEvt=true;var select=false,option=false,dimension=false;for(var d=0,dlen=dimensions.length;d<dlen;++d){dimension=dimensions[d];for(var i=0,len=this.allSelects.length;i<len;++i){select=this.allSelects[i];if(select.dimensionType==dimension.type&&select.order==dimension.order){for(var j=0,optionLen=select.options.length;j<optionLen;++j){option=select.options[j];if(option.objectRepresentation.type==dimension.type&&option.objectRepresentation.id==dimension.id&&option.objectRepresentation.territoryView==dimension.territoryView){select.selectedIndex=j;break;}}
break;}}}
this.silentDimensionChangedEvt=false;},setRepresentation:function(representation){for(var i=0;i<this.elements.optionsToSelect.childNodes.length;++i){this.elements.optionsToSelect.childNodes[i].className=this.elements.optionsToSelect.childNodes[i].className.replace(/_selected/,"");}
if(representation===SAPO.Maps.Indicator.representationTypes.pieCharts){this.elements.optionsToSelect.childNodes[1].className+="_selected";}
if(representation===SAPO.Maps.Indicator.representationTypes.territory){this.elements.optionsToSelect.childNodes[0].className+="_selected";}
if(representation===SAPO.Maps.Indicator.representationTypes.barCharts){this.elements.optionsToSelect.childNodes[2].className+="_selected";}
this.representation=representation;},getPieChartElement:function(){return this.elements.optionsToSelect.childNodes[1];},buildRepresentationTypes:function(){var div_wrapper=document.createElement("div");var h2_title=document.createElement("h2");var p_wrapper=document.createElement("p");var a_pie=document.createElement("a");var a_bar=document.createElement("a");var a_territory=document.createElement("a");div_wrapper.className="smapi_zone_header";p_wrapper.className="smapi_graph_type";a_pie.className="smapi_pie";a_pie.title="Representação em gráfico circular";a_bar.className="smapi_bar";a_bar.title="Representação em gráfico de barras";a_territory.className="smapi_territory";a_territory.title="Representação em território";h2_title.innerHTML="Tipo de representa&ccedil;&atilde;o";a_pie.representationType=1;a_bar.representationType=2;a_territory.representationType=0;p_wrapper.appendChild(a_territory);p_wrapper.appendChild(a_pie);p_wrapper.appendChild(a_bar);div_wrapper.appendChild(h2_title);div_wrapper.appendChild(p_wrapper);OpenLayers.Event.observe(a_pie,"click",this.representationChange.bindObj(this));OpenLayers.Event.observe(a_bar,"click",this.representationChange.bindObj(this));OpenLayers.Event.observe(a_territory,"click",this.representationChange.bindObj(this));this.elements.optionsToSelect=p_wrapper;this.elementsObserved.push(a_pie);this.elementsObserved.push(a_bar);this.elementsObserved.push(a_territory);if(this.representation!==null){this.setRepresentation(this.representation);}
if(!this.pieChartSelectionEnabled){this.pieChartSelectionEnabled=true;this.disablePieChartSelection();}
return div_wrapper;},buildHeader:function(indicatorName){var div_wrapper=document.createElement("div");var h1_indicatorName=document.createElement("h1");var div_config=document.createElement("div");div_wrapper.className='smapi_indicator_header_div';h1_indicatorName.className='smapi_indicator_title';h1_indicatorName.innerHTML=indicatorName;div_wrapper.appendChild(h1_indicatorName);if(this.showChangeIndicatorLink){var a_changeIndicator=document.createElement("a");a_changeIndicator.className='smapi_change_indicator';a_changeIndicator.href="#";a_changeIndicator.innerHTML="Alterar&nbsp;indicador";div_wrapper.appendChild(a_changeIndicator);this.elementsObserved.push(a_changeIndicator);OpenLayers.Event.observe(a_changeIndicator,"click",this.indicatorChange.bindObj(this));}
if(this.showConfigTerritoryDiv){var a_config=document.createElement("a");div_config.className='smapi_config';a_config.innerHTML="Configure a vista territorial";div_config.appendChild(document.createElement('div'));div_config.appendChild(a_config);div_wrapper.appendChild(div_config);OpenLayers.Event.observe(a_config,"click",this.configureTerritory.bindObj(this));}
div_wrapper.appendChild(this.buildRepresentationTypes());return div_wrapper;},buildDimensions:function(dimensions){var div_wrapper=document.createElement("div");var h2_title=document.createElement("h2");var ul_list=document.createElement("ul");div_wrapper.className="smapi_dimensions smapi_zone_header";h2_title.innerHTML="Dimens&otilde;es";var length1=dimensions.length;var li,label,select,option;var dimension,id,length2;var allSelects=[];var optGroup=document.createElement('optgroup');optGroup.label="Medidas do Eurostat";for(var i=0;i<length1;++i){dimension=dimensions[i];id=OpenLayers.Util.createUniqueID(this.CLASS_NAME);li=document.createElement("li");label=document.createElement("label");select=document.createElement("select");select.style.width="90%";select.id=id;label.htmlFor=id;select.dimensionType=dimension.DimensionType;select.order=dimension.Order;label.innerHTML=dimension.DimensionName;length2=dimension.Values.length;for(var j=0;j<length2;++j){option=document.createElement("option");option.innerHTML=dimension.Values[j].Name;option.objectRepresentation={type:dimension.DimensionType,id:dimension.Values[j].Id,order:dimension.Order,territoryView:dimension.Values[j].TerritoryView};if(dimension.DimensionType=='Geo'&&dimension.Values[j].TerritoryView=='NUTS1'||dimension.Values[j].TerritoryView=='NUTS2'||dimension.Values[j].TerritoryView=='NUTS3'){optGroup.appendChild(option);}else{select.appendChild(option);}}
label.appendChild(document.createElement("br"));label.appendChild(select);if(dimension.DimensionType=='Geo'&&optGroup.childNodes.length>0){if(select.childNodes.length>0){select.insertBefore(optGroup,select.options[0]);}else{select.appendChild(optGroup);}}
li.appendChild(label);ul_list.appendChild(li);allSelects.push(select);select.allSelects=allSelects;OpenLayers.Event.observe(select,"change",this.dimensionChange.bindObj(this));}
this.allSelects=allSelects;div_wrapper.appendChild(h2_title);div_wrapper.appendChild(ul_list);return div_wrapper;},buildFooter:function(statisticId,creditsObj){var footer=document.createElement("div");footer.className="smapi_stats_footer";var credits=document.createElement("div");credits.className="smapi_credits";credits.innerHTML="Fonte: ";var a=document.createElement("a");a.innerHTML=creditsObj.source;a.href=creditsObj.sourceUrl;a.target="_blank";credits.appendChild(a);var metainfo=document.createElement('div');metainfo.className="smapi_metainfo";var a_metainfo=document.createElement('a');a_metainfo.href=SAPO.Maps.Utils.composeUrl(this.metaInfoUrl,{statisticId:statisticId});a_metainfo.target="_blank";var img=document.createElement('img');img.src="http://imgs.sapo.pt/fotos_gis/Stats/botaoMi_on.gif";img.title="MetaInformação";a_metainfo.appendChild(img);metainfo.appendChild(a_metainfo);footer.appendChild(metainfo);footer.appendChild(credits);this.elements.credits_anchor=a;this.elements.metainfo_anchor=a_metainfo;return footer;},indicatorChange:function(evt){if(this.callbacks&&this.callbacks.indicatorChange){this.callbacks.indicatorChange.apply(this.callbacks.scope,[]);}
if(evt&&evt.preventDefault){evt.preventDefault();}
return false;},configureTerritory:function(evt){if(this.callbacks&&this.callbacks.configureTerritory){this.callbacks.configureTerritory.apply(this.callbacks.scope,[]);}
if(evt&&evt.preventDefault){evt.preventDefault();}
return false;},dimensionChange:function(evt){if(this.silentDimensionChangedEvt){return;}
if(this.callbacks&&this.callbacks.dimensionChange){var allSelects=this.allSelects;var dimensions=[];var target;for(var i=0;i<allSelects.length;++i){target=allSelects[i];dimensions.push(target.options[target.selectedIndex].objectRepresentation);}
this.callbacks.dimensionChange.apply(this.callbacks.scope,[dimensions]);}},representationChange:function(evt){var target=evt.originalTarget?evt.originalTarget:evt.srcElement;var representation=target.representationType;if(representation==SAPO.Maps.Indicator.representationTypes.pieCharts&&!this.isPieChartSelectionEnabled()){return;}
this.setRepresentation(representation);if(this.callbacks&&this.callbacks.representationChange){this.callbacks.representationChange.apply(this.callbacks.scope,[representation]);}
if(evt&&evt.preventDefault){evt.preventDefault();}
return false;},CLASS_NAME:'SAPO.Maps.Statistics.Panel'});SAPO.Maps.Statistics.Panel.Territory=OpenLayers.Class(SAPO.Maps.Statistics.Panel,{sliderControl:null,opacityValue:50,maxNrClasses:7,nrClasses:2,colors:null,callbacks:null,initialize:function(panel,callbacks,options){SAPO.Maps.Statistics.Panel.prototype.initialize.apply(this,arguments);},redraw:function(indicatorName,dimensions,selectedDimensions){SAPO.Maps.Statistics.Panel.prototype.redraw.apply(this,arguments);if(!("style"in this.elements)){this.elements.style=this.buildStyle();}
this.holder.appendChild(this.elements.style);},setOpacity:function(opacity,notify){this.opacityValue=parseInt(opacity*100,10);this.elements.inputOpacity.value=this.opacityValue+"%";this.sliderControl.setValue(this.opacityValue,true);if(notify&&this.callbacks&&this.callbacks.opacityChange){this.callbacks.opacityChange.apply(this.callbacks.scope,[this.opacityValue/100]);}},setColors:function(colors){var startColor=colors.startColor.replace(/#/,"");var endColor=colors.endColor.replace(/#/,"");this.colors=colors;if(!this.holder){return;}
this.elements.inputInitialColor.value=startColor;this.elements.inputFinalColor.value=endColor;this.elements.spanInitialColor.style.backgroundColor="#"+startColor;this.elements.spanFinalColor.style.backgroundColor="#"+endColor;this.checkIsPredefinedColor(startColor,endColor);},setNrClasses:function(nrClasses){if(nrClasses<2||nrClasses>this.maxNrClasses){return;}
this.nrClasses=nrClasses;this.elements.selectNrClasses.selectedIndex=nrClasses-2;},checkIsPredefinedColor:function(startColor,endColor){if(this.elements.selectedColor){this.elements.selectedColor.className="";}
var predefined=null;var color=(startColor+endColor).toUpperCase();var enumColors=SAPO.Maps.Statistics.Panel.Territory.customColors;switch(color){case enumColors.red.startColor+enumColors.red.endColor:predefined=this.elements.aColorRed;break;case enumColors.orange.startColor+enumColors.orange.endColor:predefined=this.elements.aColorOrange;break;case enumColors.green.startColor+enumColors.green.endColor:predefined=this.elements.aColorGreen;break;case enumColors.blue.startColor+enumColors.blue.endColor:predefined=this.elements.aColorBlue;break;}
if(predefined){predefined.parentNode.className="selected";this.elements.selectedColor=predefined.parentNode;}},buildStyle:function(){var div_wrapper=document.createElement("div");var h2_title=document.createElement("h2");var div_visual_options=document.createElement("div");var h3_opacity_title=document.createElement("h3");var div_slider=document.createElement("div");var span_input_start=document.createElement("span");var input_opacity=document.createElement("input");var div_colors=document.createElement("div");var h3_colors_title=document.createElement("h3");var ul_colors=document.createElement("ul");var li_color_red=document.createElement("li");var li_color_orange=document.createElement("li");var li_color_green=document.createElement("li");var li_color_blue=document.createElement("li");var a_color_red=document.createElement("a");var a_color_orange=document.createElement("a");var a_color_green=document.createElement("a");var a_color_blue=document.createElement("a");var h3_color_customization=document.createElement("h3");var label_initial_color=document.createElement("label");var input_initial_color=document.createElement("input");var span_initial_color=document.createElement("span");var label_final_color=document.createElement("label");var input_final_color=document.createElement("input");var span_final_color=document.createElement("span");var p_classes=document.createElement("p");var select_classes=document.createElement("select");var random=Math.random();input_initial_color.id=this.CLASS_NAME+"_"+random;label_initial_color.htmlFor=this.CLASS_NAME+"_"+random;random=Math.random();input_final_color.id=this.CLASS_NAME+"_"+random;label_final_color.htmlFor=this.CLASS_NAME+"_"+random;div_wrapper.className="smapi_zone_header";div_visual_options.className="smapi_visual_options smapi_the_next_div";div_slider.className="smapi_slider";span_input_start.className="smapi_input_start";input_opacity.className="smapi_opacity_input";div_colors.className="smapi_colors";a_color_red.className="smapi_color_red";a_color_orange.className="smapi_color_orange";a_color_green.className="smapi_color_green";a_color_blue.className="smapi_color_blue";a_color_red.colors=SAPO.Maps.Statistics.Panel.Territory.customColors.red;a_color_orange.colors=SAPO.Maps.Statistics.Panel.Territory.customColors.orange;a_color_green.colors=SAPO.Maps.Statistics.Panel.Territory.customColors.green;a_color_blue.colors=SAPO.Maps.Statistics.Panel.Territory.customColors.blue;label_initial_color.className="smapi_smapi_costum_label";input_initial_color.className="smapi_smapi_costum_input";span_initial_color.className="smapi_selected_color";label_final_color.className="smapi_smapi_costum_label";input_final_color.className="smapi_smapi_costum_input";span_final_color.className="smapi_selected_color";h2_title.innerHTML="Op&ccedil;&otilde;es de visualiza&ccedil;&atilde;o";h3_opacity_title.innerHTML="Opacidade";var callbacks={scope:this,slideChanged:this.opacityChange};this.sliderControl=new SAPO.Maps.Control.SliderControl(callbacks,{div:div_slider,controlSize:220,value:this.opacityValue});this.sliderControl.draw();span_input_start.innerHTML="&nbsp;";input_opacity.type="text";input_opacity.value=this.opacityValue+"%";this.elements.inputOpacity=input_opacity;h3_colors_title.innerHTML="Cores predefinidas";a_color_red.href=a_color_orange.href=a_color_green.href=a_color_blue.href="#";a_color_red.innerHTML=a_color_orange.innerHTML=a_color_green.innerHTML=a_color_blue.innerHTML="&nbsp;";h3_color_customization.innerHTML="Cores personalizadas";label_initial_color.innerHTML="Cor mínima";input_initial_color.type="text";input_initial_color.size="7";label_final_color.innerHTML="Cor máxima";input_final_color.type="text";input_final_color.size="7";span_initial_color.innerHTML="&nbsp;";span_final_color.innerHTML="&nbsp;";var x=new jscolor.color(input_initial_color,{styleElement:span_initial_color});x=new jscolor.color(input_final_color,{styleElement:span_final_color});p_classes.innerHTML="N&uacute;mero de intervalos";var option;for(var i=2;i<=this.nrClasses;++i){option=document.createElement("option");option.value=option.innerHTML=i;select_classes.appendChild(option);}
select_classes.selectedIndex=this.nrClasses-2;li_color_red.appendChild(a_color_red);li_color_orange.appendChild(a_color_orange);li_color_green.appendChild(a_color_green);li_color_blue.appendChild(a_color_blue);ul_colors.appendChild(li_color_red);ul_colors.appendChild(li_color_orange);ul_colors.appendChild(li_color_green);ul_colors.appendChild(li_color_blue);p_classes.appendChild(select_classes);div_colors.appendChild(h3_colors_title);div_colors.appendChild(ul_colors);div_colors.appendChild(h3_color_customization);div_colors.appendChild(label_initial_color);div_colors.appendChild(input_initial_color);div_colors.appendChild(span_initial_color);div_colors.appendChild(document.createElement("br"));div_colors.appendChild(label_final_color);div_colors.appendChild(input_final_color);div_colors.appendChild(span_final_color);div_colors.appendChild(p_classes);div_visual_options.appendChild(h3_opacity_title);div_visual_options.appendChild(div_slider);div_visual_options.appendChild(span_input_start);div_visual_options.appendChild(input_opacity);div_visual_options.appendChild(div_colors);div_wrapper.appendChild(h2_title);div_wrapper.appendChild(div_visual_options);OpenLayers.Event.observe(input_opacity,"change",this.opacityValueChange.bindObj(this));OpenLayers.Event.observe(input_initial_color,"change",this.colorsChange.bindObj(this));OpenLayers.Event.observe(input_final_color,"change",this.colorsChange.bindObj(this));OpenLayers.Event.observe(a_color_red,"click",this.predefinedColorChange.bindObj(this,a_color_red));OpenLayers.Event.observe(a_color_orange,"click",this.predefinedColorChange.bindObj(this,a_color_orange));OpenLayers.Event.observe(a_color_green,"click",this.predefinedColorChange.bindObj(this,a_color_green));OpenLayers.Event.observe(a_color_blue,"click",this.predefinedColorChange.bindObj(this,a_color_blue));OpenLayers.Event.observe(select_classes,"change",this.classesChange.bindObj(this));this.elements.inputOpacity=input_opacity;this.elements.inputInitialColor=input_initial_color;this.elements.spanInitialColor=span_initial_color;this.elements.spanFinalColor=span_final_color;this.elements.inputFinalColor=input_final_color;this.elements.aColorRed=a_color_red;this.elements.aColorOrange=a_color_orange;this.elements.aColorGreen=a_color_green;this.elements.aColorBlue=a_color_blue;this.elements.selectNrClasses=select_classes;this.elementsObserved.push(input_opacity);this.elementsObserved.push(input_initial_color);this.elementsObserved.push(input_final_color);this.elementsObserved.push(a_color_red);this.elementsObserved.push(a_color_orange);this.elementsObserved.push(a_color_green);this.elementsObserved.push(a_color_blue);this.elementsObserved.push(select_classes);if(this.colors){input_initial_color.value=this.colors.startColor;input_final_color.value=this.colors.endColor;span_initial_color.style.background="#"+this.colors.startColor;span_final_color.style.background="#"+this.colors.endColor;this.checkIsPredefinedColor(this.colors.startColor,this.colors.endColor);}
return div_wrapper;},opacityChange:function(value){this.setOpacity(value/100,true);},opacityValueChange:function(){var value=this.elements.inputOpacity.value.replace(/%/,"");if(isNaN(value)){this.elements.inputOpacity.value=this.opacityValue+"%";return;}
this.setOpacity(value/100,true);},colorsChange:function(){if(this.callbacks&&this.callbacks.colorsChange){var obj={startColor:"#"+this.elements.inputInitialColor.value,endColor:"#"+this.elements.inputFinalColor.value};this.callbacks.colorsChange.apply(this.callbacks.scope,[obj]);}},predefinedColorChange:function(predifinedColorElem,evt){var colors=predifinedColorElem.colors;this.elements.inputInitialColor.value=colors.startColor;this.elements.inputFinalColor.value=colors.endColor;this.elements.spanInitialColor.style.backgroundColor="#"+colors.startColor;this.elements.spanFinalColor.style.backgroundColor="#"+colors.endColor;if(this.elements.selectedColor){this.elements.selectedColor.className="";}
predifinedColorElem.parentNode.className="selected";this.elements.selectedColor=predifinedColorElem.parentNode;this.colorsChange();if(evt&&evt.preventDefault){evt.preventDefault();}
return false;},classesChange:function(evt){if(this.callbacks&&this.callbacks.classesChange){var select=this.elements.selectNrClasses;var value=select.options[select.selectedIndex].value;this.callbacks.classesChange.apply(this.callbacks.scope,[value]);}},CLASS_NAME:"SAPO.Maps.Statistics.Panel.Territory"});SAPO.Maps.Statistics.Panel.Territory.customColors={red:{startColor:'FFEAE5',endColor:'CC0404'},orange:{startColor:'FFF4E5',endColor:'CF8600'},green:{startColor:'E8F1E5',endColor:'1B7900'},blue:{startColor:'E5E6F2',endColor:'000B7C'}};SAPO.Maps.Statistics.Panel.Graphics=OpenLayers.Class(SAPO.Maps.Statistics.Panel,{sliderControl:null,graphicSize:100,graphicMaxSize:200,callbacks:null,disabledSelect:null,axisMessage:'Dimensão no eixo do X:',axisDimensionNotFound:false,initialize:function(panel,callbacks,options){SAPO.Maps.Statistics.Panel.prototype.initialize.apply(this,arguments);if(options&&options.width&&options.height){this.graphicSize=options.width>options.height?options.width:options.height;if(this.graphicSize>this.graphicMaxSize){this.graphicSize=this.graphicMaxSize;}}},redraw:function(indicatorName,dimensions){SAPO.Maps.Statistics.Panel.prototype.redraw.apply(this,arguments);this.elements.graphic=this.buildGraphic(dimensions);this.holder.appendChild(this.elements.graphic);if(this.axisDimensionNotFound){this.axisChange();}},selectAxisDimension:function(axisObj){var options=this.elements.selectAxisDimension.options,option=false,ids=false;this.silentDimensionChangedEvt=true;this.axisDimensionNotFound=true;for(var i=0,len=options.length;i<len;++i){option=options[i];if(option.objectRepresentation.type==axisObj.type&&option.objectRepresentation.order==axisObj.order){var diff=SAPO.Maps.Utils.diferent(option.ids,axisObj.ids);if(diff===false){this.axisDimensionNotFound=false;this.elements.selectAxisDimension.selectedIndex=i;break;}}}
this.disableDimensionSelect(axisObj.order);this.silentDimensionChangedEvt=false;},getSelectedAxisDimension:function(){if(this.elements&&this.elements.selectAxisDimension){return this.elements.selectAxisDimension.options[this.elements.selectAxisDimension.selectedIndex].objectRepresentation;}
return null;},setChartSize:function(width,height){var size=width>height?width:height;this.sizeChange((size/this.graphicMaxSize)*100,true);},buildGraphic:function(dimensions){var div_wrapper=document.createElement("div");var h2_title=document.createElement("h2");var p_axis=document.createElement("p");var select_axisDimension=document.createElement("select");select_axisDimension.style.width="90%";var p_size=document.createElement("p");var p_size_title=document.createElement("p");var div_slider=document.createElement("div");var span_size=document.createElement("span");div_wrapper.className="smapi_zone_header";div_slider.className="smapi_slider";span_size.className="smapi_graphic_size";h2_title.innerHTML="Gr&aacute;fico";p_axis.innerHTML=this.axisMessage+'<br/>';var dimension,option;for(var i=0;i<dimensions.length;++i){if(i===1){continue;}
dimension=dimensions[i];if(!this.showTemporalDimensionOnPieCharts&&dimension.DimensionType=="Year"){continue;}
option=document.createElement("option");option.innerHTML=dimension.DimensionName;option.objectRepresentation={type:dimension.DimensionType,order:dimension.Order,ids:dimension.Values};select_axisDimension.appendChild(option);}
p_size_title.innerHTML="Tamanho do gr&aacute;fico:";var callbacks={scope:this,slideChanged:this.sizeChange};this.sliderControl=new SAPO.Maps.Control.SliderControl(callbacks,{div:div_slider,controlSize:220,value:Math.floor((this.graphicSize/this.graphicMaxSize)*100)});this.sliderControl.draw();span_size.innerHTML=this.graphicSize+"x"+this.graphicSize;p_axis.appendChild(select_axisDimension);p_size.appendChild(p_size_title);p_size.appendChild(div_slider);p_size.appendChild(span_size);div_wrapper.appendChild(h2_title);div_wrapper.appendChild(p_axis);div_wrapper.appendChild(document.createElement("br"));div_wrapper.appendChild(p_size);OpenLayers.Event.observe(select_axisDimension,"change",this.axisChange.bindObj(this));this.elements.selectAxisDimension=select_axisDimension;this.elements.spanSize=span_size;var selectedOrder=select_axisDimension.options[select_axisDimension.selectedIndex].objectRepresentation.order;this.disableDimensionSelect(selectedOrder);return div_wrapper;},disableDimensionSelect:function(order){if(this.disabledSelect){this.disabledSelect.disabled=false;}
var select=this.getSelectByOrder(order);select.disabled=true;this.disabledSelect=select;},axisChange:function(){if(this.silentDimensionChangedEvt){return;}
var representation=this.elements.selectAxisDimension.options[this.elements.selectAxisDimension.selectedIndex].objectRepresentation;this.disableDimensionSelect(representation.order);if(this.callbacks&&this.callbacks.axisChange){this.callbacks.axisChange.apply(this.callbacks.scope,[representation]);}},sizeChange:function(value,silent){this.graphicSize=Math.floor((value*this.graphicMaxSize)/100);if(this.graphicSize>this.graphicMaxSize){this.graphicSize=this.graphicMaxSize;}
this.elements.spanSize.innerHTML=this.graphicSize+"x"+this.graphicSize;if(!silent&&this.callbacks&&this.callbacks.sizeChange){this.callbacks.sizeChange.apply(this.callbacks.scope,[this.graphicSize,this.graphicSize]);}},CLASS_NAME:"SAPO.Maps.Statistics.Panel.Graphics"});SAPO.Maps.Statistics.BallonRenderer=OpenLayers.Class(SAPO.Maps.PopupRenderer,{tabNames:{Pie:'Gráfico circular',Bars:'Gráfico de barras',Table:'Tabela'},tabEnum:{Pie:'Pie',Bars:'Bars',Table:'Table'},labelName:{Pie:'Grandeza a medir',Bars:'Eixo do X'},titleElement:null,currentTab:null,holderDiv:null,tabs:null,tabContents:null,tabIds:null,listeners:null,tableSelects:null,axisSelect:null,axisDimensionHolder:null,dimensions:null,callbacks:null,silentDimensionChangedEvt:false,showTemporalDimensionOnPieCharts:true,yearDimensionDisclaimer:'Atenção: Seleccionado o periodo de referência dos dados, os valores podem não ser aditivos.',temporalOption:null,initialize:function(callbacks,options){this.currentTab=SAPO.Maps.Indicator.dataTypes.table;this.listeners={};this.tableSelects={};this.tabContents={};this.tabIds={};this.holderDiv=document.createElement('div');this.titleElement=document.createElement('h1');this.titleElement.className='smapi_popup_stats_title';this.holderDiv.appendChild(this.titleElement);OpenLayers.Util.extend(this,options);this.tabs=new SAPO.Maps.Statistics.Tabs({scope:this,tabSelected:this.tabSelected},this.holderDiv,{visible:true,scrollInContent:false});this.addTabs();this.callbacks=callbacks;},destroy:function(){var tabElem=false;var listener=false;this.tabs.destroy();if(this.tableSelects){this.removeSelectListeners();}
if(this.axisSelect){this.removeAxisSelectListeners();}},setDimensions:function(dimensions,selectAxisDimension){this.dimensions=dimensions;if(this.axisSelect){this.removeAxisSelectListeners();}
this.createAxisSelect(this.labelName.Pie);if(selectAxisDimension){this.selectAxisDimension(selectAxisDimension);}
if(!this.showTemporalDimensionOnPieCharts){if(this.hasOnlyTemporalDimension()){this.tabs.hideTabById(this.tabIds[this.tabEnum.Pie]);}else{this.tabs.showTabById(this.tabIds[this.tabEnum.Pie]);}
if(this.callbacks&&this.callbacks.popupResized){this.callbacks.popupResized.apply(this.callbacks.scope,[]);}}},selectTab:function(tab,silence){var tabId=this.tabIds[tab];this.tabs.selectTab(tabId);},getSelectedTab:function(){return this.currentTab;},getHolder:function(){if(this.currentTab!=SAPO.Maps.Indicator.dataTypes.table&&this.axisDimensionHolder){var tabId=this.tabIds[this.currentTab];this.tabs.getTabContent(tabId).appendChild(this.axisDimensionHolder);}
return this.holderDiv;},isDrawn:function(tab){return this.tabContents[tab];},getSelectedAxisDimension:function(){if(!this.axisSelect){return null;}
var selectedIdx=this.axisSelect.selectedIndex;return this.axisSelect.options[selectedIdx].objectRepresentation;},selectAxisDimension:function(axisObj){var options=this.axisSelect.options,option=false,ids=false;this.silentDimensionChangedEvt=true;for(var i=0,len=options.length;i<len;++i){option=options[i];if(option.objectRepresentation.type==axisObj.type&&option.objectRepresentation.order==axisObj.order){var diff=SAPO.Maps.Utils.diferent(option.ids,axisObj.ids);if(diff===false){this.axisSelect.selectedIndex=i;break;}}}
this.silentDimensionChangedEvt=false;},showWaitIcon:function(tab){var tabId=this.tabIds[tab];if(!tabId){return;}
var tabContent=this.tabs.getTabContent(tabId);if(!SAPO.Maps.Utils.checkWaitIcon(tabContent)){SAPO.Maps.Utils.displayWaitIcon(tabContent);}},removeWaitIcon:function(tab){var tabId=this.tabIds[tab];if(!tabId){return;}
var tabContent=this.tabs.getTabContent(tabId);SAPO.Maps.Utils.removeWaitIcon(tabContent);},showErrorMessage:function(tab,errorMsg,anchor){var tabId=this.tabIds[tab];if(!tabId){return;}
var tabContent=this.tabs.getTabContent(tabId);SAPO.Maps.Utils.displayMessageToRetry(tabContent,errorMsg,anchor,SAPO.Maps.Utils.MessageType.WARNING);},removeErrorMessge:function(tab){var tabId=this.tabIds[tab];if(!tabId){return;}
var tabContent=this.tabs.getTabContent(tabId);SAPO.Maps.Utils.removeErrorMessage(tabContent);},drawTabElement:function(tab,obj,credits){var div=false;if(this.currentTab==SAPO.Maps.Indicator.dataTypes.table){div=this.renderStatisticTable(obj);}else{div=this.renderStatisticChart(obj);}
if(credits){var creditsDiv=this.buildCredits(credits);div.appendChild(creditsDiv);}
if(this.currentTab==SAPO.Maps.Indicator.dataTypes.pie){var disclaimerDiv=document.createElement('div');disclaimerDiv.className="smapi_popup_centered smapi_popup_disclaimer";disclaimerDiv.innerHTML=this.yearDimensionDisclaimer;div.appendChild(disclaimerDiv);}
var tabId=this.tabIds[tab];this.tabContents[tab]=div;this.titleElement.innerHTML=obj.Title;var html=SAPO.Maps.Utils.getOuterHTML(div);var tabContentSize=OpenLayers.Util.getRenderedDimensions(html);this.tabs.getTabContent(tabId).appendChild(div);},clear:function(){this.titleElement.innerHTML="";var tabElem=false;for(var tab in this.tabContents){tabElem=this.tabContents[tab];if(tabElem.parentNode){tabElem.parentNode.removeChild(tabElem);}
if(tab==SAPO.Maps.Indicator.dataTypes.table&&this.tableSelects){this.removeSelectListeners();}
delete this.tabContents[tab];}
for(var tab2 in SAPO.Maps.Indicator.dataTypes){this.removeErrorMessge(SAPO.Maps.Indicator.dataTypes[tab2]);this.removeWaitIcon(SAPO.Maps.Indicator.dataTypes[tab2]);}
if(this.axisDimensionHolder.parentNode||this.axisDimensionHolder.parentElement){this.axisDimensionHolder.parentNode.removeChild(this.axisDimensionHolder);}},clearTab:function(tab){if(this.tabContents&&this.tabContents[tab]){if(tab==SAPO.Maps.Indicator.dataTypes.table&&this.tableSelects){this.removeSelectListeners();}
var tabElem=this.tabContents[tab];tabElem.parentNode.removeChild(tabElem);delete this.tabContents[tab];}
this.removeErrorMessge(tab);this.removeWaitIcon(tab);},addTabs:function(){var div=false,tabId=false,currTab=this.currentTab;for(var tab in this.tabNames){div=document.createElement('div');this.tabIds[tab]=this.tabs.addTab(this.tabNames[tab],div,tab);}
this.currentTab=currTab;var selectedTabId=this.tabIds[currTab];this.tabs.selectTab(selectedTabId);},buildCredits:function(credits){var div=document.createElement('div');div.className="smapi_popup_centered";div.innerHTML="Fonte: ";var a=document.createElement('a');a.innerHTML=credits.source;a.target="_blank";a.href=credits.sourceUrl;div.appendChild(a);return div;},renderStatisticTable:function(data,display){if(!display){display=this.getDefaultDisplay(data.Data);}
newData=this.processData(display);var table=document.createElement('table');table.border="1";var tbody=document.createElement('tbody');var tr=document.createElement('tr');var th=false;var td=false;var dimension=false;var i;if(display.onRows){dimension=display.onRows;th=document.createElement('th');th.innerHTML=dimension.DimensionName;th.rowSpan=(display.onColumns.length*2)+1;tr.appendChild(th);}
tbody.appendChild(tr);var dimensionValue=false;var nrUsedColumns=1;var select=false;for(i=0;i<display.onColumns.length;++i){dimension=display.onColumns[i];tr=document.createElement('tr');th=document.createElement('th');th.innerHTML=dimension.DimensionName;th.colSpan=newData.nrCels;tr.appendChild(th);tbody.appendChild(tr);tr=document.createElement('tr');tbody.appendChild(tr);for(var currCols=0;currCols<nrUsedColumns;++currCols){for(var j=0;j<dimension.Values.length;++j){dimensionValue=dimension.Values[j];th=document.createElement('th');select=this.createSelectElement(dimension.DimensionName,dimensionValue.Id);th.appendChild(select);th.colSpan=(newData.nrCels/dimension.Values.length)/nrUsedColumns;tr.appendChild(th);}}
nrUsedColumns*=dimension.Values.length;}
if(display.onRows){for(var row=0;row<display.onRows.Values.length;++row){dimensionValue=display.onRows.Values[row];tr=document.createElement('tr');th=document.createElement('th');th.innerHTML=dimensionValue.Name;tr.appendChild(th);tbody.appendChild(tr);this.fillRowWithValues(row,newData.nrCels,display,tr,data);}}else{tr=document.createElement('tr');this.fillRowWithValues(0,newData.nrCels,display,tr,data);tbody.appendChild(tr);}
table.appendChild(tbody);var holder=document.createElement('div');holder.appendChild(table);holder.className="smapi_tableHolder";return holder;},fillRowWithValues:function(row,nrCels,displayObj,tr,data){for(var cel=0;cel<nrCels;++cel){td=document.createElement('td');td.innerHTML=this.getValue(row,cel,nrCels,displayObj,data.Data);tr.appendChild(td);}},getValue:function(row,cel,nrCels,displayObj,data){var ids=[];if(displayObj.onRows){ids.push(displayObj.onRows.Values[row].Id);}
var id=false;var dimension=false;for(var i=0;i<displayObj.onColumns.length;++i){dimension=displayObj.onColumns[i];var leafs=nrCels/dimension.Values.length;var idx=Math.floor(cel/leafs);ids.push(dimension.Values[idx].Id);}
ids.sort();for(var j=0;j<data.Values.length;++j){if(data.Values[j].DimensionIds.length!=ids.length){continue;}
if(!data.Values[j].DimensionIds.isSorted){data.Values[j].DimensionIds.sort();data.Values[j].DimensionIds.isSorted=true;}
if(this.checkIfTheArraysAreEquals(data.Values[j].DimensionIds,ids)===true){return data.Values[j].Value;}}
return-1;},checkIfTheArraysAreEquals:function(array1,array2){if(array1.length!=array2.length){return false;}
for(var i=0;i<array1.length;++i){if(array1[i]!=array2[i]){return false;}}
return true;},getDefaultDisplay:function(data){var display={onRows:false,onColumns:[]};var dimension=false;for(var i=0;i<data.DimensionsMetadata.length;++i){dimension=data.DimensionsMetadata[i];if(dimension.DimensionType==='Geo'){display.onRows=dimension;}else{display.onColumns.push(dimension);}}
return display;},processData:function(display){var obj={nrCels:1,nrRows:1};var dimension=false;for(var i=0;i<display.onColumns.length;++i){dimension=display.onColumns[i];obj.nrCels*=dimension.Values.length;}
if(display.onRows){obj.nrRows*=display.onRows.Values.length;}
return obj;},createSelectElement:function(dimensionName,selectedDimensionId){if(this.tableSelects[dimensionName]){var dimensionSelect=this.tableSelects[dimensionName];var idx=0;var opt=false;for(var k=0;k<dimensionSelect.options.length;++k){opt=dimensionSelect.options[k];if(opt.id==selectedDimensionId){idx=k;break;}}
dimensionSelect.selectedIndex=idx;return this.tableSelects[dimensionName];}
var dimension=false;for(var i=0,len=this.dimensions.length;i<len;++i){if(this.dimensions[i].DimensionName==dimensionName){dimension=this.dimensions[i];break;}}
var select=document.createElement('select');select.style.width="250px";var option=false,dimValue=false,selectedIdx=0;for(var j=0,length=dimension.Values.length;j<length;++j){dimValue=dimension.Values[j];option=document.createElement('option');option.appendChild(document.createTextNode(dimValue.Name));option.id=dimValue.Id;option.territoryView=dimValue.TerritoryView;if(dimValue.Id==selectedDimensionId){selectedIdx=j;}
select.appendChild(option);}
select.selectedIndex=selectedIdx;select.dimensionType=dimension.DimensionType;select.order=dimension.Order;var listener=OpenLayers.Function.bind(this.changedTableDimension,this);OpenLayers.Event.observe(select,'change',listener);this.tableSelects[dimensionName]=select;this.listeners[dimensionName]=listener;return select;},removeSelectListeners:function(){var listener=false;for(var select in this.tableSelects){listener=this.listeners[select];OpenLayers.Event.stopObserving(this.tableSelects[select],'change',listener);delete this.tableSelects[select];delete this.listeners[select];}},renderStatisticChart:function(data){var holder=document.createElement('div'),imgHolder=document.createElement('div'),img=document.createElement('img'),labelsHolder=document.createElement('div'),p=false,span=false;if(this.currentTab==SAPO.Maps.Indicator.dataTypes.pie){img.width=250;img.height=250;img.className='imgPieChart';}else{img.width=350;img.height=250;img.className='imgBarChart';}
function imageLoad(){this.className='';OpenLayers.Event.stopObserving(this,"load",this._onImgLoad);this._loadFunc=null;}
img._loadFunc=OpenLayers.Function.bind(imageLoad,img);OpenLayers.Event.observe(img,'load',img._loadFunc);imgHolder.appendChild(img);holder.appendChild(imgHolder);holder.className="smapi_statistics_popup smapi_clearfix";imgHolder.className="smapi_statistics_popup_img";labelsHolder.className="smapi_statistics_popup_labels";img.src=data.ChartImageURL;if(data.Labels){holder.appendChild(labelsHolder);var others=false;for(var i=0;i<data.Labels.length;++i){label=data.Labels[i];p=document.createElement('p');span=document.createElement('span');span.innerHTML="Cor: &nbsp;";span.style.background="#"+label.Color;span.style.color="#"+label.Color;p.appendChild(span);var str=label.Label;if(label.Label=="Outros"){str+=" (Inclui os restantes valores da dimensão seleccionada)";}
if(label.Unit){str+=" - "+label.Value+" ("+label.Unit+")";}
p.appendChild(document.createTextNode(str));if(label.Label!="Outros"){labelsHolder.appendChild(p);}else{others=p;}}
if(others){labelsHolder.appendChild(others);}}
var clearDiv=document.createElement('div');clearDiv.className='smapi_clear';holder.appendChild(clearDiv);return holder;},createAxisSelect:function(axisLabelMessage){var axisDimensionHolder=document.createElement('div'),select=document.createElement('select'),dimension=false,option=false;for(var i=0,len=this.dimensions.length;i<len;++i){dimension=this.dimensions[i];if(dimension.DimensionType=='Geo'){continue;}
option=document.createElement('option');option.appendChild(document.createTextNode(dimension.DimensionName));option.objectRepresentation={type:dimension.DimensionType,order:dimension.Order,ids:dimension.Values};select.appendChild(option);}
this.listeners.axisSelectListener=OpenLayers.Function.bind(this.changedAxisDimension,this);OpenLayers.Event.observe(select,'change',this.listeners.axisSelectListener);var axisLabel=document.createTextNode(axisLabelMessage);axisDimensionHolder.appendChild(axisLabel);axisDimensionHolder.appendChild(document.createElement('br'));axisDimensionHolder.appendChild(select);this.axisSelect=select;this.axisLabel=axisLabel;this.axisDimensionHolder=axisDimensionHolder;},removeAxisSelectListeners:function(){OpenLayers.Event.stopObserving(this.axisSelect,'change',this.listeners.axisSelectListener);delete this.listeners.axisSelectListener;if(this.axisDimensionHolder.parentNode){this.axisDimensionHolder.parentNode.removeChild(this.axisDimensionHolder);}
this.axisSelect=null;this.axisLabel=null;this.axisDimensionHolder=null;},changeAxisLabel:function(axisLabelMessage){if(this.axisLabel){var newNode=document.createTextNode(axisLabelMessage);this.axisDimensionHolder.replaceChild(newNode,this.axisLabel);this.axisLabel=newNode;}},hasOnlyTemporalDimension:function(axisLabelMessage){for(var i=0,len=this.dimensions.length;i<len;++i){var dimension=this.dimensions[i];if(dimension.DimensionType!='Geo'&&dimension.DimensionType!='Year'){return false;}}
return true;},getTemporalSelectOption:function(){if(this.axisSelect){var options=this.axisSelect.options;for(var i=0;i<options.length;++i){var option=options[i];if(option.objectRepresentation.type=='Year'){return option;}}}
return null;},tabSelected:function(tabId,tab){if(!this.showTemporalDimensionOnPieCharts)
{var selectedAxis=this.getSelectedAxisDimension();var temporalOption=this.getTemporalSelectOption();if(tab==SAPO.Maps.Indicator.dataTypes.pie){if(temporalOption){this.temporalOption=temporalOption;this.axisSelect.removeChild(temporalOption);}}else{if(this.temporalOption){this.axisSelect.appendChild(this.temporalOption);this.temporalOption=null;}}}
var drawn=this.tabContents[tab];if(tab!=SAPO.Maps.Indicator.dataTypes.table&&this.dimensions){if(!this.axisSelect){this.createAxisSelect(this.labelName[tab]);}else{this.changeAxisLabel(this.labelName[tab]);}
if(this.axisDimensionHolder.parentNode){this.axisDimensionHolder.parentNode.removeChild(this.axisDimensionHolder);}
if(drawn){this.tabs.getTabContent(tabId).insertBefore(this.axisDimensionHolder,this.tabContents[tab]);}else{this.tabs.getTabContent(tabId).appendChild(this.axisDimensionHolder);}}
if(drawn){var div=this.tabs.getTabContent(tabId);var tabContentSize=OpenLayers.Util.getRenderedDimensions(div.innerHTML);}
if(this.callbacks&&this.callbacks.onTabChanged){this.callbacks.onTabChanged.apply(this.callbacks.scope,[tab,drawn]);}
this.removeErrorMessge(this.currentTab);this.removeWaitIcon(this.currentTab);this.currentTab=tab;},changedTableDimension:function(){if(!this.callbacks||!this.callbacks.onDimensionTableChange){return;}
var selectedDimensions=[],dimension=false,select=false,selectedOpt=false;for(var selectKey in this.tableSelects){select=this.tableSelects[selectKey];selectedOpt=select.options[select.selectedIndex];selectedDimensions.push({type:select.dimensionType,id:select.dimensionType=='Geo'?selectedOpt.id+","+selectedOpt.territoryView:selectedOpt.id,order:select.order});}
this.callbacks.onDimensionTableChange.apply(this.callbacks.scope,[selectedDimensions]);},changedAxisDimension:function(){if(!this.callbacks||this.silentDimensionChangedEvt){return;}
this.clearTab(SAPO.Maps.Indicator.dataTypes.pie);this.clearTab(SAPO.Maps.Indicator.dataTypes.bars);if(this.callbacks&&this.callbacks.onAxisDimensionChange){var idx=this.axisSelect.selectedIndex;var axis=this.axisSelect.options[idx].objectRepresentation;this.callbacks.onAxisDimensionChange.apply(this.callbacks.scope,[this.currentTab,axis]);}},CLASS_NAME:'SAPO.Maps.PopupRenderer.Statistics'});SAPO.Maps.StatisticsSelector=OpenLayers.Class({map:null,panel:null,windowManager:null,toggleElement:null,callbacks:null,elements:null,modalVisible:false,selectedTab:null,listeners:null,statisticsSearch:null,indicatorToChange:null,searchObj:null,initialize:function(toggleElement,map,panel,windowManager,callbacks){this.selectedTab='themes';this.listeners={resize:{listener:OpenLayers.Function.bind(this.positionModalBox,this),element:window,evtType:'resize'},unload:{listener:OpenLayers.Function.bind(this.destroy,this),element:window,evtType:'unload'}};this.map=map;this.windowManager=windowManager;this.callbacks=callbacks;this.statisticsSearch=new SAPO.Maps.StatisticsSearch();this.statisticsExplorer=new SAPO.Maps.Statistics(map,panel,windowManager);this.statisticsExplorer.events.register('changeIndicator',this,this.changeIndicator);this.statisticsExplorer.events.register('selectIndicator',this,this.toggleSelector);this.searchObj={recordsPerPage:7,numberOfPagesShown:5};if(panel){this.panel=OpenLayers.Util.getElement(panel);}
if(toggleElement){this.toggleElement=OpenLayers.Util.getElement(toggleElement);this.listeners.toggleElement={listener:OpenLayers.Function.bind(this.toggleSelector,this),element:this.toggleElement,evtType:'click'};}
this.drawModalBox();this.bindListeners();this.requestThemes();},destroy:function(){this.unbindListeners();},toggleSelector:function(evt){if(this.modalVisible){this.elements.holder.style.display='none';this.indicatorToChange=null;}
else{this.elements.holder.style.display='block';this.positionModalBox();}
this.modalVisible=!this.modalVisible;return SAPO.Maps.Utils.preventDefault(evt);},selectTab:function(tab,evt){if(!this.elements.tabs[tab]){return;}
if(this.selectedTab){this.elements.tabs[this.selectedTab].tab.className='';this.elements.tabs[this.selectedTab].content.style.display='none';}
this.elements.tabs[tab].tab.className='current';this.elements.tabs[tab].content.style.display='block';this.selectedTab=tab;if(tab=='search'){this.elements.search_textbox.focus();}
this.positionModalBox();return SAPO.Maps.Utils.preventDefault(evt);},positionModalBox:function(){var windowWidth=document.documentElement.clientWidth;var windowHeight=document.documentElement.clientHeight;this.elements.modal.style.left=((windowWidth/2)-(this.elements.modal.clientWidth/2))+"px";this.elements.modal.style.top=((windowHeight/2)-(this.elements.modal.clientHeight/2))+"px";},requestThemes:function(){this.statisticsSearch.getStatisticsThemes(SAPO.Maps.Statistics.Config.currentProvider.endpoint,{onComplete:function(themes){var option=false;for(var i=0,len=themes.length;i<len;++i){option=document.createElement("option");option.value=themes[i].Code;option.innerHTML=themes[i].Description;this.elements.themes_select.appendChild(option);}},onTimeout:this.getThemes,scope:this});},requestSubThemes:function(){this.removeSelectOptions(true);var selectedIdx=this.elements.themes_select.selectedIndex;var themeCode=this.elements.themes_select.options[selectedIdx].value;this.statisticsSearch.getSubThemes(SAPO.Maps.Statistics.Config.currentProvider.endpoint,themeCode,{onComplete:function(subThemes){for(var i=0,len=subThemes.length;i<len;++i){option=document.createElement("option");option.value=subThemes[i].Code;option.innerHTML=subThemes[i].Description;this.elements.subthemes_select.appendChild(option);}
this.elements.subthemes_select.disabled=false;},onTimeout:this.requestSubThemes,scope:this,optOnComplete:themeCode});},requestIndicatorsByTheme:function(){this.removeSelectOptions(false);var selectedIdx=this.elements.subthemes_select.selectedIndex;var themeCode=this.elements.subthemes_select.options[selectedIdx].value;this.statisticsSearch.getStatisticsByTheme(SAPO.Maps.Statistics.Config.currentProvider.endpoint,themeCode,{onComplete:function(indicators){for(var i=0,len=indicators.length;i<len;++i){option=document.createElement("option");option.statObj=indicators[i];option.innerHTML=indicators[i].StatisticName;this.elements.indicator_select.appendChild(option);}
this.elements.indicator_select.disabled=false;},onTimeout:this.requestIndicatorsByTheme,scope:this,optOnComplete:themeCode});},selectIndicatorFromThemes:function(){var selectedIndex=this.elements.indicator_select.selectedIndex;if(selectedIndex===0){return;}
var code=this.elements.indicator_select.options[selectedIndex].statObj.StatisticId;this.showIndicator(code);},searchIndicators:function(evt){this.searchObj.term=encodeURIComponent(this.elements.search_textbox.value);this.searchObj.pageNumber=1;this.getIndicatorsBySearch();return SAPO.Maps.Utils.preventDefault(evt);},changeIndicator:function(evt){this.indicatorToChange=evt.indicator;this.toggleSelector();},getIndicatorsBySearch:function(){this.clearSearchResults();SAPO.Maps.Utils.displayWaitIcon(this.elements.search_results);this.statisticsSearch.getStatisticsBySearch(SAPO.Maps.Statistics.Config.currentProvider.endpoint,this.searchObj.term,this.searchObj.pageNumber,this.searchObj.recordsPerPage,{onComplete:function(results){SAPO.Maps.Utils.removeWaitIcon(this.elements.search_results);if(results.TotalResults===0){var h2=document.createElement('h2');var errorMsg="Não foram encontrados resultados na pesquisa por: "+decodeURIComponent(this.searchObj.term);h2.appendChild(document.createTextNode(errorMsg));this.elements.search_results.appendChild(h2);return;}
var _this=this;var h1_header=document.createElement("h1");var ol_list=document.createElement("ol");var nrResults=results.TotalResults>1?results.TotalResults+" Resultados encontrados":results.TotalResults+" Resultado encontrado";h1_header.appendChild(document.createTextNode(nrResults));var hits=results.Hits;var li_item,a_indicatorName;for(var i=0;i<hits.length;++i){li_item=document.createElement("li");a_indicatorName=document.createElement("a");a_indicatorName.href="#";a_indicatorName.innerHTML=hits[i].StatisticName;a_indicatorName.stat=hits[i];a_indicatorName.onclick=function(){_this.showIndicator(this.stat.StatisticId);return false;};li_item.appendChild(a_indicatorName);ol_list.appendChild(li_item);}
this.elements.search_results.appendChild(h1_header);this.elements.search_results.appendChild(ol_list);this.drawPages(results.TotalResults);this.positionModalBox();},onTimeout:this.timeout,scope:this});},drawPages:function(nrResults){if(nrResults<=this.searchObj.recordsPerPage){return;}
var div_pagination=document.createElement("div");div_pagination.className="smapi_global_pagination";var numPages=Math.ceil(nrResults/this.searchObj.recordsPerPage);var startPage=this.searchObj.pageNumber-Math.floor(this.searchObj.numberOfPagesShown/2);var endPage=this.searchObj.pageNumber+Math.floor(this.searchObj.numberOfPagesShown/2);if(endPage>numPages){endPage=numPages;}
if(startPage<1){startPage=1;}
if((endPage-startPage+1)<this.searchObj.numberOfPagesShown&&numPages>=this.searchObj.numberOfPagesShown){if(startPage<=Math.floor(this.searchObj.numberOfPagesShown/2)){endPage+=this.searchObj.numberOfPagesShown-endPage;}else if(endPage>=numPages-Math.floor(this.searchObj.numberOfPagesShown/2)){startPage-=this.searchObj.numberOfPagesShown-(endPage-startPage+1);}}
var pageNumber=false;if(this.searchObj.pageNumber!==1){var span_prev=document.createElement("span");span_prev.className="prev";span_prev.onclick=function(){this.goToPage(this.searchObj.pageNumber-1);}.bindObj(this);div_pagination.appendChild(span_prev);}
var pages=document.createElement('span');var page=false;var _this=this;for(var i=startPage;i<=endPage;++i){page=document.createElement('a');page.innerHTML=i;page.page=i;page.onclick=function(){_this.goToPage(this.page);return false;};if(i===this.searchObj.pageNumber){page.className='current';}
pages.appendChild(page);}
div_pagination.appendChild(pages);if(this.searchObj.pageNumber!==numPages){var span_next=document.createElement("span");span_next.className="next";span_next.onclick=function(){this.goToPage(this.searchObj.pageNumber+1);}.bindObj(this);div_pagination.appendChild(span_next);}
this.elements.search_results.appendChild(div_pagination);},goToPage:function(page){this.searchObj.pageNumber=page;this.getIndicatorsBySearch();},clearSearchResults:function(){this.elements.search_results.innerHTML="";},showIndicator:function(code){if(this.indicatorToChange){this.indicatorToChange.changeIndicator(code,{providerUrl:SAPO.Maps.Statistics.Config.currentProvider.endpoint});}else{this.statisticsExplorer.addIndicator(SAPO.Maps.Statistics.Config.currentProvider.endpoint,code);}
this.toggleSelector();},removeSelectOptions:function(removeSubThemes){var options=false;if(removeSubThemes){SAPO.Maps.Utils.removeChildNodes(this.elements.subthemes_select);option=document.createElement('option');option.value='select';option.innerHTML='Seleccione o sub-tema dos indicadores a consultar';this.elements.subthemes_select.appendChild(option);this.elements.subthemes_select.disabled=true;}
SAPO.Maps.Utils.removeChildNodes(this.elements.indicator_select);option=document.createElement('option');option.value='select';option.innerHTML='Seleccione o indicador a consultar';this.elements.indicator_select.appendChild(option);this.elements.indicator_select.disabled=true;},drawModalBox:function(){var backgroundId=OpenLayers.Util.createUniqueID(this.CLASS_NAME);var contentId=OpenLayers.Util.createUniqueID(this.CLASS_NAME);var closeBtnId=OpenLayers.Util.createUniqueID(this.CLASS_NAME);var modal_tab_themes_id=OpenLayers.Util.createUniqueID(this.CLASS_NAME);var modal_tab_search_id=OpenLayers.Util.createUniqueID(this.CLASS_NAME);var modal_content_themes_id=OpenLayers.Util.createUniqueID(this.CLASS_NAME);var theme_list_id=OpenLayers.Util.createUniqueID(this.CLASS_NAME);var sub_theme_list_id=OpenLayers.Util.createUniqueID(this.CLASS_NAME);var indicator_list_id=OpenLayers.Util.createUniqueID(this.CLASS_NAME);var select_theme_id=OpenLayers.Util.createUniqueID(this.CLASS_NAME);var modal_content_search_id=OpenLayers.Util.createUniqueID(this.CLASS_NAME);var model_search_form_id=OpenLayers.Util.createUniqueID(this.CLASS_NAME);var stats_textBox_id=OpenLayers.Util.createUniqueID(this.CLASS_NAME);var stats_search_results_id=OpenLayers.Util.createUniqueID(this.CLASS_NAME);var html="<div id='"+backgroundId+"' class='modal_background'></div>"+"<div id='"+contentId+"' class='modal_content'>"+"<div class='modal_tabs'>"+"<div id='"+closeBtnId+"' class='closebtn'></div>"+"<a id='"+modal_tab_themes_id+"' href='#'>Temas</a>"+"<a id='"+modal_tab_search_id+"' href='#'>Pesquisa</a>"+"</div>"+"<div class='modal_content_text modal_content_themes hide' id='"+modal_content_themes_id+"'>"+"Seleccione o indicador desejado consoante o tema escolhido"+"<p class='modal_divider'>"+"&nbsp;"+"</p>"+"<form class='themes' method='get' accept-charset='utf-8'>"+"<select id='"+theme_list_id+"'>"+"<option value='select'>Seleccione o tema de indicadores a consultar</option>"+"</select>"+"<select id='"+sub_theme_list_id+"' disabled='true'>"+"<option value='select'>Seleccione o sub-tema dos indicadores a consultar</option>"+"</select>"+"<select id='"+indicator_list_id+"' disabled='true'>"+"<option value='select'>Seleccione o indicador a consultar</option>"+"</select>"+"</form>"+"<input id='"+select_theme_id+"' type='submit' value='Seleccionar'/>"+"</div>"+"<div class='modal_content_text hide' id='"+modal_content_search_id+"'>"+"Pesquise por termos relacionados com o conteúdo que procura"+"<p class='modal_divider'>"+"&nbsp;"+"</p>"+"<form id='"+model_search_form_id+"' action='#' accept-charset='utf-8' method='get'>"+"<div class='stats_search'>"+"<input id='"+stats_textBox_id+"' type='text' name='stats_search' value='' />"+"</div>"+"<span class='input_end'>&nbsp;</span>"+"<input type='submit' name='submit' value=' ' class='submit' />"+"</form>"+"<p class='modal_divider'>&nbsp;</p>"+"<div id='"+stats_search_results_id+"' class='stats_search_results'></div>"+"</div>"+"</div>";var div=document.createElement('div');div.className="hide";div.innerHTML=html;document.body.appendChild(div);this.elements={holder:div,modalBackground:document.getElementById(backgroundId),modal:document.getElementById(contentId),closeBtn:document.getElementById(closeBtnId),tabs:{themes:{tab:document.getElementById(modal_tab_themes_id),content:document.getElementById(modal_content_themes_id)},search:{tab:document.getElementById(modal_tab_search_id),content:document.getElementById(modal_content_search_id)}},themes_select:document.getElementById(theme_list_id),subthemes_select:document.getElementById(sub_theme_list_id),indicator_select:document.getElementById(indicator_list_id),select_indicatorBt:document.getElementById(select_theme_id),search_form:document.getElementById(model_search_form_id),search_textbox:document.getElementById(stats_textBox_id),search_results:document.getElementById(stats_search_results_id)};var listeners={closeModal:{listener:OpenLayers.Function.bind(this.toggleSelector,this),element:[this.elements.modalBackground,this.elements.closeBtn],evtType:'click'},themesTab:{listener:OpenLayers.Function.bind(this.selectTab,this,'themes'),element:this.elements.tabs.themes.tab,evtType:'click'},searchTab:{listener:OpenLayers.Function.bind(this.selectTab,this,'search'),element:this.elements.tabs.search.tab,evtType:'click'},themesSelected:{listener:OpenLayers.Function.bind(this.requestSubThemes,this),element:this.elements.themes_select,evtType:'change'},subThemesSelected:{listener:OpenLayers.Function.bind(this.requestIndicatorsByTheme,this),element:this.elements.subthemes_select,evtType:'change'},indicatorThemeBtSelected:{listener:OpenLayers.Function.bind(this.selectIndicatorFromThemes,this),element:this.elements.select_indicatorBt,evtType:'click'},search:{listener:OpenLayers.Function.bind(this.searchIndicators,this),element:this.elements.search_form,evtType:'submit'}};OpenLayers.Util.extend(this.listeners,listeners);this.selectTab(this.selectedTab);},bindListeners:function(){for(var l in this.listeners){var listener=this.listeners[l];if(listener.element instanceof Array){for(var i=0;i<listener.element.length;++i){var element=listener.element[i];OpenLayers.Event.observe(element,listener.evtType,listener.listener);}}else{OpenLayers.Event.observe(listener.element,listener.evtType,listener.listener);}}},unbindListeners:function(){for(var l in this.listeners){var listener=this.listeners[l];if(listener.element instanceof Array){for(var i=0;i<listener.element.length;++i){var element=listener.element[i];OpenLayers.Event.stopObserving(element,listener.evtType,listener.listener);}}else{OpenLayers.Event.stopObserving(listener.element,listener.evtType,listener.listener);}
delete this.listeners[l];}},CLASS_NAME:'SAPO.Maps.Statistics.StatisticsSelector'});
if(!SAPO.Utility||typeof(SAPO.Utility)=='undefined'){SAPO.namespace('Utility');}
SAPO.Utility.Url={_keyStr:'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',getUrl:function()
{var url=false;url=location.href;return url;},getQueryString:function(string)
{if(string&&typeof(string)!='undefined'){var url=string;}else{var url=this.getUrl();}
var aParams={};if(url.match(/\?(.+)/i)){var queryStr=url.replace(/^(.*)\?([^\#]+)(\#(.*))?/g,"$2");if(queryStr.length>0){var aQueryStr=queryStr.split(/[;&]/);for(var i=0;i<aQueryStr.length;i++){var pairVar=aQueryStr[i].split('=');aParams[decodeURIComponent(pairVar[0])]=(typeof(pairVar[1])!='undefined'&&pairVar[1])?decodeURIComponent(pairVar[1]):false;}}}
return aParams;},getAnchor:function(string)
{if(string&&typeof(string)!='undefined'){var url=string;}else{var url=this.getUrl();}
var anchor=false;if(url.match(/#(.+)/)){anchor=url.replace(/([^#]+)#(.*)/,"$2");}
return anchor;},getAnchorString:function(string)
{if(string&&typeof(string)!='undefined'){var url=string;}else{var url=this.getUrl();}
var aParams={};if(url.match(/#(.+)/i)){var anchorStr=url.replace(/^([^#]+)#(.*)?/g,"$2");if(anchorStr.length>0){var aAnchorStr=anchorStr.split(/[;&]/);for(var i=0;i<aAnchorStr.length;i++){var pairVar=aAnchorStr[i].split('=');aParams[decodeURIComponent(pairVar[0])]=(typeof(pairVar[1])!='undefined'&&pairVar[1])?decodeURIComponent(pairVar[1]):false;}}}
return aParams;},parseUrl:function(url)
{var aURL={};if(url&&typeof(url)!='undefined'&&typeof(url)=='string'){if(url.match(/^([^:]+):\/\//i)){var re=/^([^:]+):\/\/([^\/]*)\/?([^\?#]*)\??([^#]*)#?(.*)/i;if(url.match(re)){aURL['scheme']=url.replace(re,"$1");aURL['host']=url.replace(re,"$2");aURL['path']='/'+url.replace(re,"$3");aURL['query']=url.replace(re,"$4")||false;aURL['fragment']=url.replace(re,"$5")||false;}}else{var re1=new RegExp("^([^\\?]+)\\?([^#]+)#(.*)","i");var re2=new RegExp("^([^\\?]+)\\?([^#]+)#?","i");var re3=new RegExp("^([^\\?]+)\\??","i");if(url.match(re1)){aURL['scheme']=false;aURL['host']=false;aURL['path']=url.replace(re1,"$1");aURL['query']=url.replace(re1,"$2");aURL['fragment']=url.replace(re1,"$3");}else if(url.match(re2)){aURL['scheme']=false;aURL['host']=false;aURL['path']=url.replace(re2,"$1");aURL['query']=url.replace(re2,"$2");aURL['fragment']=false;}else if(url.match(re3)){aURL['scheme']=false;aURL['host']=false;aURL['path']=url.replace(re3,"$1");aURL['query']=false;aURL['fragment']=false;}}
if(aURL['host']){var regPort=new RegExp("^(.*)\\:(\\d+)$","i");if(aURL['host'].match(regPort)){var tmpHost1=aURL['host'];aURL['host']=tmpHost1.replace(regPort,"$1");aURL['port']=tmpHost1.replace(regPort,"$2");}else{aURL['port']=false;}
if(aURL['host'].match(/@/i)){var tmpHost2=aURL['host'];aURL['host']=tmpHost2.split('@')[1];var tmpUserPass=tmpHost2.split('@')[0];if(tmpUserPass.match(/\:/)){aURL['user']=tmpUserPass.split(':')[0];aURL['pass']=tmpUserPass.split(':')[1];}else{aURL['user']=tmpUserPass;aURL['pass']=false;}}}}
return aURL;},currentScriptElement:function(match)
{var aScripts=document.getElementsByTagName('script');if(typeof(match)=='undefined'){if(aScripts.length>0){return aScripts[(aScripts.length-1)];}else{return false;}}else{var curScript=false;var re=new RegExp(""+match+"","i");for(var i=0,total=aScripts.length;i<total;i++){curScript=aScripts[i];if(re.test(curScript.src)){return curScript;}}
return false;}},base64Encode:function(string)
{if(!SAPO.Utility.String||typeof(SAPO.Utility.String)=='undefined'){throw"SAPO.Utility.Url.base64Encode depends of SAPO.Utility.String, which has not been referred.";return false;}
var output="";var chr1,chr2,chr3,enc1,enc2,enc3,enc4;var i=0;var input=SAPO.Utility.String.utf8Encode(string);while(i<input.length){chr1=input.charCodeAt(i++);chr2=input.charCodeAt(i++);chr3=input.charCodeAt(i++);enc1=chr1>>2;enc2=((chr1&3)<<4)|(chr2>>4);enc3=((chr2&15)<<2)|(chr3>>6);enc4=chr3&63;if(isNaN(chr2)){enc3=enc4=64;}else if(isNaN(chr3)){enc4=64;}
output=output+
this._keyStr.charAt(enc1)+this._keyStr.charAt(enc2)+
this._keyStr.charAt(enc3)+this._keyStr.charAt(enc4);}
return output;},base64Decode:function(string)
{if(!SAPO.Utility.String||typeof(SAPO.Utility.String)=='undefined'){throw"SAPO.Utility.Url.base64Decode depends of SAPO.Utility.String, which has not been referred.";return false;}
var output="";var chr1,chr2,chr3;var enc1,enc2,enc3,enc4;var i=0;var input=string.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(i<input.length){enc1=this._keyStr.indexOf(input.charAt(i++));enc2=this._keyStr.indexOf(input.charAt(i++));enc3=this._keyStr.indexOf(input.charAt(i++));enc4=this._keyStr.indexOf(input.charAt(i++));chr1=(enc1<<2)|(enc2>>4);chr2=((enc2&15)<<4)|(enc3>>2);chr3=((enc3&3)<<6)|enc4;output=output+String.fromCharCode(chr1);if(enc3!=64){output=output+String.fromCharCode(chr2);}
if(enc4!=64){output=output+String.fromCharCode(chr3);}}
output=SAPO.Utility.String.utf8Decode(output);return output;}};
if(!SAPO.Utility&&typeof(SAPO.Utility)=='undefined'){SAPO.namespace('Utility');}
SAPO.Utility.Cookie={fileWebView:false,webViewCookie:false,get:function(name)
{if(this.fileWebView){var stopTimer=false;if(typeof(SAPO.Communication)!='undefined'&&typeof(SAPO.Communication.Ajax)!='undefined'){new SAPO.Communication.Ajax('cookie:get:SAPO.Utility.webviewCookie',{asynchronous:false,onSuccess:function(){}});}
setTimeout(function(){stopTimer=true;},1000);while(SAPO.Utility.webviewCookie===false||stopTimer===false){}
var cookie=SAPO.Utility.webviewCookie;}else{var cookie=document.cookie||false;}
var _Cookie={};if(cookie){cookie=cookie.replace(new RegExp("; ","g"),';');var aCookie=cookie.split(';');var aItem=[];if(aCookie.length>0){for(var i=0;i<aCookie.length;i++){aItem=aCookie[i].split('=');if(aItem.length==2){_Cookie[aItem[0]]=decodeURIComponent(aItem[1]);}
aItem=[];}}}
return _Cookie;},set:function(name,value,expires,path,domain,secure)
{if(!name||value===false||typeof(name)=='undefined'||typeof(value)=='undefined'){return false;}else{if(this.fileWebView){if(typeof(SAPO.Communication)!='undefined'&&typeof(SAPO.Communication.Ajax)!='undefined'){if(!expires){expires=3600;}
new SAPO.Communication.Ajax('cookie:set:'+name+':'+value+':'+expires+'',{asynchronous:false,onSuccess:function(){}});return true;}}
var sName=name+'='+encodeURIComponent(value);}
var sExpires=false;var sPath=false;var sDomain=false;var sSecure=false;if(expires&&typeof(expires)!='undefined'&&!isNaN(expires)){var oDate=new Date();var sDate=(parseInt(Number(oDate.valueOf()))+(Number(parseInt(expires))*1000));var nDate=new Date(sDate);var expiresString=nDate.toGMTString();var re=new RegExp("([^\\s]+)(\\s\\d\\d)\\s(\\w\\w\\w)\\s(.*)");expiresString=expiresString.replace(re,"$1$2-$3-$4");sExpires='expires='+expiresString;}else{if(typeof(expires)!='undefined'&&!isNaN(expires)&&Number(parseInt(expires))===0){sExpires='';}
else
{sExpires='expires=Thu, 01-Jan-2037 00:00:01 GMT';}}
if(path&&typeof(path)!='undefined'){sPath='path='+path;}else{sPath='path=/';}
if(domain&&typeof(domain)!='undefined'){sDomain='domain='+domain;}else{var portClean=new RegExp(":(.*)");sDomain='domain='+window.location.host;sDomain=sDomain.replace(portClean,"");}
if(secure&&typeof(secure)!='undefined'){sSecure=secure;}else{sSecure=false;}
document.cookie=sName+'; '+sExpires+'; '+sPath+'; '+sDomain+'; '+sSecure;},remove:function(cookieName,path,domain)
{var sPath=false;var sDomain=false;var expiresDate=-999999999;if(path&&typeof(path)!='undefined'){sPath=path;}else{sPath='/';}
if(domain&&typeof(domain)!='undefined'){sDomain=domain;}else{sDomain=window.location.host;}
this.set(cookieName,'deleted',expiresDate,sPath,sDomain);},debug:function()
{}};
var _NB_MAX_CONTENU_=1;var _TAILLE_MAX_CONTENU_=100;var _TAILLE_MAX_CHAINE_=50;var _TAILLE_MAX_ALPHANUM_=30;var WEBO_ID_GROUPE=312222;var COOKIE_SEGMENTATION='wbo_segment_';function wreport_counter(section,subsection,site,frame,channel,section_grp,subsection_grp){this.site=site;this.section;this.subsection;this.channel='';this.content='';this.nb_content=0;this.url='';this.frame=frame;this.segmentation=new Array('','','','','');this.profiles='';this.profiling_cookie_mode=1;this.cookie_segmentation=COOKIE_SEGMENTATION;this.domaine_segmentation='';this.counter=new Image(1,1);this.profiling_cookie_mode=profiling_cookie_mode;this.generate_url=generate_url;this.add_content=add_content;this.add_channel=add_channel;this.add_group=add_group;this.add_profile=add_profile;this.add_profiles=add_profiles;this.delete_profiles=delete_profiles;this.get_profiles=get_profiles;this.count=count;this.section=traite_chaine(section,_TAILLE_MAX_ALPHANUM_);this.subsection=traite_chaine(subsection,_TAILLE_MAX_ALPHANUM_);if(channel!=null){this.add_channel(channel);}
if(section_grp!=null&&subsection_grp!=null){this.add_group(section_grp,subsection_grp);}
this.cookie_segmentation+=site;}
function generate_url(){var _date_=new Date();this.date=parseInt(_date_.getTime()/1000-60*_date_.getTimezoneOffset());this.ref=''+escape(document.referrer);this.ta='0x0';this.co=0;this.nav=navigator.appName;this.get_profiles();if(parseInt(navigator.appVersion)>=4){this.ta=screen.width+"x"+screen.height;this.co=(this.nav!="Netscape")?screen.colorDepth:screen.pixelDepth;}
if((this.frame!=null)&&(this.nav!="Netscape")){var reftmp='parent.document.referrer';if((this.frame<5)&&(this.frame>0)){for(_k=this.frame;_k>1;_k--)reftmp='parent.'+reftmp;}
var mon_ref=eval(reftmp);if(document.referrer==parent.location||document.referrer=='')this.ref=''+escape(mon_ref)}
if(location.protocol=='https:'){this.url="https://netscope.secure.marktest.pt";}else{this.url="http://netscope.data.marktest.pt";}
this.url+="/fcgi-bin/comptage_wreport.fcgi?WRP_ID="+this.site;if(this.profiles!=null)this.url+="&WRP_PFL="+this.profiles;var is_mac=(wf_uaO('mac')!=-1);var is_opera=(wf_uaO('opera')!=-1);if((!is_mac)&&(!is_opera)){var msieind=navigator.userAgent.indexOf('MSIE');if(msieind>0){if(parseInt(navigator.userAgent.charAt(msieind+5))>=5){document.body.addBehavior("#default#clientCaps");this.cnx=(document.body.connectionType=='modem')?'A':'B';document.body.addBehavior("#default#homePage");this.home=(document.body.isHomePage(location.href))?'A':'B';this.url+="&CONN="+this.cnx+"&ISHOME="+this.home;}}}
this.url+="&WRP_SECTION="+this.section+"&WRP_SUBSECTION="+this.subsection;if(this.site_grp!=null&&this.section_grp!=null&&this.subsection_grp!=null){this.url+="&WRP_ID_GRP="+this.site_grp+"&WRP_SECTION_GRP="+this.section_grp+"&WRP_SUBSECTION_GRP="+this.subsection_grp;}
if(this.content!=null)this.url+="&WRP_CONTENT="+this.content;if(this.channel!=null)this.url+="&WRP_CHANNEL="+this.channel;this.url+="&ver=2&da2="+this.date+"&ta="+this.ta+"&co="+this.co+"&ref="+this.ref;}
function count(){this.generate_url();var urlToUse=this.url;var _this_counter=this.counter;setTimeout(function(){_this_counter.src=urlToUse;},0);try{if(typeof(SAPOWA_TRACKER)!='object'||SAPOWA_TRACKER==null){SAPOWA_TRACKER={};}
SAPOWA_TRACKER.swasite=this.site;SAPOWA_TRACKER.swasection=this.section;SAPOWA_TRACKER.swasubsection=this.subsection;SAPOWA_TRACKER.swasectiongrp=this.sectiongrp;SAPOWA_TRACKER.swasubsectiongrp=this.subsectiongrp;SAPOWA_TRACKER.swacontent=this.content;SAPOWA_TRACKER.swachannel=this.channel;SAPO.WebAnalytics.track(SAPOWA_TRACKER);}catch(e){}
return 1;}
function add_channel(chaine){if(chaine==null)return 0;this.channel=traite_chaine(chaine,_TAILLE_MAX_CHAINE_);return 1;}
function add_group(section,subsection){this.site_grp=WEBO_ID_GROUPE;this.section_grp=traite_chaine(section,_TAILLE_MAX_ALPHANUM_);this.subsection_grp=traite_chaine(subsection,_TAILLE_MAX_ALPHANUM_);}
function add_content(chaine){if(chaine==null)return 0;this.nb_content++;if(this.nb_content>_NB_MAX_CONTENU_)return 0;if(this.nb_content>1)this.content=this.content.concat('|');chaine=chaine.replace('|',' ');this.content=this.content.concat(traite_chaine(chaine,_TAILLE_MAX_CONTENU_));return 1;}
function profiling_cookie_mode(mode){if(mode=='on'){this.profiling_cookie_mode=1;}else{this.profiling_cookie_mode=0;}}
function add_profile(numero,valeur){numero=parseInt(numero,10);if((numero<1)||(numero>5))return-2;if(this.profiling_cookie_mode==0){numero--;this.segmentation[numero]=valeur;return 1;}
if(parseInt(navigator.appVersion,10)<=3)return-1;nb_mois=12;var verif_val_I=/^\d+$/;if(verif_val_I.test(valeur))valeur=encode_en_lettre(valeur);var verif_val_A=/^\w*$/;if(verif_val_A.test(valeur)){var mon_profil_wbo=GetCookie(this.cookie_segmentation);tab_segment=new Array('','','','','');if(mon_profil_wbo!=null){tab_segment=mon_profil_wbo.split('|');if(tab_segment.length!=5)tab_segment=('','','','','');if(tab_segment[numero-1]==valeur)return 1;}
if(this.domaine_segmentation==''){this.domaine_segmentation=window.location.host;tab_points=new Array();tab_points=window.location.host.split('.');if(tab_points.length>2)this.domaine_segmentation=this.domaine_segmentation.substring(this.domaine_segmentation.indexOf('.'),this.domaine_segmentation.length);if(tab_points.length==2)this.domaine_segmentation='.'+this.domaine_segmentation;}
var ma_chaine_profil='';for(var i=1;i<=5;i++){if(i==numero)tab_segment[i-1]=valeur;if((tab_segment[i-1]=='')||(tab_segment[i-1]==null))tab_segment[i-1]='';ma_chaine_profil+=tab_segment[i-1];if(i<5)ma_chaine_profil+='|';}
expd=new Date();expd.setTime(expd.getTime()+(nb_mois*30*24*3600*1000));SetCookie(this.cookie_segmentation,ma_chaine_profil,expd,'/',this.domaine_segmentation);return 2;}else return-3;}
function add_profiles(p1,p2,p3,p4,p5){this.add_profile(1,p1);this.add_profile(2,p2);this.add_profile(3,p3);this.add_profile(4,p4);this.add_profile(5,p5);}
function delete_profiles(){if(this.profiling_cookie_mode==0){this.segmentation=Array('','','','','');}else{expd=new Date();expd.setTime(expd.getTime()-(24*3600*1000));SetCookie(this.cookie_segmentation,'||||',expd,'/',this.domaine_segmentation);}}
function get_profiles(){this.profiles=GetCookie(this.cookie_segmentation);if(this.profiles==null){this.profiles='';var verif_val_I=/^\d+$/;for(var i=1;i<=5;i++){if(verif_val_I.test(this.segmentation[i-1]))this.segmentation[i-1]=encode_en_lettre(this.segmentation[i-1]);this.profiles+=this.segmentation[i-1];if(i<5)this.profiles+='|';}}
this.profiles=escape(this.profiles);}
function encode_en_lettre(num){num=parseInt(num,10);if(num>2500)return'';var num1=parseInt(num/52,10);var num2=num%52;num1+=65;if(num1>90)num1+=6;num2+=65;if(num2>90)num2+=6;var mon_code52=String.fromCharCode(num1)+String.fromCharCode(num2);return mon_code52;}
function traite_chaine(s,taille_max){var bag="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-.,;:_ %";var i;var returnString="";if(s==null)return"";s=""+s;s=s.substr(0,taille_max);for(i=0;i<s.length;i++){var c=s.charAt(i);if(bag.indexOf(c)!=-1)returnString+=c;}
returnString=escape(returnString);return returnString;}
function wf_uaO(c){var wf_ual=navigator.userAgent.toLowerCase();return(wf_ual.indexOf(c))}
function getCookieVal(offset){var endstr=document.cookie.indexOf(";",offset);if(endstr==-1)endstr=document.cookie.length;return unescape(document.cookie.substring(offset,endstr));}
function GetCookie(name){var arg=name+"=";var alen=arg.length;var clen=document.cookie.length;var i=0;while(i<clen){var j=i+alen;if(document.cookie.substring(i,j)==arg)return getCookieVal(j);i=document.cookie.indexOf(" ",i)+1;if(i==0)break;}
return null;}
function SetCookie(name,value,expires,path,domain,secure){document.cookie=name+"="+escape(value)+((expires)?"; expires="+expires.toGMTString():"")+((path)?"; path="+path:"")+((domain)?"; domain="+domain:"")+((secure)?"; secure":"");}
function wreport(section,subsection,site,frame,content,channel){var w_compteur=new wreport_counter(section,subsection,site,frame,channel);w_compteur.add_content(content);w_compteur.count();}
function wreport_groupe(section,subsection,site,section_grp,subsection_grp,frame,content,channel){var w_compteur=new wreport_counter(section,subsection,site,frame,channel,section_grp,subsection_grp);w_compteur.add_content(content);w_compteur.count();}
function wreport_click(url,section,subsection,site,frame,content,channel){var w_compteur=new wreport_counter(section,subsection,site,frame,channel);w_compteur.add_content(content);w_compteur.count();w_compteur.counter.onload=function(){document.location=url;}}
function wreport_click_groupe(url,section,subsection,site,section_grp,subsection_grp,frame,content,channel){var w_compteur=new wreport_counter(section,subsection,site,frame,channel,section_grp,subsection_grp);w_compteur.add_content(content);w_compteur.count();w_compteur.counter.onload=function(){document.location=url;}}
if(typeof(SAPO)==='undefined'){window.SAPO={};}
SAPO.WebAnalytics={init:function(){this.now=new Date();var options=this.extend({vtimeout:(30*60*1000),uvtimeout:(2147385600000-this.now.getTime()),gifpath:"http://wa.sl.pt/wa.gif",sgifpath:"https://ssl.sapo.pt/wa.sl.pt/wa.gif",hostname:window.location.hostname,utext:'',swasite:'',swasection:'',swasubsection:'',swasectiongrp:'',swasubsectiongrp:'',swacontent:'',swachannel:'',etype:"page-view"},arguments[0]||{});this.swakt=options.swakt;this.vtimeout=options.vtimeout;this.uvtimeout=options.uvtimeout;this.gifpath=options.gifpath;this.sgifpath=options.sgifpath;this.host=options.hostname;this.utext=options.utext;this.swasite=options.swasite;this.swasection=options.swasection;this.swasubsection=options.swasubsection;this.swasectiongrp=options.swasectiongrp;this.swasubsectiongrp=options.swasubsectiongrp;this.swacontent=options.swacontent;this.swachannel=options.swachannel;this.etype=options.etype;},extend:function(destination,source){for(var property in source){if((typeof(source[property])==='undefined')||(source[property]==null)){continue;}
destination[property]=source[property];}
return destination;},swfver:function(){var f="-",n=navigator;if(n.plugins&&n.plugins.length){for(var ii=0;ii<n.plugins.length;ii++){if(n.plugins[ii].name.indexOf('Shockwave Flash')!=-1){f=n.plugins[ii].description.split('Shockwave Flash ')[1];break;}}}else if(window.ActiveXObject){for(var jj=10;jj>=2;jj--){try{var fl=eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash."+jj+"');");if(fl){f=jj+'.0';break;}}catch(e){}}}
return f;},es:function(s,u){if(typeof(encodeURIComponent)=='function'){if(u){return encodeURI(s);}else{return encodeURIComponent(s);}}else{return escape(s);}},des:function(s){if(typeof(decodeURIComponent)=='function'){return decodeURIComponent(s);}else{return unescape(s);}},binfo:function(){var bsr="-",bsc="-",bul="-",bfl="-",bcs="-",bje=1;var n=navigator;if(self.screen){bsr=screen.width+"x"+screen.height;bsc=screen.colorDepth+"-bit";}
if(n.language){bul=n.language.toLowerCase();}else if(n.browserLanguage){bul=n.browserLanguage.toLowerCase();}
bje=n.javaEnabled()?1:0;bfl=this.swfver();if(document.characterSet){bcs=this.es(document.characterSet);}else if(document.charset){bcs=this.es(document.charset);}
return"&bcs="+bcs+"&bsr="+bsr+"&bsc="+bsc+"&bul="+bul+"&bje="+bje+"&bfl="+bfl;},sck:function(name,value,expires,domain){var path="/";var s=name+"="+this.es(value);if(expires){var td=new Date();td.setTime(td.getTime()+expires);s+=";expires="+td.toGMTString();}
s+=";path="+path;s+=";domain="+domain;document.cookie=s;},gck:function(ckn){var name=ckn+"=";var ca=document.cookie.split(';');for(var i=0;i<ca.length;i++){var c=ca[i];while(c.charAt(0)==' '){c=c.substring(1,c.length);}
if(c.indexOf(name)===0){return this.des(c.substring(name.length,c.length));}}
return null;},ckid:function(){var maxid=Number("9223372036854775807");var svalue=Math.round(Math.random()*2147483648)+''+Math.round(this.now.getTime()/1000);var bi=Number(svalue);var l=svalue.length;var ix=0;while(bi>maxid){bi=Number(String(svalue).substring(++ix,l));}
var s=String(svalue).substring(ix,l);while(s.substr(0,1)=='0'&&s.length>1){s=s.substr(1,l);}
return s;},ckdm:function(){var ad=location.hostname.split("."),al=ad.length;return"."+ad[al-2]+"."+ad[al-1];},exkw:function(href){var params=this.urlvars(href),q=['q','query','qs','qt','rdata','search_word','szukaj','terms','text','wd','encquery','k','p']
kw='';for(var i=0;i<q.length;i++){if(typeof(params[q[i]])!='undefined'){var k=this.des(params[q[i]]);if(!this.isBlank(k)){kw=k;break;}}}
return kw},urlvars:function(href){var vars=[],hash,qs=href.replace(/.*?\?/,'').replace(/#.*$/,''),hashes=qs.split('&');for(var i=0;i<hashes.length;i++){hash=hashes[i].split('=');vars.push(hash[0]);vars[hash[0]]=hash[1];}
return vars;},isBlank:function(str){return(!str||/^\s*$/.test(str));},track:function(){try{if(arguments.length>0){this.init(arguments[0]);}else{this.init();}
if(document.location.protocol=="file:"){return;}
var _swa_uv=this.gck("_swa_uv"),_swa_huv=this.gck("_swa_huv"),_swa_hv=this.gck("_swa_hv"),is_new_huv=false;if(_swa_uv==null){_swa_uv=this.ckid();this.sck("_swa_uv",_swa_uv,this.uvtimeout,this.ckdm());}
if(_swa_huv==null){_swa_huv=this.ckid();this.sck("_swa_huv",_swa_huv,this.uvtimeout,this.host);is_new_huv=true;}
_swa_uv=this.gck("_swa_uv")==null?0:this.gck("_swa_uv");_swa_huv=this.gck("_swa_huv")==null?0:this.gck("_swa_huv");if(this.isBlank(_swa_hv)){var hv_type=is_new_huv?'new':'returning',kw=this.exkw(document.referrer),k=this.isBlank(kw)?'(none)':kw,r=this.isBlank(document.referrer)?'(none)':document.referrer,hv_source_type='direct';if(!this.isBlank(kw)){hv_source_type='organic';}else if(!this.isBlank(document.referrer)){hv_source_type='referral';}
_swa_hv=this.ckid();_swa_hv+='|'+(new Date()).getTime();_swa_hv+='|'+hv_type;_swa_hv+='|'+hv_source_type;_swa_hv+='|'+k;_swa_hv+='|'+r;this.sck("_swa_hv",_swa_hv,this.vtimeout,this.host);}
_swa_hv=this.gck("_swa_hv")==null?'':this.gck("_swa_hv");var img=new Image(1,1);var qr="?s="+this.host;qr+="&etype="+this.etype;qr+="&pg="+this.es(window.location.pathname+window.location.search);qr+="&swauv="+_swa_uv;qr+="&swahuv="+_swa_huv;qr+="&swahv="+_swa_hv;qr+=this.binfo();qr+="&utext="+this.utext;qr+="&swasite="+this.swasite;qr+="&swasection="+this.swasection;qr+="&swasubsection="+this.swasubsection;qr+="&swasectiongrp="+this.swasectiongrp;qr+="&swasubsectiongrp="+this.swasubsectiongrp;qr+="&swacontent="+this.swacontent;qr+="&swachannel="+this.swachannel;qr+="&dc="+this.es(document.title);qr+="&ref="+this.es(document.referrer);if(!this.isBlank(this.swakt)){qr+="&swakt="+this.swakt;}
qr+="&r="+Math.random();qr+="&v=1.9";var _uripath=this.gifpath+qr;if(location.protocol=='https:'){_uripath=this.sgifpath+qr;}
setTimeout(function(){img.src=_uripath;},0);}catch(ex){var errorDetail='';if(typeof(ex)!='undefined'&&typeof(ex)=='object'){if(typeof(ex.name)!='undefined'){errorDetail+=ex.name+'|';}
if(typeof(ex.message)!='undefined'){errorDetail+=ex.message+'|';}}
var img=new Image(1,1);if(location.protocol=='https:'){var _uripath=this.sgifpath+'?error='+errorDetail;}else{var _uripath=this.gifpath+'?error='+errorDetail;}
setTimeout(function(){img.src=_uripath;},0);}}}
wreport_ok=1;
function WebTrends(){var that=this;this.dcsid="";this.domain="statse.webtrendslive.com";this.timezone=0;this.fpcdom="";this.enabled=true;this.i18n=false;this.fpc="WT_FPC";this.paidsearchparams="gclid";this.DCS={};this.WT={};this.DCSext={};this.images=[];this.index=0;this.exre=(function(){return(window.RegExp?new RegExp("dcs(uri)|(ref)|(aut)|(met)|(sta)|(sip)|(pro)|(byt)|(dat)|(p3p)|(cfg)|(redirect)|(cip)","i"):"");})();this.re=(function(){return(window.RegExp?(that.i18n?{"%25":/\%/g}:{"%09":/\t/g,"%20":/ /g,"%23":/\#/g,"%26":/\&/g,"%2B":/\+/g,"%3F":/\?/g,"%5C":/\\/g,"%22":/\"/g,"%7F":/\x7F/g,"%A0":/\xA0/g}):"");})();}
WebTrends.prototype.dcsGetId=function(){if(this.enabled&&(document.cookie.indexOf(this.fpc+"=")==-1)&&(document.cookie.indexOf("WTLOPTOUT=")==-1)){document.write("<scr"+"ipt type='text/javascript' src='"+"http"+(window.location.protocol.indexOf('https:')==0?'s':'')+"://"+this.domain+"/"+this.dcsid+"/wtid.js"+"'><\/scr"+"ipt>");}}
WebTrends.prototype.dcsGetCookie=function(name){var cookies=document.cookie.split("; ");var cmatch=[];var idx=0;var i=0;var namelen=name.length;var clen=cookies.length;for(i=0;i<clen;i++){var c=cookies[i];if((c.substring(0,namelen+1))==(name+"=")){cmatch[idx++]=c;}}
var cmatchCount=cmatch.length;if(cmatchCount>0){idx=0;if((cmatchCount>1)&&(name==this.fpc)){var dLatest=new Date(0);for(i=0;i<cmatchCount;i++){var lv=parseInt(this.dcsGetCrumb(cmatch[i],"lv"));var dLst=new Date(lv);if(dLst>dLatest){dLatest.setTime(dLst.getTime());idx=i;}}}
return unescape(cmatch[idx].substring(namelen+1));}
else{return null;}}
WebTrends.prototype.dcsGetCrumb=function(cval,crumb,sep){var aCookie=cval.split(sep||":");for(var i=0;i<aCookie.length;i++){var aCrumb=aCookie[i].split("=");if(crumb==aCrumb[0]){return aCrumb[1];}}
return null;}
WebTrends.prototype.dcsGetIdCrumb=function(cval,crumb){var id=cval.substring(0,cval.indexOf(":lv="));var aCrumb=id.split("=");for(var i=0;i<aCrumb.length;i++){if(crumb==aCrumb[0]){return aCrumb[1];}}
return null;}
WebTrends.prototype.dcsIsFpcSet=function(name,id,lv,ss){var c=this.dcsGetCookie(name);if(c){return((id==this.dcsGetIdCrumb(c,"id"))&&(lv==this.dcsGetCrumb(c,"lv"))&&(ss==this.dcsGetCrumb(c,"ss")))?0:3;}
return 2;}
WebTrends.prototype.dcsFPC=function(){if(document.cookie.indexOf("WTLOPTOUT=")!=-1){return;}
var WT=this.WT;var name=this.fpc;var dCur=new Date();var adj=(dCur.getTimezoneOffset()*60000)+(this.timezone*3600000);dCur.setTime(dCur.getTime()+adj);var dExp=new Date(dCur.getTime()+315360000000);var dSes=new Date(dCur.getTime());WT.co_f=WT.vtid=WT.vtvs=WT.vt_f=WT.vt_f_a=WT.vt_f_s=WT.vt_f_d=WT.vt_f_tlh=WT.vt_f_tlv="";if(document.cookie.indexOf(name+"=")==-1){if((typeof(gWtId)!="undefined")&&(gWtId!="")){WT.co_f=gWtId;}
else if((typeof(gTempWtId)!="undefined")&&(gTempWtId!="")){WT.co_f=gTempWtId;WT.vt_f="1";}
else{WT.co_f="2";var curt=dCur.getTime().toString();for(var i=2;i<=(32-curt.length);i++){WT.co_f+=Math.floor(Math.random()*16.0).toString(16);}
WT.co_f+=curt;WT.vt_f="1";}
if(typeof(gWtAccountRollup)=="undefined"){WT.vt_f_a="1";}
WT.vt_f_s=WT.vt_f_d="1";WT.vt_f_tlh=WT.vt_f_tlv="0";}
else{var c=this.dcsGetCookie(name);var id=this.dcsGetIdCrumb(c,"id");var lv=parseInt(this.dcsGetCrumb(c,"lv"));var ss=parseInt(this.dcsGetCrumb(c,"ss"));if((id==null)||(id=="null")||isNaN(lv)||isNaN(ss)){return;}
WT.co_f=id;var dLst=new Date(lv);WT.vt_f_tlh=Math.floor((dLst.getTime()-adj)/1000);dSes.setTime(ss);if((dCur.getTime()>(dLst.getTime()+1800000))||(dCur.getTime()>(dSes.getTime()+28800000))){WT.vt_f_tlv=Math.floor((dSes.getTime()-adj)/1000);dSes.setTime(dCur.getTime());WT.vt_f_s="1";}
if((dCur.getDay()!=dLst.getDay())||(dCur.getMonth()!=dLst.getMonth())||(dCur.getYear()!=dLst.getYear())){WT.vt_f_d="1";}}
WT.co_f=escape(WT.co_f);WT.vtid=(typeof(this.vtid)=="undefined")?WT.co_f:(this.vtid||"");WT.vtvs=(dSes.getTime()-adj).toString();var expiry="; expires="+dExp.toGMTString();var cur=dCur.getTime().toString();var ses=dSes.getTime().toString();document.cookie=name+"="+"id="+WT.co_f+":lv="+cur+":ss="+ses+expiry+"; path=/"+(((this.fpcdom!=""))?("; domain="+this.fpcdom):(""));var rc=this.dcsIsFpcSet(name,WT.co_f,cur,ses);if(rc!=0){WT.co_f=WT.vtvs=WT.vt_f_s=WT.vt_f_d=WT.vt_f_tlh=WT.vt_f_tlv="";if(typeof(this.vtid)=="undefined"){WT.vtid="";}
WT.vt_f=WT.vt_f_a=rc;}}
WebTrends.prototype.dcsMultiTrack=function(){var args=dcsMultiTrack.arguments?dcsMultiTrack.arguments:arguments;if(args.length%2==0){this.dcsSetProps(args);var dCurrent=new Date();this.DCS.dcsdat=dCurrent.getTime();this.dcsFPC();this.dcsTag();}}
function dcsPause(ms){var start=new Date();var now=new Date();while(now.getTime()-start.getTime()<ms)
{now=new Date();}}
WebTrends.prototype.dcsCleanUp=function(){this.DCS={};this.WT={};this.DCSext={};if(arguments.length%2==0){this.dcsSetProps(arguments);}}
WebTrends.prototype.dcsSetProps=function(args){for(var i=0;i<args.length;i+=2){if(args[i].indexOf('WT.')==0){this.WT[args[i].substring(3)]=args[i+1];}
else if(args[i].indexOf('DCS.')==0){this.DCS[args[i].substring(4)]=args[i+1];}
else if(args[i].indexOf('DCSext.')==0){this.DCSext[args[i].substring(7)]=args[i+1];}}}
WebTrends.prototype.dcsAdv=function(){this.dcsFPC();}
WebTrends.prototype.dcsVar=function(){var dCurrent=new Date();var WT=this.WT;var DCS=this.DCS;WT.tz=parseInt(dCurrent.getTimezoneOffset()/60*-1)||"0";WT.bh=dCurrent.getHours()||"0";WT.ul=navigator.appName=="Netscape"?navigator.language:navigator.userLanguage;if(typeof(screen)=="object"){WT.cd=navigator.appName=="Netscape"?screen.pixelDepth:screen.colorDepth;WT.sr=screen.width+"x"+screen.height;}
if(typeof(navigator.javaEnabled())=="boolean"){WT.jo=navigator.javaEnabled()?"Yes":"No";}
if(document.title){if(window.RegExp){var tire=new RegExp("^"+window.location.protocol+"//"+window.location.hostname+"\\s-\\s");WT.ti=document.title.replace(tire,"");}
else{WT.ti=document.title;}}
WT.js="Yes";WT.jv=(function(){var agt=navigator.userAgent.toLowerCase();var major=parseInt(navigator.appVersion);var mac=(agt.indexOf("mac")!=-1);var ff=(agt.indexOf("firefox")!=-1);var ff0=(agt.indexOf("firefox/0.")!=-1);var ff10=(agt.indexOf("firefox/1.0")!=-1);var ff15=(agt.indexOf("firefox/1.5")!=-1);var ff20=(agt.indexOf("firefox/2.0")!=-1);var ff3up=(ff&&!ff0&&!ff10&!ff15&!ff20);var nn=(!ff&&(agt.indexOf("mozilla")!=-1)&&(agt.indexOf("compatible")==-1));var nn4=(nn&&(major==4));var nn6up=(nn&&(major>=5));var ie=((agt.indexOf("msie")!=-1)&&(agt.indexOf("opera")==-1));var ie4=(ie&&(major==4)&&(agt.indexOf("msie 4")!=-1));var ie5up=(ie&&!ie4);var op=(agt.indexOf("opera")!=-1);var op5=(agt.indexOf("opera 5")!=-1||agt.indexOf("opera/5")!=-1);var op6=(agt.indexOf("opera 6")!=-1||agt.indexOf("opera/6")!=-1);var op7up=(op&&!op5&&!op6);var jv="1.1";if(ff3up){jv="1.8";}
else if(ff20){jv="1.7";}
else if(ff15){jv="1.6";}
else if(ff0||ff10||nn6up||op7up){jv="1.5";}
else if((mac&&ie5up)||op6){jv="1.4";}
else if(ie5up||nn4||op5){jv="1.3";}
else if(ie4){jv="1.2";}
return jv;})();WT.ct="unknown";if(document.body&&document.body.addBehavior){try{document.body.addBehavior("#default#clientCaps");WT.ct=document.body.connectionType||"unknown";document.body.addBehavior("#default#homePage");WT.hp=document.body.isHomePage(location.href)?"1":"0";}
catch(e){}}
if(document.all){WT.bs=document.body?document.body.offsetWidth+"x"+document.body.offsetHeight:"unknown";}
else{WT.bs=window.innerWidth+"x"+window.innerHeight;}
WT.fv=(function(){var i,flash;if(window.ActiveXObject){for(i=10;i>0;i--){try{flash=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+i);return i+".0";}
catch(e){}}}
else if(navigator.plugins&&navigator.plugins.length){for(i=0;i<navigator.plugins.length;i++){if(navigator.plugins[i].name.indexOf('Shockwave Flash')!=-1){return navigator.plugins[i].description.split(" ")[2];}}}
return"Not enabled";})();WT.slv=(function(){var slv="Not enabled";try{if(navigator.userAgent.indexOf('MSIE')!=-1){var sli=new ActiveXObject('AgControl.AgControl');if(sli){slv="Unknown";}}
else if(navigator.plugins["Silverlight Plug-In"]){slv="Unknown";}}
catch(e){}
if(slv!="Not enabled"){var i,j,v;if((typeof(Silverlight)=="object")&&(typeof(Silverlight.isInstalled)=="function")){for(i=3;i>0;i--){for(j=9;j>=0;j--){v=i+"."+j;if(Silverlight.isInstalled(v)){slv=v;break;}}
if(slv==v){break;}}}}
return slv;})();if(this.i18n){if(typeof(document.defaultCharset)=="string"){WT.le=document.defaultCharset;}
else if(typeof(document.characterSet)=="string"){WT.le=document.characterSet;}
else{WT.le="unknown";}}
WT.tv="8.6.2";WT.dl="0";WT.ssl=(window.location.protocol.indexOf('https:')==0)?"1":"0";DCS.dcsdat=dCurrent.getTime();DCS.dcssip=window.location.hostname;DCS.dcsuri=window.location.pathname;WT.es=DCS.dcssip+DCS.dcsuri;if(window.location.search){DCS.dcsqry=window.location.search;}
if(DCS.dcsqry){var dcsqry=DCS.dcsqry.toLowerCase();var params=this.paidsearchparams.length?this.paidsearchparams.toLowerCase().split(","):[];for(var i=0;i<params.length;i++){if(dcsqry.indexOf(params[i]+"=")!=-1){WT.srch="1";break;}}}
if((window.document.referrer!="")&&(window.document.referrer!="-")){if(!(navigator.appName=="Microsoft Internet Explorer"&&parseInt(navigator.appVersion)<4)){DCS.dcsref=window.document.referrer;}}}
WebTrends.prototype.dcsEscape=function(S,REL){if(REL!=""){S=S.toString();for(var R in REL){if(REL[R]instanceof RegExp){S=S.replace(REL[R],R);}}
return S;}
else{return escape(S);}}
WebTrends.prototype.dcsA=function(N,V){if(this.i18n&&(this.exre!="")&&!this.exre.test(N)){if(N=="dcsqry"){var newV="";var params=V.substring(1).split("&");for(var i=0;i<params.length;i++){var pair=params[i];var pos=pair.indexOf("=");if(pos!=-1){var key=pair.substring(0,pos);var val=pair.substring(pos+1);if(i!=0){newV+="&";}
newV+=key+"="+this.dcsEncode(val);}}
V=V.substring(0,1)+newV;}
else{V=this.dcsEncode(V);}}
return"&"+N+"="+this.dcsEscape(V,this.re);}
WebTrends.prototype.dcsEncode=function(S){return(typeof(encodeURIComponent)=="function")?encodeURIComponent(S):escape(S);}
WebTrends.prototype.dcsCreateImage=function(dcsSrc){if(document.images){this.images[this.index]=new Image();this.images[this.index].src=dcsSrc;this.index++;}
else{document.write('<IMG ALT="" BORDER="0" NAME="DCSIMG" WIDTH="1" HEIGHT="1" SRC="'+dcsSrc+'">');}}
WebTrends.prototype.dcsMeta=function(){var elems;if(document.all){elems=document.all.tags("meta");}
else if(document.documentElement){elems=document.getElementsByTagName("meta");}
if(typeof(elems)!="undefined"){var length=elems.length;for(var i=0;i<length;i++){var name=elems.item(i).name;var content=elems.item(i).content;var equiv=elems.item(i).httpEquiv;if(name.length>0){if(name.toUpperCase().indexOf("WT.")==0){this.WT[name.substring(3)]=content;}
else if(name.toUpperCase().indexOf("DCSEXT.")==0){this.DCSext[name.substring(7)]=content;}
else if(name.toUpperCase().indexOf("DCS.")==0){this.DCS[name.substring(4)]=content;}}}}}
WebTrends.prototype.dcsTag=function(){if(document.cookie.indexOf("WTLOPTOUT=")!=-1){return;}
var WT=this.WT;var DCS=this.DCS;var DCSext=this.DCSext;var i18n=this.i18n;var P="http"+(window.location.protocol.indexOf('https:')==0?'s':'')+"://"+this.domain+(this.dcsid==""?'':'/'+this.dcsid)+"/dcs.gif?";if(i18n){WT.dep="";}
for(var N in DCS){if(DCS[N]&&(typeof DCS[N]!="function")){P+=this.dcsA(N,DCS[N]);}}
var keys=["co_f","vtid","vtvs","vt_f_tlv"];for(var i=0;i<keys.length;i++){var key=keys[i];if(WT[key]){P+=this.dcsA("WT."+key,WT[key]);delete WT[key];}}
for(N in WT){if(WT[N]&&(typeof WT[N]!="function")){P+=this.dcsA("WT."+N,WT[N]);}}
for(N in DCSext){if(DCSext[N]&&(typeof DCSext[N]!="function")){if(i18n){WT.dep=(WT.dep.length==0)?N:(WT.dep+";"+N);}
P+=this.dcsA(N,DCSext[N]);}}
if(i18n&&(WT.dep.length>0)){P+=this.dcsA("WT.dep",WT.dep);}
if(P.length>2048&&navigator.userAgent.indexOf('MSIE')>=0){P=P.substring(0,2040)+"&WT.tu=1";}
this.dcsCreateImage(P);this.WT.ad="";}
WebTrends.prototype.dcsDebug=function(){var t=this;var i=t.images[0].src;var q=i.indexOf("?");var r=i.substring(0,q).split("/");var m="<b>Protocol</b><br><code>"+r[0]+"<br></code>";m+="<b>Domain</b><br><code>"+r[2]+"<br></code>";m+="<b>Path</b><br><code>/"+r[3]+"/"+r[4]+"<br></code>";m+="<b>Query Params</b><code>"+i.substring(q+1).replace(/\&/g,"<br>")+"</code>";m+="<br><b>Cookies</b><br><code>"+document.cookie.replace(/\;/g,"<br>")+"</code>";if(t.w&&!t.w.closed){t.w.close();}
t.w=window.open("","dcsDebug","width=500,height=650,scrollbars=yes,resizable=yes");t.w.document.write(m);t.w.focus();}
WebTrends.prototype.dcsCollect=function(){if(this.enabled){this.dcsVar();this.dcsMeta();this.dcsAdv();this.dcsTag();}}
WebTrends.prototype.dcsCollectPage=function(){if(this.enabled){this.DCSext._mainreq=1;this.dcsVar();this.dcsMeta();this.dcsAdv();this.dcsTag();delete this.DCSext._mainreq;}}
function dcsMultiTrack(){if(typeof(_tag)!="undefined"){return(_tag.dcsMultiTrack());}}
function dcsDebug(){if(typeof(_tag)!="undefined"){return(_tag.dcsDebug());}}
Function.prototype.wt=function(obj){var method=this;var temp=function(){return method.apply(obj,arguments);};return temp;}
var lastZoom=-1;var zoomCount=0;var centroid=null;function checkZoomAndPan(){var zoom=map.getZoom();if(zoom!==lastZoom){lastZoom=zoom;zoomCount+=1;centroid=map.getMapCenter();if(zoomCount>5){zoomCount=0;SapoMapsApp.Analytics.track("Mapa","Utilizacao","Zoom");}}
else{if(!map.getBounds().containsLonLat(centroid)){centroid=map.getMapCenter();SapoMapsApp.Analytics.track("Mapa","Utilizacao","Pan");}}}
function initializeNetscopeZoomAndPan(){centroid=map.getMapCenter();map.events.register("moveend",this,checkZoomAndPan);}
window.onunload=unload;OpenLayers.Event.observe(window,'load',initialize);var FOOTER_HEIGHT=20;var FOOTER_MARGIN=15;var TOP_MARGIN=75;var LEFT_PANEL=308;var MARGINS=12;var pubElem=false;var pubToShow=Math.round(Math.random(1));var resultsHolder=false;var resultsElem=false;var queryBox=false;var sendMail=false;var getLink=false;var map=false;var navigation=false;var maptype=false;var scale=false;var panel_minimized=false;var wmanager=false;var madeiraWindowCreated=null;var acoresWindowCreated=null;var territoryPanel=false;var Panels={Itineraries:0,Search:1,Layers:2,Customize:3,Territory:4,Statistics:5,ItinerariesAndSearch:6};var selectedPanel=2;var lastColorSelected='white';var alternativeStyleLink=null;var fullBrowser=false;function initialize(){if(SAPO.Maps.Utils.checkIE6()){document.body.className='ie6_detection';}
var mainsearch=document.getElementById('Main_search_input');mainsearch.focus();loadHTMLElements();var borders={bottom:FOOTER_HEIGHT+40,top:TOP_MARGIN+63,right:10,left:LEFT_PANEL+57};var state={outerBorders:SapoMapsApp.outerBorders,borders:borders,center:new OpenLayers.LonLat(-11.269230,40.268509),zoomLevel:6,miniMapOpen:false,mousePositionOpen:false};var queryStr=SAPO.Utility.Url.getQueryString();if(SAPO.Maps.Utils.hasProperties(queryStr)){SapoMapsApp.State.updateMapState(state,queryStr);}else{SapoMapsApp.Cookie.updateMapState(state);}
map=new SAPO.Maps.Map('mapDiv',state);var minimap=new SAPO.Maps.Control.MiniMap2({isMinimized:!state.miniMapOpen});maptype=new SAPO.Maps.Control.MapType2("pt",{territoryBt:true,territoryConfigurationPanel:"customize_territory"});maptype.events.register("panelvisibilitychanged",this,function(evt){if(evt.visible){selectPanel("territory");}
else{closeTerritoryPanel();}});navigation=new SAPO.Maps.Control.Navigation2({borders:borders});var mousePosition=new SAPO.Maps.Control.MousePosition2({isMinimized:!state.mousePositionOpen});map.addControl(minimap);map.addControl(maptype);territoryPanel=maptype.getTerritoryPanel();map.addControl(navigation);map.addControl(new OpenLayers.Control.KeyboardDefaults({borders:borders}));map.addControl(mousePosition);initContextMenu();changeBanner();resizeWindow();OpenLayers.Event.observe(window,"resize",resizeWindow);OpenLayers.Event.observe(document.getElementById('header'),"mouseup",close_boxes);OpenLayers.Event.observe(document.getElementById('left_col'),"mouseup",close_boxes);map.events.register('click',this,close_boxes);map.events.register('changebaselayer',this,function(){var floatLogo=OpenLayers.Util.getElement('float_sapologo');floatLogo.firstChild.className="logo_black";if(map.baseLayer===map.getBaseLayers().SATELLITE_MAP||map.baseLayer===map.getBaseLayers().HYBRID_MAP){floatLogo.firstChild.className="logo_white";}});map.events.register("changebaselayer",this,function(e){if(map.getBaseLayers().TERRITORY_MAP==e.layer){if(!SapoMapsApp.Stats.isStatisticActive()){openTerritoryPanel();}}else{if(!SapoMapsApp.Stats.isStatisticActive()&&maptype.getTerritoryPanel().isVisible()){closeTerritoryPanel();}}});initWindowManager();initializeMap();iniCategoriesUI();initSuggest();initSearchFilters();loadLastState();SapoMapsApp.Analytics.track("Homepage","Mapas","Home-content");map.events.register("changebaselayer",this,function(e){SapoMapsApp.Analytics.track("Mapa","Vista",e.layer.name);});hideSapoLogo();changeBanner();map.events.register("changebaselayer",this,changeBanner);initializeNetscopeZoomAndPan();setPub();SapoMapsApp.Social.initialize();};function unload(){var queryString=SAPO.Utility.Url.getQueryString();if(SAPO.Maps.Utils.hasProperties(queryString)===false){SapoMapsApp.Cookie.save();}
return false;};function initializeMap(){SapoMapsApp.initialize(map);SapoMapsApp.GeoserverLayerManager.initialize(map);SapoMapsApp.POIS.initialize(map);SapoMapsApp.POIS.activate();SapoMapsApp.Tooltip.initialize(map);SapoMapsApp.Traffic.initialize(map);SapoMapsApp.PharmsAtService.initialize(map);SapoMapsApp.VirtualVisits.initialize(map);SapoMapsApp.Panoramas.initialize(map);SapoMapsApp.Saber.initialize(map);SapoMapsApp.Weather.initialize(map);SapoMapsApp.Photos.initialize(map);SapoMapsApp.Videos.initialize(map);SapoMapsApp.News.initialize(map);SapoMapsApp.Fuel.initialize(map);SapoMapsApp.Search.initialize(map,resultsElem,resultsHolder,queryBox,pubElem);SapoMapsApp.Itineraries.initialize(map,resultsElem,resultsHolder,document.getElementById('from'),document.getElementById('to'),document.getElementById('mode'),pubElem);SapoMapsApp.WhereAmI.initialize(map,{borders:SapoMapsApp.borders});SapoMapsApp.Territory.initialize(map,wmanager);SapoMapsApp.State.initialize(map);SapoMapsApp.Cookie.initialize(map);SapoMapsApp.Stats.initialize(map,'stats_results',wmanager);SapoMapsApp.Analytics.initialize();SapoMapsApp.WebtrendsAnalytics.initialize();};function initContextMenu(){var context=[{section:-1,options:[{text:'Itinerário a partir daqui',callback:clickOpt},{text:'Itinerário para aqui',callback:clickOpt}]},{section:2,options:[{text:'Adicionar marcador',callback:clickOpt}]},{section:3,options:[{text:'O que há aqui?',callback:clickOpt}]}];var borders={bottom:FOOTER_HEIGHT,top:TOP_MARGIN,right:0,left:panel_minimized?0:LEFT_PANEL};contextMenu=new SAPO.Maps.Control.ContextMenu(context,{borders:borders});map.addControl(contextMenu);contextMenu.activate();};function getClientHeight(){return document.compatMode=='CSS1Compat'&&!window.opera?document.documentElement.clientHeight:document.body.clientHeight;};function getClientWidth(){return document.compatMode=='CSS1Compat'&&!window.opera?document.documentElement.clientWidth:document.body.clientWidth;};function hideSapoLogo(){var logo=map.getControlsByClass('SAPO.Maps.Control.PermanentLink')[0];map.removeControl(logo);};function loadLastState(){var queryStr=SAPO.Utility.Url.getQueryString();if(SAPO.Maps.Utils.hasProperties(queryStr)){SapoMapsApp.State.load(queryStr);}
else{if(SapoMapsApp.Cookie.load()===false){applyDefaults();}}};function applyDefaults(){SapoMapsApp.POIS.activateLayer('transports','airport');SapoMapsApp.POIS.activateLayer('transports','boat');SapoMapsApp.POIS.activateLayer('transports','bus');SapoMapsApp.POIS.activateLayer('transports','parking');SapoMapsApp.POIS.activateLayer('transports','train');SapoMapsApp.POIS.activateLayer('transports','subway');activateMasterLayer('transports');toogleCategory('transports','airport',true);toogleCategory('transports','boat',true);toogleCategory('transports','bus',true);toogleCategory('transports','parking',true);toogleCategory('transports','train',true);toogleCategory('transports','subway',true);SapoMapsApp.POIS.activateLayer('health','enfermagem');SapoMapsApp.POIS.activateLayer('health','centros_saude');SapoMapsApp.POIS.activateLayer('health','hospitals');activateMasterLayer('health');toogleCategory('health','enfermagem',true);toogleCategory('health','centros_saude',true);toogleCategory('health','hospitals',true);SapoMapsApp.POIS.activateLayer('security','police');activateMasterLayer('security');toogleCategory('security','police',true);};function loadHTMLElements(){pubElem=document.getElementById('pub');resultsHolder=document.getElementById('results_holder');resultsElem=document.getElementById('results');queryBox=document.getElementById('Main_search_input');sendMail=document.getElementById('send_mail');getLink=document.getElementById('get_link');Panels={Itineraries:document.getElementById("iti_search"),Search:document.getElementById("results"),Layers:document.getElementById("mini_cat_list"),Customize:document.getElementById("personalizar"),Territory:document.getElementById("customize_territory"),Statistics:document.getElementById('stats_holder'),ItinerariesAndSearch:{Itineraries:document.getElementById("iti_search"),Search:document.getElementById("results")}}
selectedPanel=Panels.Layers;};function getPunyUrl(urlToCompress,completeHandler,timeoutHandler){var complete=null;var timeout=null;if(completeHandler!==undefined&&timeoutHandler!==undefined){complete=completeHandler;timeout=timeoutHandler;}else{complete=function(obj){document.getElementById("input_link").value=obj.punyURL.ascii;document.getElementById("input_link").select();};timeout=function(){document.getElementById("input_link").value="Serviço indisponível. Tente novamente mais tarde";};}
var url="http://services.sapo.pt/PunyURL/GetCompressedURLByURLJSON?url="+escape(urlToCompress);var rquesterObj=SAPO.Maps.Request.prototype.getRequester();rquesterObj.request(url,{timeout:4,onComplete:complete,onTimeout:timeout});};function validate_email_fields(){var name=document.getElementById('send_mail_name');var friendName=document.getElementById('send_mail_friend');var email=document.getElementById('send_mail_email');var status=document.getElementById('send_mail_status');var p_name=document.getElementById('send_mail_name_p');var p_friend=document.getElementById('send_mail_friend_p');var p_email=document.getElementById('send_mail_email_p');p_name.firstChild.className=name.value===''?'label_error':'';p_friend.firstChild.className=friendName.value===''?'label_error':'';p_email.firstChild.className=email.value===''?'label_error':'';name.className=name.value===''?'input_error':'';friendName.className=friendName.value===''?'input_error':'';email.className=email.value===''?'input_error':'';var msg='';if(name.value===''||friendName.value===''||email.value===''){status.className='error';status.innerHTML='Preenchimento obrigatório';status.style.display='block';return false;}
var filter=/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;if(!filter.test(email.value)){p_email.firstChild.className='input_not_valid';email.className='input_error';email.focus();status.style.display='block';status.className='error';status.innerHTML='Email inválido';return false;}
status.style.display='none';return true;};function adjustControlsPosition(){var floatLogo=OpenLayers.Util.getElement('float_sapologo');var mousePos=map.getControlsByClass('SAPO.Maps.Control.MousePosition2')[0];var navigation=map.getControlsByClass('SAPO.Maps.Control.Navigation2')[0];var maptype=map.getControlsByClass('SAPO.Maps.Control.MapType2')[0];var minimap=map.getControlsByClass('SAPO.Maps.Control.MiniMap2')[0];var scale=map.getControlsByClass('SAPO.Maps.Control.Scale')[0];var footer=document.getElementById('footer');var footer_offset=footer.offsetTop;var footer_height=footer.offsetHeight;var page_height=getClientHeight();var height=0;if(footer_offset<page_height&&!fullBrowser){height=page_height-footer_offset;}
scale.div.style.bottom=height+FOOTER_MARGIN+'px';scale.div.style.left=(panel_minimized||fullBrowser?MARGINS:LEFT_PANEL+MARGINS)+"px";mousePos.div.style.bottom=height+FOOTER_MARGIN+'px';navigation.div.style.top=(fullBrowser?MARGINS+floatLogo.offsetHeight:TOP_MARGIN+MARGINS)+"px";navigation.div.style.left=(panel_minimized||fullBrowser?MARGINS:LEFT_PANEL+MARGINS)+"px";maptype.div.style.top=(fullBrowser?MARGINS:TOP_MARGIN+MARGINS)+"px";maptype.div.style.right=MARGINS+minimap.div.offsetWidth+3+"px";minimap.div.style.top=(fullBrowser?MARGINS:TOP_MARGIN+MARGINS)+"px";minimap.div.style.right=MARGINS+"px";};function showPub(){document.getElementById('pub_quickaction').style.display='block';document.getElementById('pub_editorial').style.display='block';document.getElementById('pub_mrec').style.display='block';}
function hidePub(){document.getElementById('pub_quickaction').style.display='none';document.getElementById('pub_editorial').style.display='none';document.getElementById('pub_mrec').style.display='none';}
function removePubToDisplayPanel(elem,elem_margin,resElem,removeMrecIfNecessary){var quickaction=document.getElementById('pub_quickaction');var mrec=document.getElementById('pub_mrec');var editorial=document.getElementById('pub_editorial');var leftPanel=document.getElementById('left_col');if(!elem){return;}
showPub();var availlable_space=leftPanel.offsetHeight-quickaction.offsetHeight-editorial.offsetHeight-mrec.offsetHeight;var max_space=leftPanel.offsetHeight-mrec.offsetHeight;if(availlable_space===max_space){if(resElem&&leftPanel.offsetHeight>0){resElem.style.height=leftPanel.offsetHeight-elem_margin+"px";}
return;}
var elemHeight=elem.offsetHeight+elem_margin;if(elemHeight>availlable_space){if(elemHeight<availlable_space+quickaction.offsetHeight){if(resElem){resElem.style.height=availlable_space+quickaction.offsetHeight-elem_margin+'px';}
quickaction.style.display='none';}else{if(removeMrecIfNecessary&&elemHeight>max_space){quickaction.style.display='none';editorial.style.display='none';mrec.style.display="none";}
else{if(resElem){resElem.style.height=availlable_space+quickaction.offsetHeight+editorial.offsetHeight-elem_margin+'px';}
quickaction.style.display='none';editorial.style.display='none';}}}else{if(resElem){resElem.style.height=availlable_space+'px';}}}
function calcResultPanelDimensionsForSearch(){var leftPanel=document.getElementById('left_col');resultsElem.style.height=leftPanel.offsetHeight-86+"px";resultsElem.style.width=leftPanel.offsetWidth-8+"px";}
function calcResultPanelDimensionsForItineraries(){var leftPanel=document.getElementById('left_col');resultsElem.style.height=leftPanel.offsetHeight-Panels.Itineraries.offsetHeight-48+"px";resultsElem.style.width=leftPanel.offsetWidth-8+"px";}
function notifyUpdatedBorders(){wmanager.setBorders(SapoMapsApp.borders);map.getControlsByClass('SAPO.Maps.Control.ContextMenu')[0].borders=SapoMapsApp.borders;map.getControlsByClass('SAPO.Maps.Control.Navigation2')[0].borders=SapoMapsApp.borders;map.getControlsByClass('OpenLayers.Control.KeyboardDefaults')[0].borders=SapoMapsApp.borders;map.setBorders(SapoMapsApp.borders,SapoMapsApp.outerBorders);SapoMapsApp.WhereAmI.borders=SapoMapsApp.borders;}
function resizeWindow(evt){var mapas=document.getElementById('mapDiv');if(fullBrowser){mapas.style.height=getClientHeight()+'px';}else{mapas.style.height=(getClientHeight()-24)+'px';}
mapas.style.width=(getClientWidth())+'px';map.updateSize();adjustControlsPosition();if(selectedPanel===Panels.Itineraries){calcResultPanelDimensionsForItineraries();itinerariesModeChanged(true);}else if(selectedPanel===Panels.Search||selectedPanel===Panels.ItinerariesAndSearch){var aditionalContentHeight=selectedPanel===Panels.ItinerariesAndSearch?255:86;removePubToDisplayPanel(resultsElem.childNodes[0],aditionalContentHeight,resultsElem,false);}else{var removeMrecIfNecessary=selectedPanel===Panels.Territory||selectedPanel===Panels.Statistics?true:false;removePubToDisplayPanel(selectedPanel,0,null,removeMrecIfNecessary);}
s$('stats_holder').style.height=s$('left_col').offsetHeight+"px";s$('stats_results').style.height=(s$('left_col').offsetHeight-s$('stats_results').offsetTop)+"px";var fBrowser=document.getElementById("fullbrowser_exit");fBrowser.style.left=(getClientWidth()/2-fBrowser.offsetWidth/2)+"px";};function clearInput(input,defaultText,applyStyle){if(input.value!=defaultText)return;input.value='';if(applyStyle){input.className='custom_text';}};function setDefaultText(input,defaultText,applyStyle){if(input.value.length!=0&&input.value!=defaultText)return;input.value=defaultText;if(applyStyle){input.className='default_text';}};function open_url_box(){getLink.style.display='block';var input_link=document.getElementById('input_link');var url=SapoMapsApp.State.save();input_link.select();getPunyUrl(url);clipboard1=SAPO.Maps.Utils.copy2ClipboardWhenClick("copy_normal_link",function(){return document.getElementById("input_link").value;},close_boxes);var input_embed=document.getElementById('input_embed');var embedValue=SapoMapsApp.CMap.getCode();input_embed.value=embedValue;clipboard2=SAPO.Maps.Utils.copy2ClipboardWhenClick("copy_embed",function(){return document.getElementById("input_embed").value;},close_boxes);};function open_send_mail_box(){sendMail.style.display='block';};function send(){if(validate_email_fields()===false){return;}
var xhr;try{xhr=new XMLHttpRequest();}
catch(e){try{xhr=new ActiveXObject("Msxml2.XMLHTTP");}
catch(e){try{xhr=new ActiveXObject("Microsoft.XMLHTTP");}
catch(e){return false;}}}
var status=document.getElementById('send_mail_status');status.className='sending';status.innerHTML='A Enviar...';status.style.display='block';var inpFromName=document.getElementById("send_mail_name");var inpToName=document.getElementById("send_mail_friend");var inpMail=document.getElementById("send_mail_email");xhr.onreadystatechange=function(){if(xhr.readyState===4){var resObj=eval("("+xhr.responseText+")");if(!resObj.sent){status.className='error';status.innerHTML='Ocorreu um erro no envio do email.';status.style.display='block';}
if(resObj.sent){status.className='success';status.innerHTML='Email enviado com sucesso.';status.style.display='block';var timer=setTimeout(function(){inpToName.value='';inpMail.value='';close_boxes();clearTimeout(timer);},2000);}
var cleanStatusTimer=setTimeout(function(){status.style.display='none';clearTimeout(cleanStatusTimer);},2000);}};var fromName=inpFromName.value;var toName=inpToName.value;var toMail=inpMail.value;var link=SapoMapsApp.State.save();var url="SendEmailHandler.ashx";var params="fromName="+fromName+"&toName="+toName+"&toMail="+toMail+"&link="+escape(link);xhr.open("POST",url,true);xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");xhr.setRequestHeader("Content-length",params.length);xhr.setRequestHeader("Connection","close");xhr.send(params);};function close_boxes(){sendMail.style.display='none';getLink.style.display='none';hideCategories();try{clipboard1.destroy();clipboard2.destroy();}
catch(e){}};function copy_to_clipboard(inputId){SAPO.Maps.Utils.copy2Clipboard(document.getElementById(inputId).value);close_boxes();};function togglePanel(minimize,animation){if(fullBrowser){return;}
var leftPanel=document.getElementById('left_col');var close_bar=document.getElementById('close_bar');if(panel_minimized===minimize||!leftPanel){return;}
panel_minimized=minimize;document.getElementById('close_bar_arrow').className=minimize?'expand_leftcol':'';if(minimize){SapoMapsApp.borders.left-=LEFT_PANEL;SapoMapsApp.outerBorders.left-=LEFT_PANEL;adjustControlsPosition();}
else{SapoMapsApp.borders.left+=LEFT_PANEL;SapoMapsApp.outerBorders.left+=LEFT_PANEL;}
notifyUpdatedBorders();if(!animation){leftPanel.style.left=minimize?-1*(leftPanel.offsetWidth+8)+'px':0;close_bar.style.left=minimize?0:(leftPanel.offsetWidth)+'px';adjustControlsPosition();return;}
var delta_x=0;var steps=5;var interval=5;var curr_w=0;var w=leftPanel.offsetWidth;if(!minimize){delta_x=w/steps;curr_w=-1*w;}else{delta_x=(w/steps)*-1;}
var timer=window.setInterval(function(){curr_w+=delta_x;if(!minimize&&curr_w>=0){leftPanel.style.left='0px';close_bar.style.left=w+'px';window.clearInterval(timer);adjustControlsPosition();return;}
else if(minimize&&curr_w<=-1*w){leftPanel.style.left=-1*w+'px';close_bar.style.left='0px';window.clearInterval(timer);return;}
leftPanel.style.left=curr_w+'px';close_bar.style.left=curr_w+w+'px';},interval);};function addMarker(){SapoMapsApp.WhereAmI.addMarker();};function clearResults(clearStartState,clearEndState){if(selectedPanel===Panels.ItinerariesAndSearch){SapoMapsApp.Search.clear();selectedPanel=Panels.Itineraries;selectPanel('itinerary',true);return;}
SapoMapsApp.Search.clear();SapoMapsApp.Itineraries.clear(clearStartState,clearEndState);if(selectedPanel==Panels.Itineraries){removePubToDisplayPanel(selectedPanel,0,null,false);itinerariesModeChanged(false,true);}else{if(selectedPanel==Panels.Search){Panels.Layers.style.display='block';selectedPanel=Panels.Layers;removePubToDisplayPanel(this.selectedPanel,0,null,false);}else{showPub();}}};function selectPanel(panel,dontClear){if(selectedPanel==Panels.Statistics&&panel!=='statistics'&&panel!=='territory'){SapoMapsApp.Stats.unloadStatistics();}
if(selectedPanel===Panels.ItinerariesAndSearch){dontClear=true;panel='search';Panels.Itineraries.style.display='none';Panels.Search.style.display='block';}
if(selectedPanel===Panels.Territory){maptype.getTerritoryPanel().hide();}
if(!dontClear){clearResults();selectedPanel.style.display='none';}
switch(panel){case'itinerary':document.getElementById("results").className=document.getElementById("results").className.replace(/search/,"");document.getElementById("results").className+=" itineraries";Panels.Itineraries.style.display='block';selectedPanel=Panels.Itineraries;togglePanel(false,false);calcResultPanelDimensionsForItineraries();document.getElementById('from').focus();itinerariesModeChanged();SapoMapsApp.Analytics.track("Itinerario","Utilizacao","Activacao");return;case'customize':Panels.Customize.style.display='block'
selectedPanel=Panels.Customize;togglePanel(false,false);break;case'search':calcResultPanelDimensionsForSearch();togglePanel(false,false);selectedPanel=Panels.Search;break;case'itineraryAndSearch':Panels.Itineraries.style.display='block';selectedPanel=Panels.ItinerariesAndSearch;togglePanel(false,false);break;case'territory':Panels.Territory.style.display='block'
selectedPanel=Panels.Territory;togglePanel(false,false);removePubToDisplayPanel(this.selectedPanel,0,null,true);document.getElementById('pub').style.display='none';break;case'statistics':hidePub();Panels.Statistics.style.display='block'
selectedPanel=Panels.Statistics;togglePanel(false,false);maptype.unselectTerritoryConfigButton();break;default:Panels.Layers.style.display='block';selectedPanel=Panels.Layers;break;}
if(selectedPanel!==Panels.Search&&selectedPanel!==Panels.Statistics){var removeMrecIfNecessary=selectedPanel===Panels.Territory?true:false;removePubToDisplayPanel(this.selectedPanel,0,null,removeMrecIfNecessary);}};function search(){var txt=queryBox.value;if(txt.length===0||txt==='Pesquise por morada, negócio ou ponto de interesse'){return;}
SapoMapsApp.Search.getResults(txt);};function getItinerary(){var from=document.getElementById('from').value;var to=document.getElementById('to').value;var _mode=document.getElementById('mode').options[document.getElementById('mode').selectedIndex].value;var clearStartState=true,clearEndState=true;if(from===SapoMapsApp.Itineraries.from){clearStartState=false;}
if(to===SapoMapsApp.Itineraries.to){clearEndState=false;}
clearResults(clearStartState,clearEndState);if(from.length===0||to.length===0||from==='Indique o ponto de partida'||to==='Indique o ponto de chegada'){return;}
SapoMapsApp.Itineraries.getRoute(from,to,_mode);};function clickOpt(sectionIdx,arrayIdx,text,lonlat){switch(text){case'Itinerário a partir daqui':selectPanel('itinerary');SapoMapsApp.Itineraries.fromHere(lonlat);SapoMapsApp.Analytics.track("Funcionalidades","contextMenu","ItinerarioDaqui");break;case'Itinerário para aqui':selectPanel('itinerary');SapoMapsApp.Itineraries.toHere(lonlat);SapoMapsApp.Analytics.track("Funcionalidades","contextMenu","ItinerarioParaAaqui");break;case'Adicionar marcador':SapoMapsApp.WhereAmI.addMarker(lonlat);SapoMapsApp.Analytics.track("Funcionalidades","contextMenu","AdicionarMarcador");break;case'O que há aqui?':selectPanel('search');SapoMapsApp.Search.whatsHere(lonlat,map.getZoom());break;}};function print_map(){var url=SapoMapsApp.State.save();var params=url.split('?');url='index_print.html';if(params.length==2)url+='?'+params[1];window.open(url,'Imprimir','width=850,height=650,fullscreen=no,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes');};var minimized=true;function goFullBrowser(){if(fullBrowser===true){return;}
fullBrowser=true;SAPO.Maps.Utils.addClassName('bsu_container','hide');SAPO.Maps.Utils.addClassName('bsu_root','hide');SAPO.Maps.Utils.removeClassName('float_sapologo','hide');document.getElementById('header').style.display="none";document.getElementById('header_bg').style.display="none";document.getElementById('headerfade').style.display="none";document.getElementById('footer').style.display="none";document.getElementById('footer_bg').style.display="none";document.getElementById('left_col').style.display="none";document.getElementById('close_bar').style.display="none";SAPO.Maps.Utils.removeClassName(document.getElementById('fullbrowser_exit'),'hide');if(!panel_minimized){SapoMapsApp.borders.left-=LEFT_PANEL;SapoMapsApp.outerBorders.left-=LEFT_PANEL;}
SapoMapsApp.borders.top-=TOP_MARGIN;SapoMapsApp.borders.bottom-=FOOTER_HEIGHT;SapoMapsApp.outerBorders.top-=TOP_MARGIN;SapoMapsApp.outerBorders.bottom-=FOOTER_HEIGHT;notifyUpdatedBorders();adjustControlsPosition();resizeWindow();if(OpenLayers.Util.getBrowserName()==='firefox'){OpenLayers.Event.observe(window,"keydown",exitFullBrowserEscapeHandler,true);}else{OpenLayers.Event.observe(document.body,"keydown",exitFullBrowserEscapeHandler,true);}};function exitFullBrowserEscapeHandler(evt){if(evt&&evt.keyCode===OpenLayers.Event.KEY_ESC&&fullBrowser===true){exitFullBrowser();}};function exitFullBrowser(){if(fullBrowser===false){return;}
fullBrowser=false;SAPO.Maps.Utils.removeClassName('bsu_container','hide');SAPO.Maps.Utils.removeClassName('bsu_root','hide');SAPO.Maps.Utils.addClassName('float_sapologo','hide');document.getElementById('header').style.display="block";document.getElementById('header_bg').style.display="block";document.getElementById('headerfade').style.display="block";document.getElementById('footer').style.display="block";document.getElementById('footer_bg').style.display="block";document.getElementById('left_col').style.display="block";document.getElementById('close_bar').style.display="block";SAPO.Maps.Utils.addClassName(document.getElementById('fullbrowser_exit'),'hide');if(!panel_minimized){SapoMapsApp.borders.left+=LEFT_PANEL;SapoMapsApp.outerBorders.left+=LEFT_PANEL;}
SapoMapsApp.borders.top+=TOP_MARGIN;SapoMapsApp.borders.bottom+=FOOTER_HEIGHT;SapoMapsApp.outerBorders.top+=TOP_MARGIN;SapoMapsApp.outerBorders.bottom+=FOOTER_HEIGHT;notifyUpdatedBorders();adjustControlsPosition();resizeWindow();if(OpenLayers.Util.getBrowserName()==='firefox'){OpenLayers.Event.stopObserving(window,"keydown",exitFullBrowserEscapeHandler,true);}else{OpenLayers.Event.stopObserving(document.body,"keydown",exitFullBrowserEscapeHandler,true);}};function changeTheme(element,color){if(lastColorSelected===color){return;}
enableSaveSettingsButton();selectCurrentHTMLTheme(color);var styleSheetUrl='alternative_styles/'+color+'.css';if(alternativeStyleLink){alternativeStyleLink.href=styleSheetUrl;}
else{alternativeStyleLink=document.createElement('link');alternativeStyleLink.rel='stylesheet';alternativeStyleLink.href=escape(styleSheetUrl);document.getElementsByTagName("head")[0].appendChild(alternativeStyleLink);}};function selectCurrentHTMLTheme(theme){var element=document.getElementById(theme);if(lastColorSelected){var lastSelected=document.getElementById(lastColorSelected);SAPO.Maps.Utils.removeClassName(lastSelected,'active');}
element.className+=' active';lastColorSelected=theme;}
function itinerariesModeChanged(fromWindowResize,fromClearResults){var selection=document.getElementById("mode").value;switch(selection){case"fastest":case"shortest":case"walk":document.getElementById("transporlis").style.display="none";removePubToDisplayPanel(this.selectedPanel,0,null,false);break;case"transports":if(fromWindowResize){return;}
if(!fromClearResults&&(document.getElementById("results_holder").style.display!=="none"||!SapoMapsApp.Itineraries.f_here&&!SapoMapsApp.Itineraries.t_here)){var from=document.getElementById('from').value;var to=document.getElementById('to').value;var clearStartState=true,clearEndState=true;if(from===SapoMapsApp.Itineraries.from){clearStartState=false;}
if(to===SapoMapsApp.Itineraries.to){clearEndState=false;}
clearResults(clearStartState,clearEndState);}
if(document.getElementById("transporlis").style.display==="none"){updateDateHourValues();}
document.getElementById("transporlis").style.display="block";removePubToDisplayPanel(this.selectedPanel,0,null,false);document.getElementById('pub_mrec').style.display='none';break;}}
function showCalendar(){datePickerController.show("transporlis_data");}
function updateDateHourValues(){var date=new Date();var hours=document.getElementById("transporlis_horas");var minutes=document.getElementById("transporlis_minutos");hours.selectedIndex=date.getHours();minutes.selectedIndex=date.getMinutes();var dateInput=document.getElementById("transporlis_data");var year=date.getFullYear().toString();var month=(date.getMonth()+1)<10?("0"+(date.getMonth()+1).toString()):(date.getMonth()+1).toString();var day=date.getDate()<10?("0"+date.getDate().toString()):date.getDate().toString();dateInput.value=day+"/"+month+"/"+year;}
function toggleAllTravelModes(){var all=document.getElementById("transportes_todos");var train=document.getElementById("transportes_comboios");var boat=document.getElementById("transportes_barco");var metro=document.getElementById("transportes_metro");var bus=document.getElementById("transportes_autocarro");if(all.checked){train.checked=boat.checked=metro.checked=bus.checked=true;}
else{train.checked=boat.checked=metro.checked=bus.checked=false;}}
function toggleTravelMode(){var all=document.getElementById("transportes_todos");all.checked=false;}
function changeBanner(){if(map&&(map.baseLayer===map.getBaseLayers().HYBRID_MAP||map.baseLayer===map.getBaseLayers().SATELLITE_MAP)){document.getElementById("pub_editorial_img").style.display='block';if(document.getElementById('flashPubHolder')){document.getElementById('pub_editorial').removeChild(document.getElementById('flashPubHolder'));}
document.getElementById("pub_editorial_img").src="images/destaques/destaque_lojaIP.png";document.getElementById("link_destaque").href="#";document.getElementById("link_destaque").onclick=function(){var center=map.getMapCenter();window.open("http://www.infoportugal.pt/contacts/");trackDestaque();return false;}
document.getElementById("link_destaque").title="Comprar fotografia a�rea";}
else{var today=new Date(year,month-1,day);var beginDate=new Date(2011,11,12);var endDate=new Date(2012,0,5);if(today>=beginDate&&today<=endDate){document.getElementById("pub_editorial_img").src=chirstmasBannerURL;document.getElementById("link_destaque").href="#";document.getElementById("link_destaque").onclick=function(){toggleChristmasLayer();return false;};document.getElementById("link_destaque").title="Destques de Natal 2011";}
else{document.getElementById("pub_editorial_img").src="images/destaques/Censos2011.jpg";document.getElementById("link_destaque").href="#";document.getElementById("link_destaque").onclick=function(){SapoMapsApp.Stats.openModalBox();SapoMapsApp.Stats.selectModalTab('censos');return false;};document.getElementById("link_destaque").title="Censos 2011";}}}
function setPub(){var iframeElement=document.createElement("iframe");iframeElement.scrolling="NO";iframeElement.height="250";iframeElement.width="300";iframeElement.frameBorder="0";iframeElement.marginheight="0";iframeElement.marginwidth="0";iframeElement.src="mrec.html";document.getElementById("pub_mrec").appendChild(iframeElement);}
function enableSaveSettingsButton(){SAPO.Maps.Utils.removeClassName(document.getElementById('customize_spanbt1'),'pressed_btn');SAPO.Maps.Utils.removeClassName(document.getElementById('customize_spanbt2'),'pressed_btn');}
function disableSaveSettingsButton(){SAPO.Maps.Utils.addClassName(document.getElementById('customize_spanbt1'),'pressed_btn');SAPO.Maps.Utils.addClassName(document.getElementById('customize_spanbt2'),'pressed_btn');}
function saveSettings(){SapoMapsApp.Cookie.saveTheme(lastColorSelected);SapoMapsApp.Cookie.saveSettings();disableSaveSettingsButton();}
function initSuggest(){SapoMapsApp.Suggest.initialize("Main_search_input",{clickSuggestionCallback:search,scope:this});}
function openPreviewWindow(){window.open("http://"+location.host+location.pathname+"cmap/preview.html?iframe="+encodeURIComponent(encodeURIComponent(SapoMapsApp.CMap.getCode())),"_blank","status=0,toolbar=0,menubar=0,scrollbars=1,width=810,height=900");}
function trackDestaque(){SapoMapsApp.Analytics.track("Funcionalidades","Utilizacao","Destaque");}
function initWindowManager(){wmanager=new SAPO.Maps.WindowManager(map,{borders:{bottom:FOOTER_HEIGHT,top:TOP_MARGIN,right:0,left:LEFT_PANEL+50}});territoryPanel.setWindowManagerObj(wmanager);}
function openTerritoryPanel(){selectPanel('territory');var territoryPanel=maptype.getTerritoryPanel();if(!territoryPanel.isDrawn()){territoryPanel.draw();}
territoryPanel.show();maptype.selectTerritoryConfigButton();}
function closeTerritoryPanel(){if(SapoMapsApp.Stats.isStatisticActive()){selectPanel("statistics");}
else{selectPanel("layers");}
maptype.unselectTerritoryConfigButton();}
function initSearchFilters(){var search_filter=document.getElementById('search_filter');if(OpenLayers.Util.getBrowserName()==='msie'){SAPO.Maps.Utils.addClassName(search_filter,'ie');}
var filter_all=document.getElementById('search_filter_all');var filter_streets=document.getElementById('search_filter_streets');var filter_pois=document.getElementById('search_filter_pois');OpenLayers.Event.observe(filter_all,'click',searchFilterChanged)
OpenLayers.Event.observe(filter_streets,'click',searchFilterChanged)
OpenLayers.Event.observe(filter_pois,'click',searchFilterChanged)}
function showSearchFilters(){var search_filter=document.getElementById('search_filter');SAPO.Maps.Utils.removeClassName(search_filter,'hide');}
function hideSearchFilters(){var search_filter=document.getElementById('search_filter');SAPO.Maps.Utils.addClassName(search_filter,'hide');}
function searchFilterChanged(){SapoMapsApp.Search.getResults(SapoMapsApp.Search.query);}
function resetSearchFilter(){var filter_all=document.getElementById('search_filter_all');filter_all.checked=true;}
function debug(msg){}
function debug2(msg){}
SapoMapsApp={map:null,borders:{top:138,left:57+308,right:10,bottom:60},outerBorders:{top:75,left:308,right:0,bottom:20},urlToGetPOIInfo:{baseUrl:'http://services.sapo.pt/GIS/GetPOIByIdJSON?',poiId:null},initialize:function(map){this.map=map;map.events.register('click',this,this.closeInfoWindows);},closeInfoWindows:function(){var appObjs=['POIS','VirtualVisits','Panoramas','PharmsAtService','Traffic','Search','Itineraries','WhereAmI','Weather','Saber','Photos','Videos','News','Pub','Stats','Fuel','Zurich'];var obj=false;for(var i=0;i<appObjs.length;++i){obj=appObjs[i];if(SapoMapsApp[obj]){SapoMapsApp[obj].closeOpenedPopup();}}
closeOpenedChristmasLayerPopup();},getPOI:function(poiid,requester,requesterOpts){this.urlToGetPOIInfo.poiId=poiid;var url=this.getUrl(this.urlToGetPOIInfo);requester.request(url,requesterOpts);},getUrl:function(urlObj){var url="",first=true;for(var prop in urlObj){if(url.length===0){url+=urlObj[prop];}
else{if(!prop||urlObj[prop]===null||urlObj[prop]===undefined){continue;}
if(!first){url+="&";}
url+=prop+"="+urlObj[prop];first=false;}}
return url;}};
if(typeof(SapoMapsApp)=='undefined'){window.SapoMapsApp={};}else{window.SapoMapsApp=SapoMapsApp;}
SapoMapsApp.Analytics={id:null,channel:null,sectionGroup:null,subSectionGroup:null,frame:null,regex:null,initialize:function(){this.id=312286;this.channel="Mapas";this.sectionGroup="Vida e Lazer";this.subSectionGroup="Mapas "+this.id;this.regex=new RegExp("[^a-zA-Z0-9]","g");},track:function(section,subSection,content){if(!content){content="";}
content=content.replace(this.regex,"-");var counter=new wreport_counter(section,subSection,this.id,this.frame,this.channel,this.sectionGroup,this.subSectionGroup);if(content!==undefined){counter.add_content(content);}
counter.count();}};
SapoMapsApp.WebtrendsAnalytics={dcsid:"dcs939tj510000kjcex2426x9_5d6o",fpcdom:".sapo.pt",webtrendsObj:null,resultsSearchId:null,initialize:function(){this.webtrendsObj=_tag;this.webtrendsObj.DCSext.site_language="pt_PT";this.webtrendsObj.DCSext.site_type="SAPO MAPS YELLOW";this.webtrendsObj.DCSext.page="Web Search Results";},reset:function(){this.webtrendsObj.DCSext={};this.webtrendsObj.DCSext.site_language="pt_PT";this.webtrendsObj.DCSext.site_type="SAPO MAPS YELLOW";this.webtrendsObj.DCSext.page="Web Search Results";},pageView:function(args){this.reset();for(var i=0;i<args.length;i+=2){eval('this.webtrendsObj.'+args[i]+'=\''+args[i+1]+'\'');}
this.webtrendsObj.dcsCollectPage();},track:function(args,poi){this.reset();var costumerParameters=this.extractCustomerParameters(poi);var totalArgs=args.concat(costumerParameters);this.webtrendsObj.dcsMultiTrack.apply(this.webtrendsObj,totalArgs);},setWebtrendsParams:function(){var date=new Date();var year=date.getFullYear().toString();var month=date.getMonth().toString().length===1?"0"+date.getMonth().toString():date.getMonth().toString();var day=date.getDate().toString().length===1?"0"+date.getDate().toString():date.getDate().toString();var hours=date.getHours().toString().length===1?"0"+date.getHours().toString():date.getHours().toString();var minutes=date.getMinutes().toString().length===1?"0"+date.getMinutes().toString():date.getMinutes().toString();var seconds=date.getSeconds().toString().length===1?"0"+date.getSeconds().toString():date.getSeconds().toString();this.resultsSearchId="SPM_"+year+month+day+hours+minutes+seconds+"_"+SapoMapsApp.Search.search.randomToken;OpenLayers.Util.extend(this.webtrendsObj.DCSext,{page_searchtype:"simple",results_currentPage:SapoMapsApp.Search.search.getCurrentPage(SapoMapsApp.Search.search.openedZone),results_resultsPerPage:SapoMapsApp.Search.search.resultsPerPage,results_totalPages:Math.ceil(SapoMapsApp.Search.search.getTotalResults()/SapoMapsApp.Search.search.resultsPerPage),results_totalResults:SapoMapsApp.Search.search.getTotalResults(),search_what:SapoMapsApp.Search.query,results_searchId:this.resultsSearchId});this.webtrendsObj.WT.oss_r=SapoMapsApp.Search.search.getTotalResults()>0?1:0;},extractCustomerParameters:function(poi){if(!poi.DetailXml.Details.YellowPages||!poi.DetailXml.Details.YellowPages.CustomerInfo){return[];}
var details=poi.DetailXml.Details.YellowPages.CustomerInfo;if(details.ItemCode===''){details.ItemCode='null';}
return["DCSext.show_heading",details.HeadingId+"|"+details.Heading,"DCSext.show_itemCode",details.ItemCode,"DCSext.show_listingId",details.ListingId,"DCSext.show_name",poi.Name,"DCSext.show_productId",details.ProductId,"DCSext.show_subscriberId",details.SubscriberId];}};
SapoMapsApp.Tooltip={animated:true,fadeSteps:10,duration:500,timer:3500,initialize:function(map){},setOpacity:function(el,level){var divTooltip=document.getElementById(el);divTooltip.style.opacity=level;divTooltip.style.MozOpacity=level;divTooltip.style.KhtmlOpacity=level;divTooltip.style.filter="alpha(opacity="+(level*100)+");";},fadeIn:function(el){var divTooltip=document.getElementById(el);divTooltip.className="smapi_tooltip";for(i=0;i<=1;i+=(1/this.fadeSteps)){setTimeout("SapoMapsApp.Tooltip.setOpacity('smapi_tooltip',"+i+")",i*this.duration);}},fadeOut:function(el){var divTooltip=document.getElementById(el);divTooltip.className="smapi_tooltip";for(i=1;i===0;i-=(1/this.fadeSteps)){setTimeout("SapoMapsApp.Tooltip.setOpacity('smapi_tooltip',"+i+")",i*this.duration);}},showTooltip:function(msg){var divTooltip=document.getElementById('smapi_tooltip');divTooltip.innerHTML=msg;divTooltip.className="smapi_tooltip";if(this.animated){this.fadeIn('smapi_tooltip');}
if(this.timer){window.setInterval(function(){SapoMapsApp.Tooltip.hideTooltip();},this.timer);}},hideTooltip:function(){var divTooltip=document.getElementById('smapi_tooltip');divTooltip.innerHTML="";divTooltip.className="smapi_tooltip hide";}};
SapoMapsApp.GeoserverLayerManager={map:null,layers:null,currentLayerIdx:null,currentLayerEvent:null,initialize:function(map){this.map=map;this.layers=[];this.registerEvents();},registerEvents:function(){this.map.events.register('click',this,this.mapClicked);},addLayer:function(layerObj){if(this.layers.length===0){this.layers.push(layerObj);}
var newLayerZIndex=Number(layerObj.layer.getZIndex());for(var i=0;i<this.layers.length;++i){if(this.layers[i].layer===layerObj.layer){return;}
var zIndex=Number(this.layers[i].layer.getZIndex());if(zIndex>newLayerZIndex){this.layers.splice(i,0,layerObj);return;}}
this.layers.push(layerObj);},removeLayer:function(layer){for(var i=0;i<this.layers.length;++i){if(this.layers[i].layer===layer){this.layers.splice(i,1);}}},mapClicked:function(e){if(this.layers.length===0){return;}
this.currentEvent=e;this.currentLayerIdx=this.layers.length-1;var layerObj=this.layers[this.currentLayerIdx];layerObj.callback.apply(layerObj.context,[e]);},nextLayer:function(){--this.currentLayerIdx;if(this.currentLayerIdx<0){return;}
var layerObj=this.layers[this.currentLayerIdx];layerObj.callback.apply(layerObj.context,[this.currentEvent]);}};
SapoMapsApp.PharmsAtService=function(){this.active=false;this.markers=null;this.map=null;this.icon=null;this.requester=null;this.requestInProgress=false;this.validResults=true;this.pharmMarkers={};this.selectedPharm=null;this.stateToRecover=null;};SapoMapsApp.PharmsAtService.Url={baseUrl:'http://services.sapo.pt/Maps/GetPOIByBoundingBoxJSON?',fl:'Latitude,Longitude,POIId',latitude1:null,longitude1:null,latitude2:null,longitude2:null,onlyAtService:true,matchlevelId:10};SapoMapsApp.PharmsAtService.initialize=function(map){this.map=map;};SapoMapsApp.PharmsAtService.activate=function(){if(this.active){return;}
this.icon="http://imgs.sapo.pt/fotos_gis/PharmaciesAtService/icon.png";this.active=true;this.pharmMarkers={};this.validResults=true;this.markers=new SAPO.Maps.Markers("PharmaciesAtService");this.map.addMarkers(this.markers);this.map.events.register("moveend",this,this.refresh);this.refresh();try{SapoMapsApp.Analytics.track("Layers","Farmacias","ActivarLayer");}
catch(e){}};SapoMapsApp.PharmsAtService.deactivate=function(){if(this.requestInProgress){this.validResults=false;this.cancelRequests();}
this.map.events.unregister("moveend",this,this.refresh);if(this.markers){this.map.removeMarkers(this.markers);this.markers=null;this.icon=null;this.requester=null;}
this.active=false;this.pharmMarkers=null;};SapoMapsApp.PharmsAtService.isActive=function(){return this.active;};SapoMapsApp.PharmsAtService.getState=function(){if(!this.selectedPharm){return'';}
return"pharm,"+this.selectedPharm.POIId;};SapoMapsApp.PharmsAtService.setStateAfterLoad=function(state){this.stateToRecover=state.split(",")[1];};SapoMapsApp.PharmsAtService.setState=function(){var pharmMarker=this.pharmMarkers[this.stateToRecover];this.selectedPharm=pharmMarker;this.openPharmInfo(pharmMarker);};SapoMapsApp.PharmsAtService.closeOpenedPopup=function(){if(!this.selectedPharm){return;}
this.selectedPharm.closePopup();this.selectedPharm=null;};SapoMapsApp.PharmsAtService.refresh=function(){if(this.requestInProgress){this.cancelRequests();}
if(this.map.getZoom()<SapoMapsApp.Layers.health.layers.pharmaciesAtService.minZoom){this.removeMarkers(true);return;}
var bounds=this.map.getBounds();this.Url.latitude1=bounds.top.toFixed(6);this.Url.longitude1=bounds.right.toFixed(6);this.Url.latitude2=bounds.bottom.toFixed(6);this.Url.longitude2=bounds.left.toFixed(6);var url=SapoMapsApp.getUrl(this.Url);this.requester=SAPO.Maps.Request.prototype.getRequester();var _this=this;var reqID=this.requester.request(url,{timeout:4,onComplete:function(obj,args){if(!_this.validResults){return;}
this.requestInProgress=false;this.removeMarkers();try{var pharms=obj.Response.Result.POI;}
catch(e){return;}
if(!pharms.length){pharms=[pharms];}
var pharm=null;var lonlat;for(var i=0;i<pharms.length;++i){pharm=pharms[i];if(this.pharmMarkers[pharm.POIId]){continue;}
lonlat=new OpenLayers.LonLat(pharm.Longitude,pharm.Latitude);var marker=new SAPO.Maps.Marker(lonlat,{popupAnchor:new OpenLayers.Pixel(0,-11)},{markerImage:_this.icon,markerShadow:"",markerAnchor:new OpenLayers.Pixel(-11,-11),size:new OpenLayers.Size(22,22)});marker.POIId=pharm.POIId;marker.registerEvent('click',this,this.openPharmInfo);marker.registerEvent('popupclosed',this,function(marker){this.selectedPharm=null;});marker.registerEvent("mouseover",this,function(){map.div.style.cursor="pointer";});marker.registerEvent("mouseout",this,function(){map.div.style.cursor="";});this.pharmMarkers[pharm.POIId]=marker;this.markers.addMarker(marker);}
if(this.stateToRecover){this.setState();this.stateToRecover=null;}}.bindObj(this)});this.requestInProgress=true;};SapoMapsApp.PharmsAtService.openPharmInfo=function(marker){var poi=marker.poi;function openPopup(){var html=this.getHTML(marker.poi);marker.openPopup(html,{borders:SapoMapsApp.borders});}
function poiArrived(obj){marker.poi=obj.GetPOIByIdResponse.GetPOIByIdResult;if(this.selectedPharm===marker){openPopup.apply(this);}}
SapoMapsApp.closeInfoWindows();this.selectedPharm=marker;try{SapoMapsApp.Analytics.track("Layers","Farmacias","AbrirPin");}
catch(e){}
if(poi){openPopup.apply(this);}else{SapoMapsApp.getPOI(marker.POIId,this.requester,{timeout:4,onComplete:poiArrived.bindObj(this)});}};SapoMapsApp.PharmsAtService.removeMarkers=function(all){var marker;for(var i in this.pharmMarkers){marker=this.pharmMarkers[i];if(!all&&this.map.getBounds().containsLonLat(marker.getLonLat())){continue;}
if(!all&&marker.hasOpenedPopup()){continue;}
else{this.markers.removeMarker(this.pharmMarkers[i]);delete this.pharmMarkers[i];marker.poi=null;marker.POIId=null;}}};SapoMapsApp.PharmsAtService.cancelRequests=function(){this.requestInProgress=false;};SapoMapsApp.PharmsAtService.getHTML=function(pharm){var html='';try{var service=pharm.DetailXml.Details.Pharmacy.Services.Service;if(service instanceof Array){service=service[0];}
var name=pharm.Name;var type=service.Type;var date=service.LastUpdate;var street=pharm.Street;var parish=pharm.Parish;var phone=pharm.Phone;if(type){var arr=date.split('T');date=arr[0];}
html+="<div class=\"search_pop_header_smapi\">";html+="<p>"+name+"</p>";html+="<h2>"+date+" - "+type+"</h2>";html+="</div>";html+="<div class=\"search_pop_content_smapi\">";html+="<span class=\"search_destak_smaps\">Morada: </span>";html+=street+", "+parish;if(phone){html+="<br/>";html+="<span class=\"search_destak_smaps\">Telefone: </span>";html+=phone;}
html+="</div>";}
catch(e){}
return html;};
SapoMapsApp.Traffic=function(){this.active=false;this.markers=null;this.trafficMarkers=null;this.map=null;this.icons={};this.requester=null;this.zoom=null;this.requestInProgress=false;this.validResults=true;this.selectedTraffic=null;this.stateToRecover=null;};SapoMapsApp.Traffic.initialize=function(map){this.map=map;};SapoMapsApp.Traffic.activate=function(){if(this.active){return;}
this.active=true;this.validResults=true;this.icons={light:"http://imgs.sapo.pt/fotos_gis/Traffic/light.png",medium:"http://imgs.sapo.pt/fotos_gis/Traffic/medium.png",intense:"http://imgs.sapo.pt/fotos_gis/Traffic/intense.png"};this.zoom=this.map.getZoom();this.map.events.register("zoomend",this,this.zoomListener);this.markers=new SAPO.Maps.Markers("Traffic");this.map.addMarkers(this.markers);this.trafficMarkers={};this.registerEvents();this.refresh();};SapoMapsApp.Traffic.deactivate=function(){if(this.requestInProgress){this.validResults=false;this.cancelRequests();}
if(this.markers){this.map.removeMarkers(this.markers);this.markers=null;this.individualMarkers=null;this.icons=null;this.zoom=null;this.requester=null;this.map.events.unregister("zoomend",this,this.zoomListener);}
this.trafficMarkers=null;this.unregisterEvents();this.active=false;};SapoMapsApp.Traffic.registerEvents=function(){this.map.events.register("moveend",this,this.checkZoomLevel);};SapoMapsApp.Traffic.unregisterEvents=function(){this.map.events.unregister("moveend",this,this.checkZoomLevel);};SapoMapsApp.Traffic.checkZoomLevel=function(){if(this.map.getZoom()<SapoMapsApp.Layers.services.layers.traffic.minZoom){var markers=this.markers.getMarkers();for(var i=0;i<markers.length;++i){this.markers.removeMarker(markers[i]);}
this.trafficMarkers={};this.hidden=true;}
else{if(this.hidden){this.refresh();this.hidden=false;}}};SapoMapsApp.Traffic.isActive=function(){return this.active;};SapoMapsApp.Traffic.getState=function(){if(!this.selectedTraffic){return'';}
return"traffic,"+this.selectedTraffic.poi['a:POIId'];};SapoMapsApp.Traffic.setStateAfterLoad=function(state){this.stateToRecover=state.split(",")[1];};SapoMapsApp.Traffic.setState=function(){var trafficMarker=this.trafficMarkers[this.stateToRecover];if(trafficMarker){this.selectedTraffic=trafficMarker;var dateTime=trafficMarker.poi['a:PublicationDate'].split("T");var date=dateTime[0];var year=date.split("-")[0];var month=date.split("-")[1];var day=date.split("-")[2];var time=dateTime[1].substr(0,5);trafficMarker.openPopup("<p><strong>"+trafficMarker.poi['a:Name']+"</strong></p><p><em>&Uacute;ltima actualiza&ccedil&atilde;o: "+day+"/"+month+"/"+year+" - "+time+"</em></p><br/><p style=\"width: 320px;\">"+trafficMarker.poi['a:Description']+"</p>",{borders:SapoMapsApp.borders});}
else{var requester=SAPO.Maps.Request.prototype.getRequester();var reqID=requester.request("http://services.sapo.pt/GIS/GetPOIByIdJSON?poiId="+this.stateToRecover,{timeout:4,onComplete:function(obj,args){var poi;try{poi=obj.GetPOIByIdResponse.GetPOIByIdResult;}
catch(e){return;}
var lonlat=new OpenLayers.LonLat(poi.Longitude,poi.Latitude);var category=poi.DetailXml.Details.Traffic.Category;var icon=this.getIcon(category);var tmpMarker=new SAPO.Maps.Marker(lonlat,null,{markerImage:icon.image,markerShadow:"",size:icon.size,markerAnchor:new OpenLayers.Pixel(-icon.size.w/2,-icon.size.h)});tmpMarker.poi=poi;tmpMarker.registerEvent("click",this,function(marker){var dateTime=marker.poi.PublicationDate.split("T");var date=dateTime[0];var year=date.split("-")[0];var month=date.split("-")[1];var day=date.split("-")[2];var time=dateTime[1].substr(0,5);this.selectedTraffic=marker;marker.openPopup("<p><strong>"+marker.poi.Name+"</strong></p><p><em>&Uacute;ltima actualiza&ccedil&atilde;o: "+day+"/"+month+"/"+year+" - "+time+"</em></p><br/><p style=\"width: 320px;\">"+marker.poi.Description+"</p>",{borders:SapoMapsApp.borders});});if(!this.trafficMarkers[poi.POIId]){this.trafficMarkers[poi.POIId]=tmpMarker;this.markers.addMarker(tmpMarker);}
this.selectedTraffic=marker;marker.openPopup("<p><strong>"+marker.poi.Name+"</strong></p><p style=\"width: 200px;\">"+marker.poi.Description+"</p>",{borders:SapoMapsApp.borders});}.bindObj(this)});}};SapoMapsApp.Traffic.closeOpenedPopup=function(){if(!this.selectedTraffic){return;}
this.selectedTraffic.closePopup();this.selectedTraffic=null;};SapoMapsApp.Traffic.refresh=function(){if(this.requestInProgress){this.cancelRequests();}
var url="http://services.sapo.pt/Maps/GetTrafficJSON?pageNumber=1&recordsPerPage=300";this.requester=SAPO.Maps.Request.prototype.getRequester();var reqID=this.requester.request(url,{timeout:4,onComplete:function(obj,args){if(!this.validResults){return;}
this.requestInProgress=false;var pois;try{pois=obj.GetSimplifiedTrafficPOIResponse.GetSimplifiedTrafficPOIResult['a:POI'];}
catch(e){return;}
var poi;var tmpMarker=null;var lonlat;var category;var icon;var size;for(var i=0;i<pois.length;++i){poi=pois[i];lonlat=new OpenLayers.LonLat(poi['a:Longitude'],poi['a:Latitude']);category=poi['a:DetailXml']['a:Category'];if(Number(category)>5){continue;}
icon=this.getIcon(category);tmpMarker=new SAPO.Maps.Marker(lonlat,{popupAnchor:new OpenLayers.Pixel(0,-icon.size.h)},{markerImage:icon.image,markerShadow:"",size:icon.size,markerAnchor:new OpenLayers.Pixel(-icon.size.w/2,-icon.size.h)});tmpMarker.poi=poi;tmpMarker.registerEvent("click",this,function(marker){SapoMapsApp.closeInfoWindows();var dateTime=marker.poi['a:PublicationDate'].split("T");var date=dateTime[0];var year=date.split("-")[0];var month=date.split("-")[1];var day=date.split("-")[2];var time=dateTime[1].substr(0,5);this.selectedTraffic=marker;marker.openPopup("<p><strong>"+marker.poi['a:Name']+"</strong></p><p><em>&Uacute;ltima actualiza&ccedil&atilde;o: "+day+"/"+month+"/"+year+" - "+time+"</em></p><br/><p style=\"width: 320px;\">"+marker.poi['a:Description']+"</p>",{borders:SapoMapsApp.borders});try{SapoMapsApp.Analytics.track("Layers","Transito","AbrirPin");}
catch(e2){}});tmpMarker.registerEvent('popupclosed',this,function(marker){this.selectedTraffic=null;});if(!this.trafficMarkers[poi['a:POIId']]){this.trafficMarkers[poi['a:POIId']]=tmpMarker;tmpMarker.registerEvent("mouseover",this,function(){map.div.style.cursor="pointer";});tmpMarker.registerEvent("mouseout",this,function(){map.div.style.cursor="";});this.markers.addMarker(tmpMarker);}}
if(this.stateToRecover){this.setState();this.stateToRecover=null;}
map.getMessageBoardControl().hideMessage();}.bindObj(this)});this.requestInProgress=true;map.getMessageBoardControl().showMessage("A carregar");};SapoMapsApp.Traffic.getIcon=function(category){var zoom=this.map.getZoom();switch(Number(category)){case 1:if(zoom>9){return{image:this.icons.light,size:new OpenLayers.Size(17,31)};}
else{return{image:this.icons.light,size:new OpenLayers.Size(10,18)};}
case 2:case 3:if(zoom>9){return{image:this.icons.medium,size:new OpenLayers.Size(17,31)};}
else{return{image:this.icons.medium,size:new OpenLayers.Size(10,18)};}
case 4:case 5:if(zoom>9){return{image:this.icons.intense,size:new OpenLayers.Size(17,31)};}
else{return{image:this.icons.intense,size:new OpenLayers.Size(10,18)};}}};SapoMapsApp.Traffic.zoomListener=function(){var newZoom=this.map.getZoom();var feature=null,offset=null;if(this.zoom<=9&&newZoom>=10){feature=null;offset=new OpenLayers.Pixel(0,-15);for(var e in this.trafficMarkers){this.trafficMarkers[e].setStyle({size:new OpenLayers.Size(17,31),markerAnchor:new OpenLayers.Pixel(-9,-31)});this.trafficMarkers[e].options.popupAnchor.y=-31;}}
if(this.zoom>=10&&newZoom<=9){feature=null;offset=new OpenLayers.Pixel(0,-9);for(var f in this.trafficMarkers){this.trafficMarkers[f].setStyle({size:new OpenLayers.Size(10,18),markerAnchor:new OpenLayers.Pixel(-5,-18)});this.trafficMarkers[f].options.popupAnchor.y=-18;}}
this.zoom=newZoom;};SapoMapsApp.Traffic.cancelRequests=function(){this.requestInProgress=false;};
SapoMapsApp.VirtualVisits=function(){this.active=null;this.map=null;this.markers=null;this.requester=null;this.requestInProgress=null;this.validResults=null;this.window=null;this.multiplePanoramasWindow=null;this.multiplePanoramasWindowOpened=null;this.visitMarkers=null;this.selectedVisit=null;this.selectedVisitMarker=null;this.stateToRecover=null;this.markersStyle=null;this.markersOptions=null;};SapoMapsApp.VirtualVisits.url={baseUrl:'http://services.sapo.pt/Maps/GetPOIByBoundingBoxJSON?',fl:'POIId,Latitude,Longitude,Detail',latitude1:null,longitude1:null,latitude2:null,longitude2:null,categoryId:246,matchlevelId:0,trustlevelId:100,pageNumber:1,recordsPerPage:50,withMedia:true};SapoMapsApp.VirtualVisits.initialize=function(map){this.map=map;this.active=false;};SapoMapsApp.VirtualVisits.activate=function(){if(this.active){return;}
this.validResults=true;this.requestInProgress=false;this.visitMarkers={};this.requester=SAPO.Maps.Request.prototype.getRequester();this.markers=new SAPO.Maps.Markers("VirtualVisits360PT");this.map.addMarkers(this.markers);this.markersStyle={markerImage:"http://imgs.sapo.pt/fotos_gis/VirtualVisits/icon.png",markerAnchor:new OpenLayers.Pixel(-10,-10),size:new OpenLayers.Size(20,20)};this.markersOptions={popupAnchor:new OpenLayers.Pixel(0,-10)};this.registerEvents();this.active=true;this.refresh();};SapoMapsApp.VirtualVisits.deactivate=function(){if(!this.active){return;}
this.cancel();this.map.removeMarkers(this.markers);this.markers=null;this.markersStyle=null;this.unRegisterEvents();this.validResults=false;this.visitMarkers=null;this.requester=null;this.window=null;this.multiplePanoramasWindow=null;this.multiplePanoramasWindowOpened=false;this.markersStyle=null;this.markersOptions=null;this.selectedVisit=null;this.selectedVisitMarker=null;this.active=false;};SapoMapsApp.VirtualVisits.isActive=function(){return this.active;};SapoMapsApp.VirtualVisits.getState=function(){if(!this.selectedVisitMarker){return'';}
return"virtual,"+(this.selectedVisitMarker.poi.POIId);};SapoMapsApp.VirtualVisits.setStateAfterLoad=function(state){this.stateToRecover=state.split(",")[1];};SapoMapsApp.VirtualVisits.setState=function(){var visitMarker=this.visitMarkers[this.stateToRecover];if(visitMarker){this.openVisit(visitMarker);}
else{var rquesterObj=SAPO.Maps.Request.prototype.getRequester();var reqID=rquesterObj.request("http://services.sapo.pt/GIS/GetPOIByIdJSON?poiId="+this.stateToRecover,{timeout:4,onComplete:function(obj,args){var visit;try{visit=obj.GetPOIByIdResponse.GetPOIByIdResult;}
catch(e){return;}
var marker=new SAPO.Maps.Marker(new OpenLayers.LonLat(visit.Longitude,visit.Latitude),this.markersOptions,this.markersStyle);marker.poi=visit;this.visitMarkers[visit.POIId]=marker;this.markers.addMarker(marker);this.openVisit(marker);}.bindObj(this)});}};SapoMapsApp.VirtualVisits.registerEvents=function(){this.map.events.register("moveend",this,this.refresh);};SapoMapsApp.VirtualVisits.unRegisterEvents=function(){this.map.events.unregister("moveend",this,this.refresh);};SapoMapsApp.VirtualVisits.refresh=function(){if(this.requestInProgress){this.cancel();}
if(this.map.getZoom()<SapoMapsApp.Layers.services.layers.virtual.minZoom){this.removeMarkers(true);return;}
var bounds=this.map.getExtent();bounds.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));this.url.latitude1=bounds.top.toFixed(6);this.url.longitude1=bounds.right.toFixed(6);this.url.latitude2=bounds.bottom.toFixed(6);this.url.longitude2=bounds.left.toFixed(6);var url=SapoMapsApp.getUrl(this.url);this.requester=SAPO.Maps.Request.prototype.getRequester();var reqID=this.requester.request(url,{timeout:4,onComplete:this.resultsAvailable.bindObj(this)});this.validResults=true;this.requestInProgress=true;};SapoMapsApp.VirtualVisits.resultsAvailable=function(obj,args){if(!this.validResults){return;}
this.requestInProgress=false;this.removeMarkers();var pois;try{pois=obj.Response.Result.POI?obj.Response.Result.POI:[obj.Response.Result];if(!(pois instanceof Array)){pois=[pois];}}
catch(e1){return;}
this.processResults(pois);};SapoMapsApp.VirtualVisits.processResults=function(pois){var poi,marker;for(var i=0;i<pois.length;++i){poi=pois[i];if(!this.filterPoi(poi)){continue;}
marker=new SAPO.Maps.Marker(new OpenLayers.LonLat(poi.Longitude,poi.Latitude),this.markersOptions,this.markersStyle);marker.registerEvent('click',this,this.openVisit);marker.POIId=poi.POIId;if(!this.visitMarkers[poi.POIId]){this.visitMarkers[poi.POIId]=marker;marker.registerEvent("mouseover",this,function(){map.div.style.cursor="pointer";});marker.registerEvent("mouseout",this,function(){map.div.style.cursor="";});this.markers.addMarker(marker);}}
if(this.stateToRecover){this.setState();this.stateToRecover=null;}};SapoMapsApp.VirtualVisits.filterPoi=function(poi){if(!poi||!poi.DetailXml||!poi.DetailXml.Details||!poi.DetailXml.Details._3dCities){return false;}
return true;};SapoMapsApp.VirtualVisits.removeMarkers=function(all){var marker;for(var i in this.visitMarkers){marker=this.visitMarkers[i];if(!all&&this.map.getBounds().containsLonLat(marker.getLonLat())){continue;}
if(!all&&marker.hasOpenedPopup()){continue;}
else{this.visitMarkers[i].unRegisterEvent('click',this,this.openVisit);this.markers.removeMarker(this.visitMarkers[i]);delete this.visitMarkers[i];marker.poi=null;marker.POIId=null;}}};SapoMapsApp.VirtualVisits.closeOpenedPopup=function(e){if(this.selectedVisitMarker){this.selectedVisitMarker.closePopup();this.selectedVisitMarker=null;}
if(this.selectedVisitMarkerMulti){this.selectedVisitMarkerMulti.closePopup();this.selectedVisitMarkerMulti=null;}};SapoMapsApp.VirtualVisits.cancel=function(){this.validResults=false;this.requestInProgress=false;};SapoMapsApp.VirtualVisits.openVisit=function(marker){var poi=marker.poi;function openPopup(){this.showVirtual3D(marker);this.selectedVisit=poi;}
function poiArrived(obj){marker.poi=obj.GetPOIByIdResponse.GetPOIByIdResult;if(this.selectedVisitMarker===marker){openPopup.apply(this);}}
SapoMapsApp.closeInfoWindows();this.selectedVisitMarker=marker;this.selectedVisitMarker.registerEvent("popupclosed",this,this.popupClosed);try{SapoMapsApp.Analytics.track("Layers","VisitasVirtuais","AbrirVisita");}
catch(e){}
if(marker.poi){openPopup.apply(this);}else{SapoMapsApp.getPOI(marker.POIId,this.requester,{timeout:4,onComplete:poiArrived.bindObj(this)});}};SapoMapsApp.VirtualVisits.popupClosed=function(){if(!this.selectedVisitMarker){return;}
this.selectedVisitMarker.unRegisterEvent("popupclosed",this,this.popupClosed);this.selectedVisitMarker=null;};SapoMapsApp.VirtualVisits.showVirtual3D=function(marker){var virtualPoi=marker.poi;var virtualPoiDetails=virtualPoi.DetailXml;var holder=document.body;if(virtualPoiDetails.Details._3dCities.EntityInteractiveVisit&&virtualPoiDetails.Details._3dCities.EntityInteractiveVisit.InteractiveVisit){this.showInteractiveVisit(holder,marker,virtualPoiDetails.Details._3dCities.EntityInteractiveVisit);}else if(virtualPoiDetails.Details._3dCities.EntityVirtualVisit){this.showVirtualVisit(holder,marker,virtualPoiDetails.Details._3dCities.EntityVirtualVisit);}};SapoMapsApp.VirtualVisits.buildVirtualDescription=function(virtualPoi){var descriptionHTML='';if(virtualPoi.Description){descriptionHTML+=virtualPoi.Description+'<br/><br/>';if(virtualPoi.Address&&virtualPoi.Address!==''){descriptionHTML+='Morada: '+virtualPoi.Address+'<br />';}
if(virtualPoi.Phone&&virtualPoi.Phone!==''){descriptionHTML+='Telefone: '+virtualPoi.Phone+'<br />';}
if(virtualPoi.Fax&&virtualPoi.Fax!==''){descriptionHTML+='Fax: '+virtualPoi.Fax+'<br />';}
if(virtualPoi.EMail&&virtualPoi.EMail!==''){descriptionHTML+='e-mail: <a href="mailto:'+virtualPoi.EMail+'">'+virtualPoi.EMail+'</a><br/>';}
if(virtualPoi.URL&&virtualPoi.URL!==''){descriptionHTML+='Site: <a target="_new" href="http://'+virtualPoi.URL+'">'+virtualPoi.URL+'</a><br/>';}}
return descriptionHTML;};SapoMapsApp.VirtualVisits.buildVirtualDescription360PT=function(virtualPoi){var descriptionHTML='';if(virtualPoi.Description){descriptionHTML+=virtualPoi.Description+'<br/><br/>';if(virtualPoi.Address&&virtualPoi.Address!==''){descriptionHTML+='Morada: '+virtualPoi.Address+'<br />';}
if(virtualPoi.Phone&&virtualPoi.Phone!==''){descriptionHTML+='Telefone: '+virtualPoi.Phone+'<br />';}
if(virtualPoi.Fax&&virtualPoi.Fax!==''){descriptionHTML+='Fax: '+virtualPoi.Fax+'<br />';}
if(virtualPoi.EMail&&virtualPoi.EMail!==''){descriptionHTML+='e-mail: <a href="mailto:'+virtualPoi.EMail+'">'+virtualPoi.EMail+'</a><br/>';}}
return descriptionHTML;};SapoMapsApp.VirtualVisits.showInteractiveVisit=function(holder,marker,interactiveVisit){var virtualPoi=marker.poi;var div_content=document.createElement("div");var div_header=document.createElement("div");var div_links=document.createElement("div");var a_description=document.createElement("a");var p_header_content=document.createElement("p");var div_flash=document.createElement("div");var div_description=document.createElement("div");var p_description_content=document.createElement("p");var div_footer=document.createElement("div");p_header_content.innerHTML=interactiveVisit.Text?interactiveVisit.Text:virtualPoi.Name;this.InteractiveVisit(div_flash,interactiveVisit.InteractiveVisit,627,328);var size=OpenLayers.Util.getRenderedDimensions(div_flash.innerHTML);div_footer.innerHTML='<a target="_new" style="color: #636163;" href="http://www.3dcities.com">'+'3DCities. Todos os direitos reservados.'.replace(/ /g,'&nbsp;')+'</a>';p_description_content.innerHTML=this.buildVirtualDescription(virtualPoi);a_description.innerHTML="[Ver descri&ccedil;&atilde;o]";div_header.className="pop_header";a_description.style.cursor="pointer";a_description.style.fontSize="10px";div_content.style.width=size.w+"px";div_flash.style.height="328px";p_description_content.style.marginTop="10px";p_description_content.style.lineHeight="17px";p_description_content.style.textAlign="justify";div_description.className="pop_content";div_description.style.overflowY="auto";div_description.style.height="328px";div_description.style.maxHeight="328px";div_description.style.display="none";div_footer.className="pop_content";div_footer.style.textAlign="center";div_footer.style.color="#636163";var showDescriptionFunction=function(){div_content.style.height=div_content.clientHeight+"px";div_description.style.display="block";div_flash.style.display="none";a_description.innerHTML="[Fechar descri&ccedil;&atilde;o]";a_description.onclick=closeDescriptionFunction;}.bindObj(this);var closeDescriptionFunction=function(){div_description.style.display="none";div_flash.style.display="block";a_description.innerHTML="[Ver descri&ccedil;&atilde;o]";a_description.onclick=showDescriptionFunction;}.bindObj(this);a_description.onclick=showDescriptionFunction;if(p_description_content.innerHTML!==""){div_links.appendChild(a_description);}
div_header.appendChild(p_header_content);div_description.appendChild(p_description_content);div_content.appendChild(div_header);div_content.appendChild(div_links);div_content.appendChild(div_flash);div_content.appendChild(div_description);div_content.appendChild(div_footer);marker.openPopup(div_content,{borders:SapoMapsApp.borders});};SapoMapsApp.VirtualVisits.showVirtualVisit=function(holder,marker,guid){var virtualPoi=marker.poi;var width=800;var height=500;if(this.map.div.clientWidth<900||this.map.div.clientHeight<720){width=520;height=350;}
var div_content=document.createElement("div");var div_header=document.createElement("div");var div_links=document.createElement("div");var p_header_content=document.createElement("p");var div_flash=document.createElement("div");var a_description=document.createElement("a");var div_description=document.createElement("div");var p_description_content=document.createElement("p");var div_footer=document.createElement("div");this.VirtualVisit(div_flash,guid,width,height);var size=OpenLayers.Util.getRenderedDimensions(div_flash.innerHTML);p_header_content.innerHTML=virtualPoi.Name;p_description_content.innerHTML=virtualPoi.Description;a_description.innerHTML="[Ver descri&ccedil;&atilde;o]";div_footer.innerHTML='<a target="_new" style="color: #636163;" href="http://www.3dcities.com">'+'3DCities. Todos os direitos reservados.'.replace(/ /g,'&nbsp;')+'</a>';div_content.style.width=size.w+"px";div_flash.style.height=height+"px";div_header.className="pop_header";div_description.className="pop_content";div_description.style.height=height+"px";div_description.style.maxHeight=height+"px";div_description.style.overflowY="auto";p_description_content.style.marginTop="10px";p_description_content.style.lineHeight="17px";p_description_content.style.textAlign="justify";div_description.style.display="none";a_description.style.cursor="pointer";a_description.style.fontSize="10px";div_footer.className="pop_content";div_footer.style.textAlign="center";div_footer.style.color="#636163";var showDescriptionFunction=function(){div_content.style.height=div_content.clientHeight+"px";div_description.style.display="block";div_flash.style.display="none";a_description.innerHTML="[Fechar descri&ccedil;&atilde;o]";a_description.onclick=closeDescriptionFunction;}.bindObj(this);var closeDescriptionFunction=function(){div_description.style.display="none";div_flash.style.display="block";a_description.innerHTML="[Ver descri&ccedil;&atilde;o]";a_description.onclick=showDescriptionFunction;}.bindObj(this);a_description.onclick=showDescriptionFunction;div_header.appendChild(p_header_content);if(p_description_content.innerHTML!==""){div_links.appendChild(a_description);}
div_description.appendChild(p_description_content);div_content.appendChild(div_header);div_content.appendChild(div_links);div_content.appendChild(div_flash);div_content.appendChild(div_description);div_content.appendChild(div_footer);marker.openPopup(div_content,{borders:SapoMapsApp.borders});};SapoMapsApp.VirtualVisits.showPanorama=function(holder,marker,panorama,isFromMultiPanorama){var virtualPoi=marker.poi;var div_content=document.createElement("div");var div_header=document.createElement("div");var div_links=document.createElement("div");var p_header_content=document.createElement("p");var div_flash=document.createElement("div");var div_tooltip=document.createElement("div");var div_description=document.createElement("div");var div_copyright=document.createElement("div");var a_description=document.createElement("a");var p_description_content=document.createElement("p");p_header_content.innerHTML=(virtualPoi.Name.indexOf(panorama.Text)!=-1)?virtualPoi.Name:virtualPoi.Name+': '+panorama.Text;div_tooltip.innerHTML="<p>Arraste a imagem para navegar no panorama.</p>";this.Panorama(div_flash,panorama.Image);var size=OpenLayers.Util.getRenderedDimensions(div_flash.innerHTML);a_description.innerHTML="[Ver descri&ccedil;&atilde;o]";p_description_content.innerHTML=this.buildVirtualDescription(virtualPoi);div_copyright.innerHTML='<a target="_new" style="color: #636163;" href="http://www.3dcities.com">'+'3DCities. Todos os direitos reservados.'.replace(/ /g,'&nbsp;')+'</a>';div_content.style.width=size.w+"px";div_header.className="pop_header";a_description.style.fontSize="10px";a_description.style.cursor="pointer";div_tooltip.className="pop_content";div_tooltip.style.textAlign="center";p_description_content.style.marginTop="10px";p_description_content.style.lineHeight="17px";p_description_content.style.textAlign="justify";div_flash.style.height="300px";div_description.className="pop_content";div_description.style.maxHeight="315px";div_description.style.height="315px";div_description.style.overflowY="auto";div_description.style.display="none";div_copyright.className="pop_content";div_copyright.style.textAlign="center";div_copyright.style.color="#636163";if(isFromMultiPanorama){this.selectedVisitMarker=marker;a_description.style.marginLeft="10px";var a_return=document.createElement("a");a_return.style.fontSize="10px";a_return.innerHTML="[Voltar aos panoramas]";a_return.onclick=function(){this.openVisit(marker);}.bindObj(this);a_return.style.cursor="pointer";div_links.appendChild(a_return);marker.closePopup();}
var showDescriptionFunction=function(){div_content.style.height=div_content.clientHeight+"px";div_description.style.display="block";div_flash.style.display="none";div_tooltip.style.display="none";a_description.innerHTML="[Fechar descri&ccedil;&atilde;o]";a_description.onclick=closeDescriptionFunction;}.bindObj(this);var closeDescriptionFunction=function(){div_description.style.display="none";div_flash.style.display="block";div_tooltip.style.display="block";a_description.innerHTML="[Ver descri&ccedil;&atilde;o]";a_description.onclick=showDescriptionFunction;}.bindObj(this);a_description.onclick=showDescriptionFunction;if(p_description_content.innerHTML!==""){div_links.appendChild(a_description);}
div_header.appendChild(p_header_content);div_header.appendChild(div_links);div_content.appendChild(div_header);div_content.appendChild(div_flash);div_content.appendChild(div_tooltip);div_description.appendChild(p_description_content);div_content.appendChild(div_description);div_content.appendChild(div_copyright);marker.openPopup(div_content,{borders:SapoMapsApp.borders});};SapoMapsApp.VirtualVisits.showPanoramaList=function(holder,marker,panoramas){this.selectedVisitMarker=marker;var virtualPoi=marker.poi;var MAX_SIZE=150;var thumbsDiv=document.createElement('div');for(var i=0;i<panoramas.length;++i){var img=document.createElement("img");img.src='http://62.28.57.115/3DPortugal/BackOfficeImages2/Images/'+panoramas[i].ImageThumb+'.jpg';if(img.width>MAX_SIZE||img.height>MAX_SIZE){var ratio=img.width/img.height;img.width=ratio>=1?MAX_SIZE:MAX_SIZE*ratio;img.height=ratio<1?MAX_SIZE:MAX_SIZE/ratio;}
var label=document.createElement('a');label.href='#';label.appendChild(document.createTextNode(panoramas[i].Text));var thumb=this.Thumb(null,label,img);thumbsDiv.appendChild(thumb);var fn=function(e){if(!e){e=window.event;}
var poiContainer=document.getElementById(arguments.callee.panorama.Image);if(poiContainer){holder.appendChild(poiContainer);}else{poiContainer=SapoMapsApp.VirtualVisits.showPanorama(holder,marker,arguments.callee.panorama,true);}
OpenLayers.Event.stop(e);};fn.holder=holder;fn.virtualPoi=virtualPoi;fn.panorama=panoramas[i];Event.observe(thumb,'click',fn);}
var div_content=document.createElement("div");var div_header=document.createElement("div");var p_header_content=document.createElement("p");var div_flash=document.createElement("div");var div_footer=document.createElement("div");div_header.className="pop_header";p_header_content.innerHTML=virtualPoi.Name;div_header.appendChild(p_header_content);div_flash.style.width="400px";div_flash.appendChild(thumbsDiv);div_content.style.width="400px";div_footer.className="pop_content";div_footer.style.maxHeight="100px";div_footer.style.width="400px";div_footer.style.overflowY="auto";div_footer.innerHTML='<a target="_new" style="color: #636163;" href="http://www.3dcities.com">'+'3DCities. Todos os direitos reservados.'.replace(/ /g,'&nbsp;')+'</a>';div_flash.style.textAlign="center";div_footer.style.textAlign="center";div_content.appendChild(div_header);div_content.appendChild(div_flash);div_content.appendChild(div_footer);marker.openPopup(div_content,{borders:SapoMapsApp.borders});};SapoMapsApp.VirtualVisits.Thumb=function(holder,label,img){var a=document.createElement("span");a.style.display='inline-block';a.style.padding='2px';cell=document.createElement("div");if(typeof img=='string'){cell.innerHTML='<img src="'+img+'"/>';}
else{cell.appendChild(img);}
a.appendChild(cell);cell=document.createElement("div");if(typeof label=='string'){cell.innerHTML=label;}
else{cell.appendChild(label);}
a.appendChild(cell);if(holder){holder.appendChild(a);}
return a;};SapoMapsApp.VirtualVisits.Panorama=function(holder,photoID,width,height){var obj=document.createElement("span");var frame=document.createElement('iframe');frame.src='http://62.28.57.115/3DPortugal/Widgets/Content/Clip/Viewers/PanoramaFlash.aspx?panoramaID='+photoID;frame.width=(width?width:350);frame.height=(height?height:300);frame.scrolling='no';frame.setAttribute('frameBorder','0');obj.appendChild(frame);if(holder){holder.appendChild(obj);}
return obj;};SapoMapsApp.VirtualVisits.Visit=function(holder,url,width,height){var obj=document.createElement("span");var frame=document.createElement('iframe');frame.src=url;frame.width=(width?width:627);frame.height=(height?height:328);frame.scrolling='no';frame.setAttribute('frameBorder','0');obj.appendChild(frame);if(holder){holder.appendChild(obj);}
return obj;};SapoMapsApp.VirtualVisits.InteractiveVisit=function(holder,guid,width,height){return this.Visit(holder,'http://62.28.57.115/3DPortugal/Widgets/Content/Clip/Viewers/InteractiveVisit.aspx?VisitID='+guid,width?width:627,height?height:328);};SapoMapsApp.VirtualVisits.VirtualVisit=function(holder,guid,width,height){if(width>520&&height>350){return this.Visit(holder,'http://62.28.57.115/3DPortugal/Widgets/Content/Clip/Viewers/VirtualVisit.aspx?visitID='+guid,width?width:800,height?height:500);}
else{return this.Visit(holder,'http://62.28.57.115/3DPortugal/BackOfficeImages2/VirtualTourShort/'+guid+"/vtour.html",width?width:520,height?height:350);}};SapoMapsApp.VirtualVisits.showVirtual360PT=function(marker){var poi=marker.poi;var playerFileName=poi.DetailXml.Details["_360:Portugal360"]["_360:PlayerFileName"];if(playerFileName.indexOf("PurePlayer")!==-1){var div_content=document.createElement("div");var div_header=document.createElement("div");var p_header_content=document.createElement("p");var div_links=document.createElement("div");var a_description=document.createElement("a");var div_description=document.createElement("div");var p_description_content=document.createElement("p");var div_flash=document.createElement("div");var div_flash_wraper=document.createElement("div");var div_footer=document.createElement("div");p_header_content.innerHTML=poi.Name;p_description_content.innerHTML=SapoMapsApp.VirtualVisits.buildVirtualDescription360PT(poi);div_footer.innerHTML='<a target="_new" style="color: #636163;" href="http://www.360portugal.com/">'+'360Portugal. Todos os direitos reservados.'.replace(/ /g,'&nbsp;')+'</a>';a_description.innerHTML="[Ver descri&ccedil;&atilde;o]";div_header.className="pop_header";div_flash_wraper.style.height="300px";div_footer.className="pop_content";div_footer.style.maxWidth="400px";div_content.style.width="400px";div_description.style.display="none";div_description.style.height="300px";div_description.className="pop_content";p_description_content.style.lineHeight="17px";p_description_content.style.textAlign="justify";div_footer.style.textAlign="center";a_description.style.fontSize="10px";a_description.style.cursor="pointer";var showDescriptionFunction=function(){div_content.style.height=div_content.clientHeight+"px";div_description.style.display="block";div_flash_wraper.style.display="none";a_description.innerHTML="[Fechar descri&ccedil;&atilde;o]";a_description.onclick=closeDescriptionFunction;}.bindObj(this);var closeDescriptionFunction=function(){div_description.style.display="none";div_flash_wraper.style.display="block";a_description.innerHTML="[Ver descri&ccedil;&atilde;o]";a_description.onclick=showDescriptionFunction;}.bindObj(this);a_description.onclick=showDescriptionFunction;if(p_description_content.innerHTML!==""){div_links.appendChild(a_description);}
div_header.appendChild(p_header_content);div_flash.id="__SAPO_MAPS_WEBSITE_VIRTUAL_VISIT_360_PORTUGAL";div_flash_wraper.appendChild(div_flash);div_description.appendChild(p_description_content);div_content.appendChild(div_header);div_content.appendChild(div_links);div_content.appendChild(div_flash_wraper);div_content.appendChild(div_description);div_content.appendChild(div_footer);marker.openPopup(div_content,{borders:SapoMapsApp.borders});marker.registerEvent("popupclosed",this,function(){this.selectedVisitMarker=null;});this.embedSWF_purePlayer(poi);document.getElementById("__SAPO_MAPS_WEBSITE_VIRTUAL_VISIT_360_PORTUGAL").style.visibility="";}};SapoMapsApp.VirtualVisits.embedSWF_purePlayer=function(poi){swfobject.embedSWF("files/PurePlayer.swf","__SAPO_MAPS_WEBSITE_VIRTUAL_VISIT_360_PORTUGAL","400","300","9.0.0",null,{panorama:"files/"+poi.DetailXml.Details["_360:Portugal360"]["_360:VisitFileName"]},{allowscriptaccess:"sameDomain",allowfullscreen:"true",wmode:"transparent"});};
SapoMapsApp.Panoramas=function(){this.active=null;this.map=null;this.markers=null;this.requester=null;this.requestInProgress=null;this.validResults=null;this.window=null;this.multiplePanoramasWindow=null;this.multiplePanoramasWindowOpened=null;this.visitMarkers=null;this.selectedVisit=null;this.selectedVisitMarker=null;this.stateToRecover=null;this.markersStyle=null;this.markersOptions=null;};SapoMapsApp.Panoramas.url={baseUrl:'http://services.sapo.pt/Maps/GetPOIByBoundingBoxJSON?',fl:'POIId,Latitude,Longitude',latitude1:null,longitude1:null,latitude2:null,longitude2:null,categoryId:355,matchlevelId:0,trustlevelId:100,pageNumber:1,recordsPerPage:50,withMedia:true};SapoMapsApp.Panoramas.initialize=function(map){this.map=map;this.active=false;};SapoMapsApp.Panoramas.activate=function(){if(this.active){return;}
this.validResults=true;this.requestInProgress=false;this.visitMarkers={};this.requester=SAPO.Maps.Request.prototype.getRequester();this.markers=new SAPO.Maps.Markers("VirtualVisits360PT");this.map.addMarkers(this.markers);this.markersStyle={markerImage:"http://imgs.sapo.pt/fotos_gis/Panoramas/icon.png",markerAnchor:new OpenLayers.Pixel(-10,-10),size:new OpenLayers.Size(20,20)};this.markersOptions={popupAnchor:new OpenLayers.Pixel(0,-10)};this.registerEvents();this.active=true;this.refresh();};SapoMapsApp.Panoramas.deactivate=function(){if(!this.active){return;}
this.cancel();this.map.removeMarkers(this.markers);this.markers=null;this.markersStyle=null;this.unRegisterEvents();this.validResults=false;this.visitMarkers=null;this.requester=null;this.window=null;this.multiplePanoramasWindow=null;this.multiplePanoramasWindowOpened=false;this.markersStyle=null;this.markersOptions=null;this.selectedVisit=null;this.selectedVisitMarker=null;this.active=false;};SapoMapsApp.Panoramas.isActive=function(){return this.active;};SapoMapsApp.Panoramas.getState=function(){if(!this.selectedVisitMarker){return'';}
return"panoramas,"+(this.selectedVisitMarker.poi.POIId);};SapoMapsApp.Panoramas.setStateAfterLoad=function(state){this.stateToRecover=state.split(",")[1];};SapoMapsApp.Panoramas.setState=function(){var visitMarker=this.visitMarkers[this.stateToRecover];if(visitMarker){this.openVisit(visitMarker);}
else{var syndicationObj=new SAPO.Communication.Syndication();var reqID=syndicationObj.push("http://services.sapo.pt/GIS/GetPOIByIdJSON?poiId="+this.stateToRecover,{timeout:4,onComplete:function(obj,args){var visit=obj.GetPOIByIdResponse.GetPOIByIdResult;var marker=new SAPO.Maps.Marker(new OpenLayers.LonLat(visit.Longitude,visit.Latitude),this.markersOptions,this.markersStyle);marker.poi=visit;this.visitMarkers[visit.POIId]=marker;this.markers.addMarker(marker);this.openVisit(marker);}.bindObj(this)});syndicationObj.run(reqID);}};SapoMapsApp.Panoramas.registerEvents=function(){this.map.events.register("moveend",this,this.refresh);};SapoMapsApp.Panoramas.unRegisterEvents=function(){this.map.events.unregister("moveend",this,this.refresh);};SapoMapsApp.Panoramas.refresh=function(){if(this.requestInProgress){this.cancel();}
if(this.map.getZoom()<SapoMapsApp.Layers.services.layers.virtual.minZoom){this.removeMarkers(true);return;}
var bounds=this.map.getExtent();bounds.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));this.url.latitude1=bounds.top.toFixed(6);this.url.longitude1=bounds.right.toFixed(6);this.url.latitude2=bounds.bottom.toFixed(6);this.url.longitude2=bounds.left.toFixed(6);var url=SapoMapsApp.getUrl(this.url);this.requester=SAPO.Maps.Request.prototype.getRequester();var reqID=this.requester.request(url,{timeout:4,onComplete:this.resultsAvailable.bindObj(this)});this.validResults=true;this.requestInProgress=true;};SapoMapsApp.Panoramas.resultsAvailable=function(obj,args){if(!this.validResults){return;}
this.requestInProgress=false;this.removeMarkers();var pois;try{pois=obj.Response.Result.POI?obj.Response.Result.POI:[obj.Response.Result];if(!(pois instanceof Array)){pois=[pois];}}
catch(e1){return;}
this.processResults(pois);};SapoMapsApp.Panoramas.processResults=function(pois){var poi,marker;for(var i=0;i<pois.length;++i){poi=pois[i];marker=new SAPO.Maps.Marker(new OpenLayers.LonLat(poi.Longitude,poi.Latitude),this.markersOptions,this.markersStyle);marker.registerEvent('click',this,this.openVisit);marker.POIId=poi.POIId;if(!this.visitMarkers[poi.POIId]){this.visitMarkers[poi.POIId]=marker;marker.registerEvent("mouseover",this,function(){map.div.style.cursor="pointer";});marker.registerEvent("mouseout",this,function(){map.div.style.cursor="";});this.markers.addMarker(marker);}}
if(this.stateToRecover){this.setState();this.stateToRecover=null;}};SapoMapsApp.Panoramas.removeMarkers=function(all){var marker;for(var i in this.visitMarkers){marker=this.visitMarkers[i];if(!all&&this.map.getBounds().containsLonLat(marker.getLonLat())){continue;}
if(!all&&marker.hasOpenedPopup()){continue;}
else{this.visitMarkers[i].unRegisterEvent('click',this,this.openVisit);this.markers.removeMarker(this.visitMarkers[i]);delete this.visitMarkers[i];marker.POIId=null;marker.poi=null;}}};SapoMapsApp.Panoramas.closeOpenedPopup=function(e){if(this.selectedVisitMarker){this.selectedVisitMarker.closePopup();this.selectedVisitMarker=null;}
if(this.selectedVisitMarkerMulti){this.selectedVisitMarkerMulti.closePopup();this.selectedVisitMarkerMulti=null;}};SapoMapsApp.Panoramas.cancel=function(){this.validResults=false;this.requestInProgress=false;};SapoMapsApp.Panoramas.openVisit=function(marker){function openPopup(){var poi=marker.poi;if(poi.SourceId==21){this.showVirtual360PT(marker);}
else{if(poi.SourceId==20){this.showVirtual3D(marker);}
else{if(poi.SourceId==32){this.showGloriosoPanoramaList(marker);}}}
this.selectedVisit=poi;}
function poiArrived(obj){var poi=obj.GetPOIByIdResponse.GetPOIByIdResult;marker.poi=poi;if(this.selectedVisitMarker===marker){openPopup.apply(this);}}
SapoMapsApp.closeInfoWindows();this.selectedVisitMarker=marker;this.selectedVisitMarker.registerEvent("popupclosed",this,this.popupClosed);try{SapoMapsApp.Analytics.track("Layers","VisitasVirtuais","AbrirVisita");}catch(e){}
if(marker.poi){openPopup.apply(this);}
else{SapoMapsApp.getPOI(marker.POIId,this.requester,{timeout:4,onComplete:poiArrived.bindObj(this)});}};SapoMapsApp.Panoramas.popupClosed=function(){if(!this.selectedVisitMarker){return;}
this.selectedVisitMarker.unRegisterEvent("popupclosed",this,this.popupClosed);this.selectedVisitMarker=null;};SapoMapsApp.Panoramas.showVirtual3D=function(marker){var virtualPoi=marker.poi;var virtualPoiDetails=virtualPoi.DetailXml;var holder=document.body;if(virtualPoiDetails.Details._3dCities.EntityPanoramas.Panoramas.Panorama.length){this.showPanoramaList(holder,marker,virtualPoiDetails.Details._3dCities.EntityPanoramas.Panoramas.Panorama);}
else{this.showPanorama(holder,marker,virtualPoiDetails.Details._3dCities.EntityPanoramas.Panoramas.Panorama);}};SapoMapsApp.Panoramas.buildVirtualDescription=function(virtualPoi){var descriptionHTML='';if(virtualPoi.Description){descriptionHTML+=virtualPoi.Description+'<br/><br/>';if(virtualPoi.Address&&virtualPoi.Address!==''){descriptionHTML+='Morada: '+virtualPoi.Address+'<br />';}
if(virtualPoi.Phone&&virtualPoi.Phone!==''){descriptionHTML+='Telefone: '+virtualPoi.Phone+'<br />';}
if(virtualPoi.Fax&&virtualPoi.Fax!==''){descriptionHTML+='Fax: '+virtualPoi.Fax+'<br />';}
if(virtualPoi.EMail&&virtualPoi.EMail!==''){descriptionHTML+='e-mail: <a href="mailto:'+virtualPoi.EMail+'">'+virtualPoi.EMail+'</a><br/>';}
if(virtualPoi.URL&&virtualPoi.URL!==''){descriptionHTML+='Site: <a target="_new" href="http://'+virtualPoi.URL+'">'+virtualPoi.URL+'</a><br/>';}}
return descriptionHTML;};SapoMapsApp.Panoramas.buildVirtualDescription360PT=function(virtualPoi){var descriptionHTML='';if(virtualPoi.Description){descriptionHTML+=virtualPoi.Description+'<br/><br/>';if(virtualPoi.Address&&virtualPoi.Address!==''){descriptionHTML+='Morada: '+virtualPoi.Address+'<br />';}
if(virtualPoi.Phone&&virtualPoi.Phone!==''){descriptionHTML+='Telefone: '+virtualPoi.Phone+'<br />';}
if(virtualPoi.Fax&&virtualPoi.Fax!==''){descriptionHTML+='Fax: '+virtualPoi.Fax+'<br />';}
if(virtualPoi.EMail&&virtualPoi.EMail!==''){descriptionHTML+='e-mail: <a href="mailto:'+virtualPoi.EMail+'">'+virtualPoi.EMail+'</a><br/>';}}
return descriptionHTML;};SapoMapsApp.Panoramas.showPanorama=function(holder,marker,panorama,isFromMultiPanorama){var virtualPoi=marker.poi;var div_content=document.createElement("div");var div_header=document.createElement("div");var div_links=document.createElement("div");var p_header_content=document.createElement("p");var div_flash=document.createElement("div");var div_tooltip=document.createElement("div");var div_description=document.createElement("div");var div_copyright=document.createElement("div");var a_description=document.createElement("a");var p_description_content=document.createElement("p");p_header_content.innerHTML=(virtualPoi.Name.indexOf(panorama.Text)!=-1)?virtualPoi.Name:virtualPoi.Name+': '+panorama.Text;div_tooltip.innerHTML="<p>Arraste a imagem para navegar no panorama.</p>";this.Panorama(div_flash,panorama.Image);var size=OpenLayers.Util.getRenderedDimensions(div_flash.innerHTML);a_description.innerHTML="[Ver descri&ccedil;&atilde;o]";p_description_content.innerHTML=this.buildVirtualDescription(virtualPoi);div_copyright.innerHTML='<a target="_new" style="color: #636163;" href="http://www.3dcities.com">'+'3DCities. Todos os direitos reservados.'.replace(/ /g,'&nbsp;')+'</a>';div_content.style.width=size.w+"px";div_header.className="pop_header";a_description.style.fontSize="10px";a_description.style.cursor="pointer";div_tooltip.className="pop_content";div_tooltip.style.textAlign="center";p_description_content.style.marginTop="10px";p_description_content.style.lineHeight="17px";p_description_content.style.textAlign="justify";div_flash.style.height="300px";div_description.className="pop_content";div_description.style.maxHeight="315px";div_description.style.height="315px";div_description.style.overflowY="auto";div_description.style.display="none";div_copyright.className="pop_content";div_copyright.style.textAlign="center";div_copyright.style.color="#636163";if(isFromMultiPanorama){this.selectedVisitMarker=marker;a_description.style.marginLeft="10px";var a_return=document.createElement("a");a_return.style.fontSize="10px";a_return.innerHTML="[Voltar aos panoramas]";a_return.onclick=function(){this.openVisit(marker);}.bindObj(this);a_return.style.cursor="pointer";div_links.appendChild(a_return);marker.closePopup();}
var showDescriptionFunction=function(){div_content.style.height=div_content.clientHeight+"px";div_description.style.display="block";div_flash.style.display="none";div_tooltip.style.display="none";a_description.innerHTML="[Fechar descri&ccedil;&atilde;o]";a_description.onclick=closeDescriptionFunction;}.bindObj(this);var closeDescriptionFunction=function(){div_description.style.display="none";div_flash.style.display="block";div_tooltip.style.display="block";a_description.innerHTML="[Ver descri&ccedil;&atilde;o]";a_description.onclick=showDescriptionFunction;}.bindObj(this);a_description.onclick=showDescriptionFunction;if(p_description_content.innerHTML!==""){div_links.appendChild(a_description);}
var div_loader=document.createElement("div");var img_loader=document.createElement("img");img_loader.width="111";img_loader.height="82";img_loader.src="http://js.sapo.pt/Assets/Maps/Images/bigwheel_1.gif";div_loader.appendChild(img_loader);div_loader.style.position="absolute";div_loader.style.top="150px";div_loader.style.left="120px";div_content.appendChild(div_loader);div_flash.childNodes[0].childNodes[0].onload=div_flash.childNodes[0].childNodes[0].onreadystatechange=function(){div_loader.style.display="none";};div_header.appendChild(p_header_content);div_header.appendChild(div_links);div_content.appendChild(div_header);div_content.appendChild(div_flash);div_content.appendChild(div_tooltip);div_description.appendChild(p_description_content);div_content.appendChild(div_description);div_content.appendChild(div_copyright);marker.openPopup(div_content,{borders:SapoMapsApp.borders});};SapoMapsApp.Panoramas.showPanoramaList=function(holder,marker,panoramas){this.selectedVisitMarker=marker;var virtualPoi=marker.poi;var MAX_SIZE=150;var thumbsDiv=document.createElement('div');for(var i=0;i<panoramas.length;++i){var img=document.createElement("img");img.src='http://62.28.57.115/3dportugal/Widgets/Content/Clip/Viewers/PanoramaThumbnail.aspx?PanoramaId='+panoramas[i].Image;if(img.width>MAX_SIZE||img.height>MAX_SIZE){var ratio=img.width/img.height;img.width=ratio>=1?MAX_SIZE.toString():(MAX_SIZE*ratio).toString();img.height=ratio<1?MAX_SIZE.toString():(MAX_SIZE/ratio).toString();}
var label=document.createElement('a');label.href='#';label.appendChild(document.createTextNode(panoramas[i].Text));var thumb=this.Thumb(null,label,img);thumbsDiv.appendChild(thumb);var fn=function(e){if(!e){e=window.event;}
var poiContainer=document.getElementById(arguments.callee.panorama.Image);if(poiContainer){holder.appendChild(poiContainer);}else{poiContainer=SapoMapsApp.Panoramas.showPanorama(holder,marker,arguments.callee.panorama,true);}
OpenLayers.Event.stop(e);};fn.holder=holder;fn.virtualPoi=virtualPoi;fn.panorama=panoramas[i];Event.observe(thumb,'click',fn);}
var div_content=document.createElement("div");var div_header=document.createElement("div");var p_header_content=document.createElement("p");var div_flash=document.createElement("div");var div_footer=document.createElement("div");div_header.className="pop_header";p_header_content.innerHTML=virtualPoi.Name;div_header.appendChild(p_header_content);div_flash.style.width="400px";div_flash.appendChild(thumbsDiv);div_content.style.width="400px";div_footer.className="pop_content";div_footer.style.maxHeight="100px";div_footer.style.width="400px";div_footer.style.overflowY="auto";div_footer.innerHTML='<a target="_new" style="color: #636163;" href="http://www.3dcities.com">'+'3DCities. Todos os direitos reservados.'.replace(/ /g,'&nbsp;')+'</a>';div_flash.style.textAlign="center";div_footer.style.textAlign="center";div_content.appendChild(div_header);div_content.appendChild(div_flash);div_content.appendChild(div_footer);marker.openPopup(div_content,{borders:SapoMapsApp.borders});};SapoMapsApp.Panoramas.Thumb=function(holder,label,img){var a=document.createElement("span");a.style.display='inline-block';a.style.padding='2px';cell=document.createElement("div");if(typeof img=='string'){cell.innerHTML='<img src="'+img+'" width="100" height="90""/>';}
else{img.width="100";img.height="90";cell.appendChild(img);}
a.appendChild(cell);cell=document.createElement("div");if(typeof label=='string'){cell.innerHTML=label;}
else{cell.appendChild(label);}
a.appendChild(cell);if(holder){holder.appendChild(a);}
return a;};SapoMapsApp.Panoramas.Panorama=function(holder,photoID,width,height){var obj=document.createElement("span");var frame=document.createElement('iframe');frame.src='http://62.28.57.115/3DPortugal/Widgets/Content/Clip/Viewers/PanoramaFlash.aspx?panoramaID='+photoID;frame.width=(width?width:350);frame.height=(height?height:300);frame.scrolling='no';frame.setAttribute('frameBorder','0');obj.appendChild(frame);if(holder){holder.appendChild(obj);}
return obj;};SapoMapsApp.Panoramas.Visit=function(holder,url,width,height){var obj=document.createElement("span");var frame=document.createElement('iframe');frame.src=url;frame.width=(width?width:627);frame.height=(height?height:328);frame.scrolling='no';frame.setAttribute('frameBorder','0');obj.appendChild(frame);if(holder){holder.appendChild(obj);}
return obj;};SapoMapsApp.Panoramas.InteractiveVisit=function(holder,guid,width,height){return this.Visit(holder,'http://62.28.57.115/3DPortugal/Widgets/Content/Clip/Viewers/InteractiveVisit.aspx?VisitID='+guid,width?width:627,height?height:328);};SapoMapsApp.Panoramas.VirtualVisit=function(holder,guid,width,height){return this.Visit(holder,'http://62.28.57.115/3DPortugal/Widgets/Content/Clip/Viewers/VirtualVisit.aspx?visitID='+guid,width?width:800,height?height:500);};SapoMapsApp.Panoramas.showVirtual360PT=function(marker){var poi=marker.poi;var playerFileName=poi.DetailXml.Details["_360:Portugal360"]["_360:PlayerFileName"];if(playerFileName.indexOf("PurePlayer")!==-1){var div_content=document.createElement("div");var div_header=document.createElement("div");var p_header_content=document.createElement("p");var div_links=document.createElement("div");var a_description=document.createElement("a");var div_description=document.createElement("div");var p_description_content=document.createElement("p");var div_flash=document.createElement("div");var div_flash_wraper=document.createElement("div");var div_footer=document.createElement("div");p_header_content.innerHTML=poi.Name;p_description_content.innerHTML=SapoMapsApp.Panoramas.buildVirtualDescription360PT(poi);div_footer.innerHTML='<a target="_new" style="color: #636163;" href="http://www.360portugal.com/">'+'360Portugal. Todos os direitos reservados.'.replace(/ /g,'&nbsp;')+'</a>';a_description.innerHTML="[Ver descri&ccedil;&atilde;o]";div_header.className="pop_header";div_flash_wraper.style.height="300px";div_flash_wraper.style.width="400px";div_footer.className="pop_content";div_footer.style.maxWidth="400px";div_content.style.width="400px";div_description.style.display="none";div_description.style.height="300px";p_description_content.style.lineHeight="17px";p_description_content.style.textAlign="justify";div_footer.style.textAlign="center";a_description.style.fontSize="10px";a_description.style.cursor="pointer";var showDescriptionFunction=function(){div_content.style.height=div_content.clientHeight+"px";div_description.style.display="block";div_flash_wraper.style.display="none";a_description.innerHTML="[Fechar descri&ccedil;&atilde;o]";a_description.onclick=closeDescriptionFunction;}.bindObj(this);var closeDescriptionFunction=function(){div_description.style.display="none";div_flash_wraper.style.display="block";a_description.innerHTML="[Ver descri&ccedil;&atilde;o]";a_description.onclick=showDescriptionFunction;}.bindObj(this);a_description.onclick=showDescriptionFunction;if(p_description_content.innerHTML!==""){div_links.appendChild(a_description);}
div_header.appendChild(p_header_content);div_flash.id="__SAPO_MAPS_WEBSITE_VIRTUAL_VISIT_360_PORTUGAL";div_flash_wraper.appendChild(div_flash);div_description.appendChild(p_description_content);div_content.appendChild(div_header);div_content.appendChild(div_links);div_content.appendChild(div_flash_wraper);div_content.appendChild(div_description);div_content.appendChild(div_footer);marker.openPopup(div_content,{borders:SapoMapsApp.borders});marker.registerEvent("popupclosed",this,function(){this.selectedVisitMarker=null;});this.embedSWF_purePlayer(poi);document.getElementById("__SAPO_MAPS_WEBSITE_VIRTUAL_VISIT_360_PORTUGAL").style.visibility="";}};SapoMapsApp.Panoramas.embedSWF_purePlayer=function(poi){swfobject.embedSWF("files/PurePlayer.swf","__SAPO_MAPS_WEBSITE_VIRTUAL_VISIT_360_PORTUGAL","400","300","9.0.0",null,{panorama:"files/"+poi.DetailXml.Details["_360:Portugal360"]["_360:VisitFileName"]},{allowscriptaccess:"sameDomain",allowfullscreen:"true",wmode:"transparent"});};SapoMapsApp.Panoramas.showGloriosoPanoramaList=function(marker){var _this=this;this.selectedVisitMarker=marker;var baseAddr="http://mapas.sapo.pt/files/";var panoramas=marker.poi.DetailXml.Details.Panoramas.Panorama;var div_content=document.createElement("div");var div_header=document.createElement("div");var div_list=document.createElement("div");var div_footer=document.createElement("div");div_header.className="pop_header";div_header.innerHTML="<p>Est&aacute;dio da Luz</p>";div_list.style.textAlign="center";div_footer.className="pop_content";div_footer.style.textAlign="center";div_footer.innerHTML="<a href='"+marker.poi.URL+"' style='color: rgb(99,97,99);' target='_new'> Ant&oacute;nio Cabral Fotografia. Todos os direitos reservados.</a>";var a_title,thumb;for(var i=0;i<panoramas.length;++i){var img=baseAddr+panoramas[i].Thumbnail;a_title=document.createElement("a");a_title.href="#";a_title.innerHTML=panoramas[i].Title;thumb=SapoMapsApp.Panoramas.Thumb(div_list,a_title,img);thumb.marker=marker;thumb.panorama=panoramas[i];thumb.onclick=function(e){SapoMapsApp.Panoramas.showGloriosoPanorama.apply(_this,[this.marker,this.panorama]);};}
div_content.appendChild(div_header);div_content.appendChild(div_list);div_content.appendChild(div_footer);marker.openPopup(div_content,{borders:SapoMapsApp.borders});marker.registerEvent("popupclosed",this,function(){this.selectedVisitMarker=null;});};SapoMapsApp.Panoramas.showGloriosoPanorama=function(marker,panorama){var baseAddr="http://mapas.sapo.pt/files/";var div_content=document.createElement("div");var div_header=document.createElement("div");var div_flash=document.createElement("div");var div_back=document.createElement("div");var a_back=document.createElement("a");var div_footer=document.createElement("div");div_content.style.width="400px";div_content.style.height="383px";a_back.style.fontSize="10px";a_back.style.cursor="pointer";a_back.innerHTML="[Voltar aos panoramas]";a_back.onclick=function(){this.openVisit(marker);}.bindObj(this);div_header.className="pop_header";div_header.innerHTML="<p>Est&aacute;dio da Luz: "+panorama.Title+"</p>";div_back.appendChild(a_back);div_header.appendChild(div_back);div_flash.style.width="500px";div_flash.style.height="375px";div_flash.id="__SAPO_MAPS_WEBSITE_VIRTUAL_VISIT_GLORIOSO";div_footer.className="pop_content";div_footer.style.textAlign="center";div_footer.innerHTML="<p>Arraste a imagem para navegar no panorama.</p>";div_footer.innerHTML+="<a href='"+marker.poi.URL+"' style='color: rgb(99,97,99);' target='_new'> Ant&oacute;nio Cabral Fotografia. Todos os direitos reservados.</a>";div_content.appendChild(div_header);div_content.appendChild(div_flash);div_content.appendChild(div_footer);marker.closePopup();this.selectedVisitMarker=marker;marker.openPopup(div_content,{borders:SapoMapsApp.borders});marker.registerEvent("popupclosed",this,function(){this.selectedVisitMarker=null;});swfobject.embedSWF(baseAddr+panorama.FileName,"__SAPO_MAPS_WEBSITE_VIRTUAL_VISIT_GLORIOSO","400","300","7.0.0","",[],{"swliveconnect":"default","play":"true","loop":"true","menu":"false","quality":"autohigh","scale":"showall","align":"l","salign":"tl","wmode":"opaque","bgcolor":"#FFFFFF","version":"7","allowfullscreen":"true","allowscriptaccess":"sameDomain","base":baseAddr,"src":baseAddr+panorama.FileName,"height":400,"width":300});};
SapoMapsApp.Weather={url:{baseUrl:'http://services.sapo.pt/Maps/GetPOIByBoundingBoxJSON?',fl:'Latitude,Longitude,Detail,Name,MunicipalityId,DistrictId',latitude1:null,longitude1:null,latitude2:null,longitude2:null,categoryId:200,matchlevelId:0,trustlevelId:0,pageNumber:1,recordsPerPage:50,withMedia:true,fq:null},active:false,map:null,zoom:null,weather:{},selectedWeather:null,markersObject:null,requester:null,markersStyle:null,markersOptions:null,requestInProgress:false,validResults:true,initialize:function(map){this.map=map;},activate:function(){if(this.active){return;}
this.requester=SAPO.Maps.Request.prototype.getRequester();this.markersObject=new SAPO.Maps.Markers("SAPOMapsWeather");this.map.addMarkers(this.markersObject);this.registerEvents();this.active=true;this.refresh();},deactivate:function(){if(!this.active){return;}
this.map.removeMarkers(this.markersObject);this.requester=null;this.markersObject=null;this.selectedNew=null;this.weather={};this.unregisterEvents();this.active=false;},isActive:function(){return this.active;},getState:function(){if(!this.selectedWeather){return"";}
return"weather,"+this.selectedWeather.poi.MunicipalityId;},setStateAfterLoad:function(id){this.stateToRecover=id.split(",")[1];},setState:function(){var markers=this.markersObject.getMarkers();if(markers.length===0){return;}
var id=this.zoom<12?this.stateToRecover.substr(0,2):this.stateToRecover;for(var e in markers){if(markers[e].poi.DistrictId===id||markers[e].poi.MunicipalityId===id){this.showWeatherForMarker(markers[e]);this.stateToRecover=null;return;}}},registerEvents:function(){this.map.events.register("moveend",this,this.refresh);},unregisterEvents:function(){this.map.events.unregister("moveend",this,this.refresh);},closeOpenedPopup:function(){if(this.selectedWeather){this.selectedWeather.closePopup();this.selectedWeather=null;}},refresh:function(){if(!this.active){return;}
if(this.requestsInProgresss){this.cancelRequests();}
if(this.map.getZoom()<SapoMapsApp.Layers.services.layers.weather.minZoom){this.validResults=false;this.removeMarkers(true);return;}
var oldZoom=this.zoom;this.zoom=this.map.getZoom();if(oldZoom>=12&&this.zoom<12){this.removeMarkers(true);}
else{this.removeMarkers();}
if(this.zoom<12){this.getWeatherForDistricts();}
else{this.getWeatherForMunicipalities();}
this.validResults=true;},getWeatherForDistricts:function(){var bounds=this.map.getBounds();this.url.latitude1=bounds.top.toFixed(6);this.url.longitude1=bounds.right.toFixed(6);this.url.latitude2=bounds.bottom.toFixed(6);this.url.longitude2=bounds.left.toFixed(6);this.url.fq="SystemTags:DISTRICT_CAPITAL";var url=SapoMapsApp.getUrl(this.url);this.requester=SAPO.Maps.Request.prototype.getRequester();var reqID=this.requester.request(url,{timeout:4,onComplete:this.districtResultsAvailable.bindObj(this)});this.requestsInProgresss=true;},districtResultsAvailable:function(obj){this.requestsInProgresss=false;var pois;try{pois=obj.Response.Result.POI?obj.Response.Result.POI:[obj.Response.Result];if(!(pois instanceof Array)){pois=[pois];}}
catch(e1){return;}
this.processResults(pois);},getWeatherForMunicipalities:function(){var bounds=this.map.getBounds();this.url.latitude1=bounds.top.toFixed(6);this.url.longitude1=bounds.right.toFixed(6);this.url.latitude2=bounds.bottom.toFixed(6);this.url.longitude2=bounds.left.toFixed(6);this.url.fq=null;var url=SapoMapsApp.getUrl(this.url);this.requester=SAPO.Maps.Request.prototype.getRequester();var reqID=this.requester.request(url,{timeout:4,onComplete:this.municipalityResultsAvailable.bindObj(this)});this.requestsInProgress=true;},municipalityResultsAvailable:function(obj){this.requestsInProgress=false;var pois;try{pois=obj.Response.Result.POI?obj.Response.Result.POI:[obj.Response.Result];if(!(pois instanceof Array)){pois=[pois];}}
catch(e1){return;}
this.processResults(pois);},processResults:function(pois){if(!this.validResults){return;}
var poi,marker,markerImage;for(var i=0;i<pois.length;++i){poi=pois[i];if(!this.isOnTheMap(poi)){marker=new SAPO.Maps.Marker(new OpenLayers.LonLat(poi.Longitude,poi.Latitude),{popupAnchor:new OpenLayers.Pixel(0,-18)},{markerImage:"http://js.sapo.pt/Assets/Images/Meteo/"+poi.DetailXml.Details.WeatherForecast.CurrentWeather.WeatherCode+".png",markerAnchor:new OpenLayers.Pixel(-30,-22),size:new OpenLayers.Size(60,53)});marker.poi=poi;marker.registerEvent("click",this,this.showWeatherForMarker);marker.registerEvent("mouseover",this,function(){map.div.style.cursor="pointer";});marker.registerEvent("mouseout",this,function(){map.div.style.cursor="";});this.markersObject.addMarker(marker);}}
if(this.stateToRecover){this.setState();}},showWeatherForMarker:function(marker){if(marker.hasOpenedPopup()){return;}
SapoMapsApp.closeInfoWindows();this.selectedWeather=marker;var html=this.getHtmlForWeatherPopup(marker.poi);marker.openPopup(html,{borders:SapoMapsApp.borders});SapoMapsApp.Analytics.track("Layers","Weather","AbrirPin");},getHtmlForWeatherPopup:function(poi){var div_wrapper=document.createElement("div");var h1_title=document.createElement("h1");var div_footer=document.createElement("div");var p_credits=document.createElement("p");div_wrapper.className="weather_wrapper";h1_title.className="title";div_footer.className="footer";p_credits.className="credits";h1_title.innerHTML=poi.Name;div_wrapper.appendChild(h1_title);p_credits.innerHTML="Dados fornecidos por AccuWeather";var days=poi.DetailXml.Details.WeatherForecast.Days.Day;var div_dayWrapper,div_dayDay,div_dayImageWrapper,img_dayImage,div_dayDescription,div_dayTemperatures,span_dayMaxTemperature,span_dayMinTemperature;for(var i=0;i<4;++i){div_dayWrapper=document.createElement("div");div_dayDay=document.createElement("div");div_dayImageWrapper=document.createElement("div");img_dayImage=new Image();div_dayDescription=document.createElement("div");div_dayTemperatures=document.createElement("div");span_dayMaxTemperature=document.createElement("span");span_dayMinTemperature=document.createElement("span");div_dayWrapper.className="weather_dayWrapper";div_dayDay.className="weather_dayDay";div_dayImageWrapper.className="weather_dayImageWrapper";img_dayImage.className="weather_dayImage";span_dayMinTemperature.className="weather_minTemperature";span_dayMaxTemperature.className="weather_maxTemperature";div_dayDescription.className="weather_dayDescription";img_dayImage.onload=function(){this.width="60";this.height="53";this.style.visibility="visible";};if(i===0){div_dayDay.innerHTML="Hoje";}
else{if(i===1){div_dayDay.innerHTML="Amanh&atilde;";}
else{if(days[i].Name==="Sabado"){div_dayDay.innerHTML="S&aacute;bado";}
else{div_dayDay.innerHTML=days[i].Name.replace(/\*/,"&ordf;");}}}
img_dayImage.src="http://js.sapo.pt/Assets/Images/Meteo/"+days[i].WeatherCode+".png";div_dayDescription.innerHTML=days[i].Description;span_dayMinTemperature.innerHTML=days[i].Low+"&ordm;C";span_dayMaxTemperature.innerHTML=days[i].High+"&ordm;C";div_dayTemperatures.appendChild(span_dayMinTemperature);div_dayTemperatures.appendChild(span_dayMaxTemperature);div_dayImageWrapper.appendChild(img_dayImage);div_dayWrapper.appendChild(div_dayDay);div_dayWrapper.appendChild(div_dayImageWrapper);div_dayWrapper.appendChild(div_dayTemperatures);div_dayWrapper.appendChild(div_dayDescription);div_wrapper.appendChild(div_dayWrapper);}
div_footer.appendChild(p_credits);div_wrapper.appendChild(div_footer);return div_wrapper;},isOnTheMap:function(poi){var markersOnTheMap=this.markersObject.getMarkers();var lonlat=null;for(var i=0;i<markersOnTheMap.length;++i){lonlat=markersOnTheMap[i].getLonLat();if(lonlat.lat.toFixed(4)===Number(poi.Latitude).toFixed(4)&&lonlat.lon.toFixed(4)===Number(poi.Longitude).toFixed(4)){return true;}}
return false;},removeMarkers:function(all){if(all){this.map.removeMarkers(this.markersObject);this.markersObject=new SAPO.Maps.Markers("SAPOMapsWeather");this.map.addMarkers(this.markersObject);}
else{var markers=this.markersObject.getMarkers();var marker=null;for(var i=0;i<markers.length;++i){marker=markers[i];if(this.map.getBounds().containsLonLat(marker.getLonLat())){continue;}
if(marker.hasOpenedPopup()){continue;}
else{marker.unRegisterEvent('click',this,this.showWeatherForMarker);this.markersObject.removeMarker(marker);marker.poi=null;}}}},cancelRequests:function(){this.requestInProgress=false;this.validResults=false;}};
SapoMapsApp.Saber={url:{baseUrl:'http://services.sapo.pt/Maps/GetPOIByBoundingBoxJSON?',latitude1:null,longitude1:null,latitude2:null,longitude2:null,fl:'POIId,Latitude,Longitude,CountryId,Detail',categoryId:5,matchlevelId:0,trustlevelId:75,pageNumber:1,recordsPerPage:50,withMedia:true},active:false,map:null,selectedArticle:null,stateToRecover:null,markersObject:null,requester:null,markersStyle:null,markersOptions:null,oldZoom:null,requestInProgress:false,validResults:true,initialize:function(map){this.map=map;this.markersStyle={markerImage:"http://imgs.sapo.pt/fotos_gis/Saber/saber.png",markerAnchor:new OpenLayers.Pixel(-10,-10),size:new OpenLayers.Size(22,23)};this.markersOptions={popupAnchor:new OpenLayers.Pixel(0,-10)};},activate:function(){if(this.active){return;}
this.requester=SAPO.Maps.Request.prototype.getRequester();this.markersObject=new SAPO.Maps.Markers("SAPOMapsSaber");this.map.addMarkers(this.markersObject);this.registerEvents();this.active=true;this.refresh();try{SapoMapsApp.Analytics.track("Layers","Saber","ActivarLayer");}
catch(e){}},deactivate:function(){if(!this.active){return;}
this.map.removeMarkers(this.markersObject);this.requester=null;this.markersObject=null;this.unregisterEvents();this.active=false;},isActive:function(){return this.active;},getState:function(){if(!this.selectedArticle){return"";}
return"saber,"+this.selectedArticle.poi.POIId;},setStateAfterLoad:function(id){this.stateToRecover=id.split(",")[1];},setState:function(){var url="http://services.sapo.pt/GIS/GetPOIByIdJSON?poiId="+this.stateToRecover;var tmpRequesterObj=SAPO.Maps.Request.prototype.getRequester();var reqId=tmpRequesterObj.request(url,{timeout:4,onComplete:function(obj){try{var poi=obj.GetPOIByIdResponse.GetPOIByIdResult;}
catch(e){return;}
if(!this.isOnTheMap(poi)){var marker=new SAPO.Maps.Marker(new OpenLayers.LonLat(poi.Longitude,poi.Latitude),this.markersOptions,this.markersStyle);marker.poi=poi;marker.registerEvent("click",this,this.showArticleForMarker);marker.registerEvent("mouseover",this,function(){map.div.style.cursor="pointer";});marker.registerEvent("mouseout",this,function(){map.div.style.cursor="";});this.markersObject.addMarker(marker);this.showArticleForMarker(marker);}
else{var markersOnTheMap=this.markersObject.getMarkers();var lonlat=null;for(var i=0;i<markersOnTheMap.length;++i){lonlat=markersOnTheMap[i].getLonLat();if(lonlat.lat.toFixed(4)===Number(poi.Latitude).toFixed(4)&&lonlat.lon.toFixed(4)===Number(poi.Longitude).toFixed(4)){markersOnTheMap[i].poi=poi;this.showArticleForMarker(markersOnTheMap[i]);return;}}}}.bindObj(this)});},registerEvents:function(){this.map.events.register("moveend",this,this.refresh);},unregisterEvents:function(){this.map.events.unregister("moveend",this,this.refresh);},closeOpenedPopup:function(){if(this.selectedArticle){this.selectedArticle.closePopup();this.selectedArticle=null;}},refresh:function(){if(!this.active){return;}
if(this.requestsInProgresss){this.cancelRequests();}
if(this.map.getZoom()<SapoMapsApp.Layers.services.layers.saber.minZoom){this.removeMarkers(true);return;}
this.removeMarkers(this.oldZoom&&this.oldZoom>this.map.getZoom());this.oldZoom=this.map.getZoom();var zoom=this.map.getZoom();this.getPois();this.validResults=true;this.requestsInProgresss=true;},getPois:function(){var bounds=this.map.getBounds();this.url.latitude1=bounds.top.toFixed(6);this.url.longitude1=bounds.right.toFixed(6);this.url.latitude2=bounds.bottom.toFixed(6);this.url.longitude2=bounds.left.toFixed(6);var url=SapoMapsApp.getUrl(this.url);this.requester=SAPO.Maps.Request.prototype.getRequester();var reqID=this.requester.request(url,{timeout:4,onComplete:this.resultsAvailable.bindObj(this)});},resultsAvailableGrided:function(obj){this.requestsInProgresss=false;var pois;try{pois=obj.GetPOIByBoundingBoxGridedResponse.GetPOIByBoundingBoxGridedResult.POI?obj.GetPOIByBoundingBoxGridedResponse.GetPOIByBoundingBoxGridedResult.POI:[obj.GetPOIByBoundingBoxGridedResponse.GetPOIByBoundingBoxGridedResult];}
catch(e1){return;}
this.processResults(pois);},resultsAvailable:function(obj){var pois;try{pois=obj.Response.Result.POI?obj.Response.Result.POI:[obj.Response.Result];if(!(pois instanceof Array)){pois=[pois];}}
catch(e1){return;}
this.processResults(pois);},processResults:function(pois){if(!this.validResults){return;}
var poi,marker,markerImage;for(var i=0;i<pois.length;++i){poi=pois[i];if(!this.filterPoi(poi)){continue;}
if(!this.isOnTheMap(poi)){marker=new SAPO.Maps.Marker(new OpenLayers.LonLat(poi.Longitude,poi.Latitude),this.markersOptions,this.markersStyle);marker.POIId=poi.POIId;marker.registerEvent("click",this,this.showArticleForMarker);marker.registerEvent("mouseover",this,function(){map.div.style.cursor="pointer";});marker.registerEvent("mouseout",this,function(){map.div.style.cursor="";});this.markersObject.addMarker(marker);}}
if(this.stateToRecover){this.setState();this.stateToRecover=null;}},filterPoi:function(poi){if(poi.CountryId==="PT"&&poi.DetailXml.Details.Saber.Abstract){return true;}
return false;},showArticleForMarker:function(marker){function openPopup(){if(marker.hasOpenedPopup()){return;}
var html=this.getHtmlForArticlePopup(marker.poi);marker.openPopup(html,{borders:SapoMapsApp.borders});}
function poiArrived(obj){marker.poi=obj.GetPOIByIdResponse.GetPOIByIdResult;if(this.selectedArticle===marker){openPopup.apply(this);}}
try{SapoMapsApp.Analytics.track("Layers","Saber","AbrirPin");}
catch(e){}
SapoMapsApp.closeInfoWindows();this.selectedArticle=marker;if(marker.poi){openPopup.apply(this);}
else{SapoMapsApp.getPOI(marker.POIId,this.requester,{timeout:4,onComplete:poiArrived.bindObj(this)});}},getHtmlForArticlePopup:function(poi){var div_wrapper=document.createElement("div");var h1_title=document.createElement("h1");var div_imageWrapper=document.createElement("div");var img_image=document.createElement("img");var p_abstract=document.createElement("p");var div_link=document.createElement("div");var a_link=document.createElement("a");div_wrapper.className="saber_wrapper";h1_title.className="saber_title";div_imageWrapper.className="saber_imageWrapper";img_image.className="saber_image";div_link.className="saber_link";h1_title.innerHTML=poi.Name;p_abstract.innerHTML=poi.DetailXml.Details.Saber.Abstract;a_link.target="_blank";a_link.href=poi.URL;a_link.innerHTML="Ver este artigo no SAPO Saber";div_wrapper.appendChild(h1_title);if(poi.DetailXml.Details.Saber.Image){img_image.onload=function(){var originalWidth=img_image.naturalWidth?img_image.naturalWidth:img_image.width;var originalHeight=img_image.naturalHeight?img_image.naturalHeight:img_image.height;if(originalHeight<=200&&originalWidth<=200){div_imageWrapper.style.width=originalWidth+"px";div_imageWrapper.style.height=originalHeight+"px";div_imageWrapper.style.margin="10px";return;}
var adjustedWidth,adjustedHeight;if(originalHeight>originalWidth){adjustedHeight=200;adjustedWidth=Math.round((adjustedHeight*originalWidth)/originalHeight);}
if(originalWidth>originalHeight){adjustedWidth=200;adjustedHeight=Math.round((adjustedWidth*originalHeight)/originalWidth);}
if(adjustedWidth>0&&adjustedHeight>0){img_image.width=adjustedWidth;img_image.height=adjustedHeight;div_imageWrapper.style.width=adjustedWidth+"px";div_imageWrapper.style.height=adjustedHeight+"px";div_imageWrapper.style.margin="10px";}}.bindObj(this);img_image.src=poi.DetailXml.Details.Saber.Image.replace(/\+/g,"_");div_imageWrapper.appendChild(img_image);div_wrapper.appendChild(div_imageWrapper);}
div_wrapper.appendChild(p_abstract);div_link.appendChild(a_link);div_wrapper.appendChild(div_link);return div_wrapper;},isOnTheMap:function(poi){var markersOnTheMap=this.markersObject.getMarkers();var lonlat=null;for(var i=0;i<markersOnTheMap.length;++i){lonlat=markersOnTheMap[i].getLonLat();if(lonlat.lat.toFixed(4)===Number(poi.Latitude).toFixed(4)&&lonlat.lon.toFixed(4)===Number(poi.Longitude).toFixed(4)){return true;}}
return false;},removeMarkers:function(all){var markers=this.markersObject.getMarkers();var marker=null;for(var i=0;i<markers.length;++i){marker=markers[i];if(!all&&this.map.getBounds().containsLonLat(marker.getLonLat())){continue;}
if(!all&&marker.hasOpenedPopup()){continue;}
else{marker.unRegisterEvent("click",this,this.showArticleForMarker);this.markersObject.removeMarker(marker);marker.poi=null;marker.POIId=null;}}},cancelRequests:function(){this.requestInProgress=false;this.validResults=false;}};
SapoMapsApp.Photos={url:{baseUrl:'http://services.sapo.pt/Maps/GetPOIByBoundingBoxJSON?',latitude1:null,longitude1:null,latitude2:null,longitude2:null,fl:'POIId, Latitude, Longitude',categoryId:202,matchlevelId:0,trustlevelId:0,pageNumber:1,recordsPerPage:50,withMedia:true},active:false,map:null,selectedPhoto:null,stateToRecover:null,markersObject:null,requester:null,markersStyle:null,markersOptions:null,initialize:function(map){this.map=map;this.markersStyle={markerImage:"http://imgs.sapo.pt/fotos_gis/Photos/icon.png",markerAnchor:new OpenLayers.Pixel(-10,-10),size:new OpenLayers.Size(22,23)};this.markersOptions={popupAnchor:new OpenLayers.Pixel(0,-10)};},activate:function(){if(this.active){return;}
this.requester=SAPO.Maps.Request.prototype.getRequester();this.markersObject=new SAPO.Maps.Markers("SAPOMapsPhotos");this.map.addMarkers(this.markersObject);this.registerEvents();this.active=true;this.refresh();},deactivate:function(){if(!this.active){return;}
this.map.removeMarkers(this.markersObject);this.requester=null;this.markersObject=null;this.unregisterEvents();this.active=false;},isActive:function(){return this.active;},getState:function(){if(!this.selectedPhoto){return"";}
return"photos,"+this.selectedPhoto.poi.POIId;},setStateAfterLoad:function(id){this.stateToRecover=id.split(",")[1];},setState:function(){var url="http://services.sapo.pt/GIS/GetPOIByIdJSON?poiId="+this.stateToRecover;var tmpRequester=SAPO.Maps.Request.prototype.getRequester();var reqId=tmpRequester.request(url,{timeout:4,onComplete:function(obj){try{var poi=obj.GetPOIByIdResponse.GetPOIByIdResult;}
catch(e){return;}
if(!this.isOnTheMap(poi)){var marker=new SAPO.Maps.Marker(new OpenLayers.LonLat(poi.Longitude,poi.Latitude),this.markersOptions,this.markersStyle);marker.poi=poi;marker.registerEvent("click",this,this.showPhotoForMarker);marker.registerEvent("mouseover",this,function(){map.div.style.cursor="pointer";});marker.registerEvent("mouseout",this,function(){map.div.style.cursor="";});this.markersObject.addMarker(marker);this.showPhotoForMarker(marker);}
else{var markersOnTheMap=this.markersObject.getMarkers();var lonlat=null;for(var i=0;i<markersOnTheMap.length;++i){lonlat=markersOnTheMap[i].getLonLat();if(lonlat.lat.toFixed(4)===Number(poi.Latitude).toFixed(4)&&lonlat.lon.toFixed(4)===Number(poi.Longitude).toFixed(4)){markersOnTheMap[i].poi=poi;this.showPhotoForMarker(markersOnTheMap[i]);return;}}}}.bindObj(this)});},registerEvents:function(){this.map.events.register("moveend",this,this.refresh);},unregisterEvents:function(){this.map.events.unregister("moveend",this,this.refresh);},closeOpenedPopup:function(){if(this.selectedPhoto){this.selectedPhoto.closePopup();this.selectedPhoto=null;}},refresh:function(){if(!this.active){return;}
if(this.map.getZoom()<SapoMapsApp.Layers.services.layers.saber.minZoom){this.removeMarkers(true);return;}
this.removeMarkers();this.oldZoom=this.map.getZoom();var zoom=this.map.getZoom();this.getPois();},getPois:function(){var bounds=this.map.getBounds();this.url.latitude1=bounds.top.toFixed(6);this.url.longitude1=bounds.right.toFixed(6);this.url.latitude2=bounds.bottom.toFixed(6);this.url.longitude2=bounds.left.toFixed(6);var url=SapoMapsApp.getUrl(this.url);this.requester=SAPO.Maps.Request.prototype.getRequester();var reqID=this.requester.request(url,{timeout:4,onComplete:this.resultsAvailable.bindObj(this)});},resultsAvailable:function(obj){var pois;try{pois=obj.Response.Result.POI?obj.Response.Result.POI:[obj.Response.Result];if(!(pois instanceof Array)){pois=[pois];}}
catch(e1){return;}
this.processResults(pois);},processResults:function(pois){var poi,marker,markerImage;for(var i=pois.length-1;i>=0;--i){poi=pois[i];if(!this.filterPoi(poi)){continue;}
if(!this.isOnTheMap(poi)){marker=new SAPO.Maps.Marker(new OpenLayers.LonLat(poi.Longitude,poi.Latitude),this.markersOptions,this.markersStyle);marker.POIId=poi.POIId;marker.registerEvent("click",this,this.showPhotoForMarker);marker.registerEvent("mouseover",this,function(){map.div.style.cursor="pointer";});marker.registerEvent("mouseout",this,function(){map.div.style.cursor="";});this.markersObject.addMarker(marker);}}
if(this.stateToRecover){this.setState();this.stateToRecover=null;}},filterPoi:function(poi){return true;},showPhotoForMarker:function(marker){if(marker.hasOpenedPopup()){return;}
SapoMapsApp.closeInfoWindows();this.selectedPhoto=marker;function openPopup(obj){marker.poi=obj.GetPOIByIdResponse.GetPOIByIdResult;if(this.selectedPhoto===marker){marker.openPopup(this.getHtmlForPhotoPopup(marker),{borders:SapoMapsApp.borders});}}
if(marker.poi){marker.openPopup(this.getHtmlForPhotoPopup(marker),{borders:SapoMapsApp.borders});}else{SapoMapsApp.getPOI(marker.POIId,this.requester,{timeout:4,onComplete:openPopup.bindObj(this)});}
try{SapoMapsApp.Analytics.track("Layers","Fotos","AbrirPin");}
catch(e){}},getHtmlForPhotoPopup:function(marker){var isLoaded=false;var toShow=true;var poi=marker.poi;var div_wrapper=document.createElement("div");var div_loader=document.createElement("div");var div_imgWrapper=document.createElement("div");var div_imgArea=document.createElement("div");var img_loader=document.createElement("img");var img_image=document.createElement("img");var h1_title=document.createElement("h1");var p_description=document.createElement("p");var div_link=document.createElement("div");var a_link=document.createElement("a");div_wrapper.className="SapoPhotos";div_loader.className="Loader";div_imgArea.className="ImageArea";div_imgWrapper.className="ImageWrapper";h1_title.className="Title";p_description.className="Description";div_link.className="Link";img_image.onload=function(){if(!toShow){return;}
isLoaded=true;div_loader.style.display="none";div_imgArea.style.display="block";var width=this.naturalWidth?this.naturalWidth:this.width;var height=this.naturalHeight?this.naturalHeight:this.height;var adjustedWidth=width,adjustedHeight=height;if(width>400||height>400){if(height>width){adjustedHeight=400;adjustedWidth=Math.round((adjustedHeight*width)/height);}
if(width>height){adjustedWidth=400;adjustedHeight=Math.round((adjustedWidth*height)/width);}}
this.width=adjustedWidth;this.height=adjustedHeight;p_description.style.width=this.width>300?(this.width+"px"):"300px";if(marker.popup){marker.popup.contentUpdated();}};img_loader.width="111";img_loader.height="82";img_loader.src="http://js.sapo.pt/Assets/Maps/Images/bigwheel_1.gif";img_image.src=poi.DetailXml.Details.Photo.DirectUrl;h1_title.innerHTML=poi.Name;a_link.href=poi.URL;a_link.target="_blank";a_link.innerHTML="Veja esta fotografia no SAPO fotos";div_loader.appendChild(img_loader);div_imgArea.appendChild(h1_title);div_imgWrapper.appendChild(img_image);div_imgArea.appendChild(div_imgWrapper);if(poi.Description){p_description.innerHTML=poi.Description;div_imgArea.appendChild(p_description);}
div_link.appendChild(a_link);div_imgArea.appendChild(div_link);div_wrapper.appendChild(div_loader);div_wrapper.appendChild(div_imgArea);window.setTimeout(function(){if(!isLoaded){div_imgArea.style.display="none";toShow=false;div_loader.innerHTML="";div_loader.style.width="300px";div_loader.style.height="auto";SAPO.Maps.Utils.displayMessageHTML(div_loader,"Lamentamos mas de momento não é possível apresentar a fotografia.","","",SAPO.Maps.Utils.MessageType.WARNING);if(marker.popup){marker.popup.contentUpdated();}}},3000);return div_wrapper;},isOnTheMap:function(poi){if(!this.markersObject){return false;}
var markersOnTheMap=this.markersObject.getMarkers(),lonlat=false;for(var i=0,len=markersOnTheMap.length;i<len;++i){lonlat=markersOnTheMap[i].getLonLat();if(lonlat.lat.toFixed(4)===Number(poi.Latitude).toFixed(4)&&lonlat.lon.toFixed(4)===Number(poi.Longitude).toFixed(4)){return true;}}
return false;},removeMarkers:function(all){var markers=this.markersObject.getMarkers(),marker=null;for(var i=markers.length-1;i>=0;--i){marker=markers[i];if(!all&&this.map.getBounds().containsLonLat(marker.getLonLat())){continue;}
if(!all&&marker.hasOpenedPopup()){continue;}
else{marker.unRegisterEvent("click",this,this.showArticleForMarker);this.markersObject.removeMarker(marker);marker.poi=null;marker.POIId=null;}}}};
SapoMapsApp.Videos={url:{baseUrl:'http://services.sapo.pt/Maps/GetPOIByBoundingBoxJSON?',latitude1:null,longitude1:null,latitude2:null,longitude2:null,fl:'POIId,Latitude,Longitude,Detail',categoryId:203,matchlevelId:0,trustlevelId:0,pageNumber:1,recordsPerPage:50,withMedia:true},active:false,map:null,selectedVideo:null,stateToRecover:null,markersObject:null,request:null,markersStyle:null,markersOptions:null,initialize:function(map){this.map=map;this.markersStyle={markerImage:"http://imgs.sapo.pt/fotos_gis/Videos/icon.png",markerAnchor:new OpenLayers.Pixel(-10,-10),size:new OpenLayers.Size(22,24)};this.markersOptions={popupAnchor:new OpenLayers.Pixel(0,-10)};},activate:function(){if(this.active){return;}
this.requester=SAPO.Maps.Request.prototype.getRequester();this.markersObject=new SAPO.Maps.Markers("SAPOMapsVideos");this.map.addMarkers(this.markersObject);this.registerEvents();this.active=true;this.refresh();},deactivate:function(){if(!this.active){return;}
this.map.removeMarkers(this.markersObject);this.requester=null;this.markersObject=null;this.unregisterEvents();this.active=false;},isActive:function(){return this.active;},getState:function(){if(!this.selectedVideo){return"";}
return"videos,"+this.selectedVideo.poi.POIId;},setStateAfterLoad:function(id){this.stateToRecover=id.split(",")[1];},setState:function(){var url="http://services.sapo.pt/GIS/GetPOIByIdJSON?poiId="+this.stateToRecover;var tmpRequesterObj=SAPO.Maps.Request.prototype.getRequester();tmpRequesterObj.request(url,{timeout:4,onComplete:function(obj){var poi;try{poi=obj.GetPOIByIdResponse.GetPOIByIdResult;}
catch(e){return;}
if(!this.isOnTheMap(poi)){var marker=new SAPO.Maps.Marker(new OpenLayers.LonLat(poi.Longitude,poi.Latitude),this.markersOptions,this.markersStyle);marker.poi=poi;marker.registerEvent("click",this,this.showVideoForMarker);marker.registerEvent("mouseover",this,function(){map.div.style.cursor="pointer";});marker.registerEvent("mouseout",this,function(){map.div.style.cursor="";});this.markersObject.addMarker(marker);this.showVideoForMarker(marker);}
else{var markersOnTheMap=this.markersObject.getMarkers();var lonlat=null;for(var i=0;i<markersOnTheMap.length;++i){lonlat=markersOnTheMap[i].getLonLat();if(lonlat.lat.toFixed(4)===Number(poi.Latitude).toFixed(4)&&lonlat.lon.toFixed(4)===Number(poi.Longitude).toFixed(4)){markersOnTheMap[i].poi=poi;this.showVideoForMarker(markersOnTheMap[i]);return;}}}}.bindObj(this)});},registerEvents:function(){this.map.events.register("moveend",this,this.refresh);},unregisterEvents:function(){this.map.events.unregister("moveend",this,this.refresh);},closeOpenedPopup:function(){if(this.selectedVideo){this.selectedVideo.closePopup();this.selectedVideo=null;}},refresh:function(){if(!this.active){return;}
if(this.map.getZoom()<SapoMapsApp.Layers.services.layers.saber.minZoom){this.removeMarkers(true);return;}
this.removeMarkers();this.oldZoom=this.map.getZoom();var zoom=this.map.getZoom();this.getPois();},getPois:function(){var bounds=this.map.getBounds();this.url.latitude1=bounds.top.toFixed(6);this.url.longitude1=bounds.right.toFixed(6);this.url.latitude2=bounds.bottom.toFixed(6);this.url.longitude2=bounds.left.toFixed(6);var url=SapoMapsApp.getUrl(this.url);this.requester=SAPO.Maps.Request.prototype.getRequester();var reqID=this.requester.request(url,{timeout:4,onComplete:this.resultsAvailable.bindObj(this)});},resultsAvailable:function(obj){var pois;try{pois=obj.Response.Result.POI?obj.Response.Result.POI:[obj.Response.Result];if(!(pois instanceof Array)){pois=[pois];}}
catch(e1){return;}
this.processResults(pois);},processResults:function(pois){var poi,marker,markerImage;for(var i=pois.length-1;i>=0;--i){poi=pois[i];if(!this.filterPoi(poi)){continue;}
if(!this.isOnTheMap(poi)){marker=new SAPO.Maps.Marker(new OpenLayers.LonLat(poi.Longitude,poi.Latitude),this.markersOptions,this.markersStyle);marker.POIId=poi.POIId;marker.registerEvent("click",this,this.showVideoForMarker);marker.registerEvent("mouseover",this,function(){map.div.style.cursor="pointer";});marker.registerEvent("mouseout",this,function(){map.div.style.cursor="";});this.markersObject.addMarker(marker);}}
if(this.stateToRecover){this.setState();this.stateToRecover=null;}},filterPoi:function(poi){if(poi.DetailXml.Details.Video.M18==="false"){return true;}
return false;},showVideoForMarker:function(marker){function openPopup(){if(marker.hasOpenedPopup()){return;}
var html=this.getHtmlForVideoPopup(marker.poi);marker.openPopup(html,{borders:SapoMapsApp.borders});}
function poiArrived(obj){marker.poi=obj.GetPOIByIdResponse.GetPOIByIdResult;if(this.selectedVideo===marker){openPopup.apply(this);}}
SapoMapsApp.closeInfoWindows();this.selectedVideo=marker;try{SapoMapsApp.Analytics.track("Layers","Videos","AbrirPin");}
catch(e){}
if(marker.poi){openPopup.apply(this);}else{SapoMapsApp.getPOI(marker.POIId,this.requester,{timeout:4,onComplete:poiArrived.bindObj(this)});}},getHtmlForVideoPopup:function(poi){var url=poi.DetailXml.Details.Video.DirectUrl.replace(/http:\/\/mobile./,"http://");url=url.replace(/http:\/\/rd3./,"http://");var div_wrapper=document.createElement("div");var h1_title=document.createElement("h1");var p_description=document.createElement("p");var div_video=document.createElement("div");var div_link=document.createElement("div");var a_link=document.createElement("a");div_wrapper.className="SapoVideos";h1_title.className="Title";div_video.className="Video";p_description.className="Description";div_link.className="Link";h1_title.innerHTML=poi.Name;p_description.innerHTML=poi.Description;div_video.innerHTML="<embed src=\"http://rd3.videos.sapo.pt/play?file="+url+"\" type=\"application/x-shockwave-flash\" width=\"300\" height=\"261\" allowFullScreen=\"true\"></embed>";a_link.innerHTML="Veja este vídeo no SAPO videos";a_link.href=poi.URL.replace(/http:\/\/mobile./,"http://");a_link.target="_blank";div_link.appendChild(a_link);div_wrapper.appendChild(h1_title);div_wrapper.appendChild(div_video);div_wrapper.appendChild(p_description);div_wrapper.appendChild(div_link);return div_wrapper;},isOnTheMap:function(poi){var markersOnTheMap=this.markersObject.getMarkers();var lonlat=null;for(var i=0;i<markersOnTheMap.length;++i){lonlat=markersOnTheMap[i].getLonLat();if(lonlat.lat.toFixed(4)===Number(poi.Latitude).toFixed(4)&&lonlat.lon.toFixed(4)===Number(poi.Longitude).toFixed(4)){return true;}}
return false;},removeMarkers:function(all){var markers=this.markersObject.getMarkers();var marker=null;for(var i=0;i<markers.length;++i){marker=markers[i];if(!all&&this.map.getBounds().containsLonLat(marker.getLonLat())){continue;}
if(!all&&marker.hasOpenedPopup()){continue;}
else{marker.unRegisterEvent("click",this,this.showArticleForMarker);this.markersObject.removeMarker(marker);marker.POIId=null;marker.poi=null;}}}};
SapoMapsApp.News={active:false,map:null,news:{},selectedNew:null,districts:{"01":{name:"Aveiro",lat:40.64392,lon:-8.6422205},"02":{name:"Beja",lat:38.0149956,lon:-7.86307573},"03":{name:"Braga",lat:41.55065,lon:-8.425066},"04":{name:"Bragança",lat:41.80548,lon:-6.75527573},"05":{name:"Castelo Branco",lat:39.82458,lon:-7.49288845},"06":{name:"Coimbra",lat:40.2100563,lon:-8.427385},"07":{name:"Évora",lat:38.5715637,lon:-7.90875864},"08":{name:"Faro",lat:37.0180321,lon:-7.93370152},"09":{name:"Guarda",lat:40.5383,lon:-7.26700926},"10":{name:"Leiria",lat:39.74456,lon:-8.808894},"11":{name:"Lisboa",lat:38.7115479,lon:-9.13774},"12":{name:"Portalegre",lat:39.2923355,lon:-7.430914},"13":{name:"Porto",lat:41.15804,lon:-8.629256},"14":{name:"Santarém",lat:39.23557,lon:-8.683809},"15":{name:"Setúbal",lat:38.5271339,lon:-8.888036},"16":{name:"Viana do Castelo",lat:41.6926041,lon:-8.828435},"17":{name:"Vila Real",lat:41.2980461,lon:-7.753213},"18":{name:"Viseu",lat:40.6573257,lon:-7.912638},"31":{name:"Ilha da Madeira",lat:32.6474724,lon:-16.9059067},"32":{name:"Ilha de Porto Santo",lat:33.0596466,lon:-16.3336163},"41":{name:"Ilha de Santa Maria",lat:36.97227,lon:-25.099371},"42":{name:"Ilha de São Miguel",lat:37.7381,lon:-25.66962},"43":{name:"Ilha Terceira",lat:38.72379,lon:-27.2111435},"44":{name:"Ilha Graciosa",lat:39.0522079,lon:-28.01019},"45":{name:"Ilha de São Jorge",lat:38.63713,lon:-28.0281487},"46":{name:"Ilha do Pico",lat:38.46935,lon:-28.3325367},"47":{name:"Ilha do Faial",lat:38.57811,lon:-28.7002583},"48":{name:"Ilha das Flores",lat:39.44274,lon:-31.2030678},"49":{name:"Ilha do Corvo",lat:39.6999359,lon:-31.1058865}},municipalities:null,markersObject:null,requester:null,markersStyle:null,markersOptions:null,zoom:null,oldZoom:null,initialize:function(map){this.map=map;this.markersStyle={markerImage:"http://imgs.sapo.pt/fotos_gis/News/icon.png",markerAnchor:new OpenLayers.Pixel(-10,-10),size:new OpenLayers.Size(22,23)};this.markersOptions={popupAnchor:new OpenLayers.Pixel(0,-10)};},activate:function(){if(this.active){return;}
this.requester=SAPO.Maps.Request.prototype.getRequester();this.markersObject=new SAPO.Maps.Markers("SAPOMapsNews");this.map.addMarkers(this.markersObject);this.registerEvents();this.active=true;this.refresh();},deactivate:function(){if(!this.active){return;}
this.map.removeMarkers(this.markersObject);this.requester=null;this.markersObject=null;this.selectedNew=null;this.news={};this.unregisterEvents();this.active=false;},isActive:function(){return this.active;},getState:function(){if(!this.selectedNew){return"";}
return"news,"+(this.selectedNew.district?this.selectedNew.district.id:this.selectedNew.municipality.id);},setStateAfterLoad:function(id){this.stateToRecover=id.split(",")[1];},setState:function(){var markers=this.markersObject.getMarkers();if(markers.length===0){return;}
for(var e in markers){if((markers[e].district&&markers[e].district.id===this.stateToRecover)||(markers[e].municipality&&markers[e].municipality.id===this.stateToRecover)){this.getNewsForMarker(markers[e]);this.stateToRecover=null;return;}}},registerEvents:function(){this.map.events.register("moveend",this,this.refresh);},unregisterEvents:function(){this.map.events.unregister("moveend",this,this.refresh);},closeOpenedPopup:function(){if(this.selectedNew){this.selectedNew.closePopup();this.selectedNew=null;}},refresh:function(){if(!this.active){return;}
if(this.map.getZoom()<SapoMapsApp.Layers.services.layers.news.minZoom){this.removeMarkers(true);return;}
this.removeMarkers();this.oldZoom=this.zoom;this.zoom=this.map.getZoom();if(this.zoom<10){this.removeMarkers(this.oldZoom&&this.oldZoom>=10);this.addDistrictMarkers();}
else{this.addMunicipalitiesMarkers();}
if(this.stateToRecover){this.setState();}},addDistrictMarkers:function(){var district=null,marker=null;for(var e in this.districts){district=this.districts[e];marker=new SAPO.Maps.Marker(new OpenLayers.LonLat(district.lon,district.lat),this.markersOptions,this.markersStyle);marker.district={id:e,name:district.name};marker.registerEvent('click',this,this.getNewsForMarker);marker.registerEvent("mouseover",this,function(){map.div.style.cursor="pointer";});marker.registerEvent("mouseout",this,function(){map.div.style.cursor="";});this.markersObject.addMarker(marker);}},addMunicipalitiesMarkers:function(){if(this.municipalities){var bounds=this.map.getBounds();var lonlat=new OpenLayers.LonLat(0,0);var marker=null;for(var e in this.municipalities){lonlat.lon=this.municipalities[e].lon;lonlat.lat=this.municipalities[e].lat;if(bounds.containsLonLat(lonlat)){marker=new SAPO.Maps.Marker(new OpenLayers.LonLat(lonlat.lon,lonlat.lat),this.markersOptions,this.markersStyle);marker.municipality={id:e,name:this.municipalities[e].name};marker.registerEvent('click',this,this.getNewsForMarker);marker.registerEvent("mouseover",this,function(){map.div.style.cursor="pointer";});marker.registerEvent("mouseout",this,function(){map.div.style.cursor="";});this.markersObject.addMarker(marker);}}}
else{var url="http://services.sapo.pt/GIS/GetMunicipalitiesSortedByIdJSON?includeParishes=0";this.requester.request(url,{timeout:4,onComplete:function(obj){this.municipalities={};try{var data=obj.GetMunicipalitiesSortedByIdResponse.GetMunicipalitiesSortedByIdResult.Municipality;}
catch(e){return;}
for(var i=0;i<data.length;++i){this.municipalities[data[i].MunicipalityId]={name:data[i].MunicipalityName,lat:data[i].Latitude,lon:data[i].Longitude};}
this.addMunicipalitiesMarkers();if(this.stateToRecover){this.setState();}}.bindObj(this)});}},getNewsForMarker:function(marker){if(marker.hasOpenedPopup()){return;}
SapoMapsApp.closeInfoWindows();this.selectedNew=marker;marker.registerEvent("popupclosed",this,this.closeOpenedPopup);var url=null;var reqID=null;if(marker.district){url="http://services.sapo.pt/GIS/GetPOIByDistrictIdAndCategoryIdJSON?districtId="+marker.district.id+"&categoryId=191&matchlevelId=0&trustlevelId=0&pageNumber=1&recordsPerPage=10";reqID=this.requester.request(url,{timeout:4,onComplete:function(obj){var news;try{news=obj.GetPOIByDistrictIdAndCategoryIdResponse.GetPOIByDistrictIdAndCategoryIdResult.POI.length?obj.GetPOIByDistrictIdAndCategoryIdResponse.GetPOIByDistrictIdAndCategoryIdResult.POI:[obj.GetPOIByDistrictIdAndCategoryIdResponse.GetPOIByDistrictIdAndCategoryIdResult.POI];}
catch(e1){news=[];}
this.showNewsForMarker(news,marker);}.bindObj(this)});}
else{if(marker.municipality){url="http://services.sapo.pt/GIS/GetPOIByMunicipalityIdAndCategoryIdJSON?municipalityId="+marker.municipality.id+"&categoryId=191&matchlevelId=0&trustlevelId=0&pageNumber=1&recordsPerPage=10";reqID=this.requester.request(url,{timeout:4,onComplete:function(obj){var news;try{news=obj.GetPOIByMunicipalityIdAndCategoryIdResponse.GetPOIByMunicipalityIdAndCategoryIdResult.POI.length?obj.GetPOIByMunicipalityIdAndCategoryIdResponse.GetPOIByMunicipalityIdAndCategoryIdResult.POI:[obj.GetPOIByMunicipalityIdAndCategoryIdResponse.GetPOIByMunicipalityIdAndCategoryIdResult.POI];}
catch(e1){news=[];}
this.showNewsForMarker(news,marker);}.bindObj(this)});}}
try{SapoMapsApp.Analytics.track("Layers","Noticias","AbrirPin");}
catch(e){}},showNewsForMarker:function(news,marker){var div_wraper=document.createElement("div");var div_header=document.createElement("div");var div_content=document.createElement("div");var div_newsBody=document.createElement("div");var p_newsBodyContent=document.createElement("p");var ul_list=document.createElement("ul");div_header.className="pop_header news_div_header";div_content.className="pop_content news_div_content";ul_list.className="news_ul_list";div_wraper.className="news_div_wraper";div_newsBody.className="pop_content news_div_newsBody";p_newsBodyContent.className="news_p_newsBodyContent";div_header.innerHTML="<p>Not&iacute;cias de "+(marker.district?marker.district.name:marker.municipality.name)+":</p>";var hideNewsBodyFunction=function(){div_header.innerHTML="<p>Not&iacute;cias de "+(marker.district?marker.district.name:marker.municipality.name)+":</p>";div_content.style.display="block";div_newsBody.style.display="none";marker.popup.contentUpdated();};var showNewsBodyFunction=function(){var div_links=document.createElement("div");var a_return=document.createElement("a");a_return.className="news_a";a_return.innerHTML="[Voltar &agrave;s not&iacute;cias]";var a_link=document.createElement("a");a_link.className="news_a";a_link.innerHTML="[Ver not&iacute;cia completa]";a_link.target="_blank";a_link.href=this.newsItem.URL;a_return.onclick=hideNewsBodyFunction;var p_locality=document.createElement("p");var p_date=document.createElement("p");var p_hour=document.createElement("p");p_locality.className="news_locality";p_date.className="news_date";p_hour.className="news_hour";p_locality.innerHTML=marker.district?marker.district.name:marker.municipality.name;p_date.innerHTML=this.newsItem.PublicationDate.substr(0,10);p_hour.innerHTML=this.newsItem.PublicationDate.substr(11,5);div_header.innerHTML="";div_header.appendChild(p_locality);div_header.appendChild(p_date);div_header.appendChild(p_hour);div_header.appendChild(a_return);div_links.appendChild(a_return);div_links.appendChild(a_link);div_header.appendChild(div_links);p_newsBodyContent.innerHTML="<strong>"+this.newsItem.Name+": </strong>"+this.newsItem.Description;div_wraper.style.marginLeft="0px";div_content.style.display="none";div_newsBody.style.display="block";if(div_newsBody.clientHeight>350){div_newsBody.style.height="350px";div_newsBody.style.overflow="auto";}
marker.popup.contentUpdated();};var newsItem=null,li_listItem=null,a_link=null;for(var i=0;i<news.length;++i){newsItem=news[i];if(i>0&&newsItem.Name===news[i-1].Name){continue;}
li_listItem=document.createElement("li");a_link=document.createElement("a");a_link.className="news_a_link";a_link.innerHTML=newsItem.Name;a_link.newsItem=newsItem;a_link.onclick=showNewsBodyFunction;li_listItem.appendChild(a_link);ul_list.appendChild(li_listItem);}
div_content.appendChild(ul_list);div_newsBody.appendChild(p_newsBodyContent);div_wraper.appendChild(div_header);div_wraper.appendChild(div_content);div_wraper.appendChild(div_newsBody);marker.openPopup(div_wraper,{borders:SapoMapsApp.borders});},removeMarkers:function(all){if(all){this.map.removeMarkers(this.markersObject);this.markersObject=new SAPO.Maps.Markers("SAPOMapsNews");this.map.addMarkers(this.markersObject);}
else{var markers=this.markersObject.getMarkers();var marker=null;for(var i=0;i<markers.length;++i){marker=markers[i];if(this.map.getBounds().containsLonLat(marker.getLonLat())){continue;}
if(marker.hasOpenedPopup()){continue;}
else{marker.unRegisterEvent('click',this,this.getNewsForMarker);this.markersObject.removeMarker(marker);}}}}};
﻿
SapoMapsApp.Layers={shopping:{name:'Compras',layers:{shoppings:{name:'Centros comerciais',categories:[82,85,86],minZoom:17},supermarkets:{name:'Hiper & supermercados',categories:[39,89,111,165],minZoom:18},traditionalProducts:{name:'Produtos tradicionais',categories:[285,17,109,284],minZoom:18},others:{name:'Outros',categories:[53],minZoom:18}}},culture:{name:'Cultura',layers:{libraries:{name:'Bibliotecas',categories:[25],minZoom:15},bingo:{name:'Casinos e bingos',categories:[40],minZoom:14},castels:{name:'Castelos e fortes',categories:[41],minZoom:10},catedrais:{name:'Catedrais e basílicas',categories:[42],minZoom:10},cultural_centers:{name:'Centros culturais',categories:[45],minZoom:15},cinema:{name:'Cinemas',categories:[51],minZoom:14},mosteiros:{name:'Conventos e mosteiros',categories:[56],minZoom:10},events:{name:'Eventos',categories:[363],minZoom:10},feiras:{name:'Feiras',categories:[74],minZoom:14},romarias:{name:'Festas e romarias',categories:[75],minZoom:14},movies:{name:'Filmes',categories:[364],minZoom:10},museums:{name:'Museus',categories:[120],minZoom:17},espetaculos:{name:'Salas de espectáculos',categories:[161],minZoom:15},others:{name:'Outros',categories:[283,204,80,279,309,148],minZoom:18}}},sports:{name:'Desportos',layers:{martial:{name:'Artes marciais',categories:[292],minZoom:17},football:{name:'Campos de futebol',categories:[31,288],minZoom:17},golf:{name:'Campos de golf',categories:[32,295],minZoom:17},tenis:{name:'Campos de ténis',categories:[33],minZoom:17},maintain:{name:'Circuitos de manutenção',categories:[293],minZoom:17},motor:{name:'Desportos motorizados',categories:[289,105],minZoom:17},gym:{name:'Ginásios',categories:[84,88],minZoom:17},swim:{name:'Piscinas',categories:[140],minZoom:17},padel:{name:'Padel',categories:[418],minZoom:15},polysports:{name:'Recintos polidesportivos',categories:[153],minZoom:17},others:{name:'Outros',categories:[28,34,49,60,294,173],minZoom:17}}},education:{name:'Ensino',layers:{schools:{name:'Basico e secundário',categories:[24],minZoom:16},univ:{name:'Ensino superior',categories:[164],minZoom:15},driveschools:{name:'Escolas de condução',categories:[64],minZoom:16},prof:{name:'Escolas profissionais',categories:[68],minZoom:15},arts:{name:'Escolas técnicas e artísticas',categories:[304],minZoom:15},preschool:{name:'Pré-escolar',categories:[151],minZoom:16},others:{name:'Outros',categories:[305],minZoom:17}}},hotels:{name:'Hotéis e alojamentos',layers:{flats:{name:'Apartamentos turísticos',categories:[12,15],minZoom:15},estalagens:{name:'Estalagens e albergarias',categories:[71],minZoom:15},hotels:{name:'Hotéis',categories:[92],minZoom:16},camp:{name:'Parques de campismo',categories:[131],minZoom:13},hostels:{name:'Pensões e residênciais',categories:[139],minZoom:16},pousadas:{name:'Pousadas',categories:[145,146],minZoom:14},spas:{name:'Termas e spas',categories:[166],minZoom:12},others:{name:'Outros',categories:[262,172],minZoom:17}}},restaurants:{name:'Restaurantes',layers:{bars:{name:'Bares',categories:[209,21,52],minZoom:18},cafes:{name:'Cafés',categories:[29,36,83],minZoom:18},discos:{name:'Discotecas',categories:[61],minZoom:18},restaurants:{name:'Restaurantes',categories:[37,43,50,158],minZoom:18}}},health:{name:'Saúde',layers:{enfermagem:{name:'Centros de enfermagem',categories:[47],minZoom:16},centros_saude:{name:'Centros de saúde',categories:[48,269],minZoom:16},pharmacies:{name:'Farmácias',categories:[73,127,270],minZoom:16},pharmaciesAtService:{name:'Farmácias de serviço',minZoom:6},hospitals:{name:'Hospitais',categories:[91],minZoom:16},others:{name:'Outros',categories:[274],minZoom:16}}},security:{name:'Segurança',layers:{fireman:{name:'Bombeiros',categories:[27],minZoom:16},army:{name:'Forças armadas',categories:[276],minZoom:17},police:{name:'Polícias',categories:[142],minZoom:17},proteccao_civil:{name:'Protecção civil',categories:[278],minZoom:17},tribunals:{name:'Tribunais',categories:[171],minZoom:17},others:{name:'Outros',categories:[277],minZoom:17}}},services:{name:'Serviços',layers:{photos:{name:'Fotos',minZoom:6},panoramas:{name:'Fotos 360º',minZoom:6},weather:{name:'Meteorologia',minZoom:6},news:{name:'Notícias',minZoom:6},fuel:{name:'Combustíveis',minZoom:6},saber:{name:'Saber',minZoom:6},traffic:{name:'Trânsito',minZoom:6},videos:{name:'Vídeos',minZoom:6},virtual:{name:'Visitas virtuais',minZoom:6}}},transports:{name:'Transportes',layers:{airport:{name:'Aeroportos',categories:[10],minZoom:11},air_heli_port:{name:'Aeródromos e heliportos',categories:[215,314],minZoom:11},train:{name:'Estações de caminhos de ferro',categories:[69],minZoom:15},subway:{name:'Estações de metro',categories:[70],minZoom:17},taxi:{name:'Praças de táxi',categories:[147],minZoom:16},parking:{name:'Parques de estacionamento',categories:[133],minZoom:18},rent_bike:{name:'Rent-a-bike',categories:[155],minZoom:14},rent_car:{name:'Rent-a-car',categories:[156],minZoom:16},boat:{name:'Terminais de barco',categories:[167],minZoom:15},bus:{name:'Terminais de camionagem',categories:[168],minZoom:15}}},tourism:{name:'Turismo e viagens',layers:{travel:{name:'Agências de viagens',categories:[11],minZoom:17},villages:{name:'Aldeias típicas',categories:[13,235,122,174],minZoom:11},barrage:{name:'Barragens',categories:[154],minZoom:13},gardens:{name:'Jardins',categories:[100,101,102],minZoom:14},monumentos:{name:'Monumentos',categories:[72,325,77,313,96,119,126,143,323,38],minZoom:15},miradouros:{name:'Miradouros',categories:[113],minZoom:15},funparks:{name:'Parques de diversão',categories:[326,128,129,130,134],minZoom:15},beach:{name:'Praias',categories:[149,150],minZoom:13},turism:{name:'Postos de turismo',categories:[144],minZoom:18},geo_turism:{name:'Locais geo-turísticos',categories:[415],minZoom:12},others:{name:'Outros',categories:[14,16,299,54,57,116,324,87,90,107,108,121,115,124,125,137,141,95,315,97,297,211,138,159,170,172],minZoom:18}}},utilities:{name:'Utilidades',layers:{bank:{name:'Bancos',categories:[19],minZoom:17},securityAgency:{name:'Seguradoras',categories:[420],minZoom:17},gas:{name:'Bombas de gasolina',categories:[26],minZoom:15},camaras:{name:'Câmaras municipais',categories:[30],minZoom:14},cartorios:{name:'Cartórios/Conservatórias',categories:[35,55],minZoom:15},poststation:{name:'Correios',categories:[58],minZoom:16},embancy:{name:'Embaixadas e consulados',categories:[62],minZoom:14},internet:{name:'Espaços internet e hotspots',categories:[317,94],minZoom:16},financas:{name:'Finanças',categories:[76],minZoom:16},juntas:{name:'Juntas de freguesia',categories:[103],minZoom:16},cidadao:{name:'Lojas do cidadão',categories:[216],minZoom:15},multibancos:{name:'Multibancos',categories:[118],minZoom:18},social_security:{name:'Segurança social',categories:[162],minZoom:16},auto_inspection:{name:'Centros de Inspecção Automóvel',categories:[413],minZoom:9},auto_garage:{name:'Oficina',categories:[417],minZoom:11},recycle:{name:'Reciclagem',categories:[404,411],minZoom:13},funeral_agency:{name:'Agências funerárias',categories:[412],minZoom:12},others:{name:'Outros',categories:[316,216,302,44,63,310,307,79,414,416,410,98,99],minZoom:18}}}};SapoMapsApp.Categories={};(function(){for(var layerName in SapoMapsApp.Layers){var layer=SapoMapsApp.Layers[layerName];for(var subLayerName in layer.layers){var subLayer=layer.layers[subLayerName];if(!subLayer.categories){continue;}
for(var i=0;i<subLayer.categories.length;++i){var category=subLayer.categories[i];SapoMapsApp.Categories[category]={l:layerName,sl:subLayerName};}}}})();
var categories_html=null;var visible=false;var categoryShownInfo=null;var categories_sidebar={services_traffic:{layer:'services',sub_layer:'traffic'},health_pharmaciesAtService:{layer:'health',sub_layer:'pharmaciesAtService'},services_virtual:{layer:'services',sub_layer:'virtual'},services_panoramas:{layer:'services',sub_layer:'panoramas'},services_weather:{layer:'services',sub_layer:'weather'},services_fuel:{layer:'services',sub_layer:'fuel'}};function iniCategoriesUI(){categories_html=document.getElementById('categories');var resize=OpenLayers.Function.bindAsEventListener(resizeCategories,this);OpenLayers.Event.observe(window,"resize",resize);resizeCategories();buildCategoriesHTML();map.events.register('zoomend',this,zoomChanged);var id=false;var element=false;var listener=false;var listener_hover=false;var listener_out=false;for(var e in categories_sidebar){id='sidebar_'+e;listener=OpenLayers.Function.bind(toggleSideBarCategories,this,e,true);OpenLayers.Event.observe(document.getElementById(id),'click',listener);}
checkDimensionsToDisplayExtraCategories();};function buildCategoriesHTML(){var curr_zoom=map.getZoom();var deactivated_categories_text=document.getElementById('deactivated_categories_text');var activeLayers=document.getElementById('selected_cat_list');var nonActiveLayers=document.getElementById('unselected_cat_list');var subcategoriesHolder=document.getElementById('subcategories');var hasDeactiveLayers=false;var li=false;var input=false;var label=false;var div_arrow=false;var isAnyActive=false;var subcategories=false;var sub_ul=false;var sub_li=false;var sub_input=false;var sub_label=false;var toggleLayer_listener=false;var toggleCategory_listener=false;var toggleSubLayers_listener=false;var sideBarId=false;var sideBarCategory=false;var layers=SapoMapsApp.Layers;for(var l in layers){isAnyActive=false;li=document.createElement('li');input=document.createElement('input');try{label=document.createElement('<label for="'+l+'"></label>');}
catch(e1){label=document.createElement('label');label.setAttribute('for',l);}
div_arrow=document.createElement('div');input.id=l;input.type='checkbox';div_arrow.className='cat_expand_arrow';li.appendChild(input);li.appendChild(label);li.appendChild(div_arrow);label.appendChild(document.createTextNode(layers[l].name));label.className='cat_'+l;subcategories=layers[l].layers;sub_ul=document.createElement('ul');sub_ul.id='sub_'+l;sub_ul.className='hide';subcategoriesHolder.appendChild(sub_ul);for(var subl in subcategories){sub_li=document.createElement('li');sub_input=document.createElement('input');var id=l+'_'+subl;try{sub_label=document.createElement('<label for="'+id+'"></label>');}
catch(e2){sub_label=document.createElement('label');sub_label.setAttribute('for',id);}
sub_input.type='checkbox';sub_input.id=id;sub_ul.appendChild(sub_li);sub_li.appendChild(sub_input);sub_li.appendChild(document.createTextNode('   '));sub_li.appendChild(sub_label);sub_label.innerHTML=subcategories[subl].name;sideBarId=l+'_'+subl;if(curr_zoom>=subcategories[subl].minZoom){sub_li.className='';isAnyActive=true;if(categories_sidebar[sideBarId]){sideBarCategory=document.getElementById('sidebar_'+sideBarId);SAPO.Maps.Utils.removeClassName(sideBarCategory,'disabled_cat');}}else{sub_li.className='inactive';hasDeactiveLayers=true;if(categories_sidebar[sideBarId]){sideBarCategory=document.getElementById('sidebar_'+sideBarId);SAPO.Maps.Utils.addClassName(sideBarCategory,'disabled_cat');}}
toggleCategory_listener=OpenLayers.Function.bind(toggleLayerCategory,this,l,subl,true);OpenLayers.Event.observe(sub_input,'click',toggleCategory_listener);}
if(isAnyActive){activeLayers.appendChild(li);}else{input.disabled=true;nonActiveLayers.appendChild(li);}
toggleLayer_listener=OpenLayers.Function.bind(toggleLayers,this,l);OpenLayers.Event.observe(input,'click',toggleLayer_listener);toggleSubLayers_listener=OpenLayers.Function.bind(toggleSubCategoriesHTML,this,{superLayer_id:l,id:sub_ul.id,arrow:div_arrow});OpenLayers.Event.observe(div_arrow,'click',toggleSubLayers_listener);}
if(!hasDeactiveLayers){deactivated_categories_text.className='hide';}};function toggleSubCategoriesHTML(categoryInfo){var nonActivatableLayers=document.getElementById('unselected_cat_list');if(document.getElementById(categoryInfo.superLayer_id).parentNode.parentNode===nonActivatableLayers){return;}
if(categoryInfo){var size=OpenLayers.Util.getRenderedDimensions(document.getElementById(categoryInfo.id).innerHTML);document.getElementById('subcategories').style.width=size.w+60+'px';}
if(categoryShownInfo){var categoryShown=document.getElementById(categoryShownInfo.id);var superLayer=document.getElementById(categoryShownInfo.superLayer_id);var arrow=categoryShownInfo.arrow;categoryShown.className='hide';arrow.className='cat_expand_arrow';SAPO.Maps.Utils.removeClassName(superLayer.parentNode,'active');}
if(categoryShownInfo&&categoryShownInfo.superLayer_id===categoryInfo.superLayer_id){categoryShownInfo=null;document.getElementById('subcategories').style.width='0px';return;}
categoryShownInfo=categoryInfo;var categoryShown=document.getElementById(categoryInfo.id);var superLayer=document.getElementById(categoryInfo.superLayer_id);categoryShown.className='show';categoryInfo.arrow.className='cat_collapse_arrow';SAPO.Maps.Utils.addClassName(superLayer.parentNode,'active');document.getElementById('subcategories').style.height=document.getElementById('selected_cat_list').parentNode.offsetHeight+'px';};function toggleCategoriesHTML(){visible=!visible;categories_html.style.display=visible?'block':'none';};function hideCategories(){if(visible){visible=false;categories_html.style.display='none';}};function checkDimensionsToDisplayExtraCategories(){var left_col=document.getElementById('left_col');var quickaction=document.getElementById('pub_quickaction');var editorial=document.getElementById('pub_editorial');var mrec=document.getElementById('pub_mrec');var weather=document.getElementById('sidebar_services_weather');var fuel=document.getElementById('sidebar_services_fuel');var filter_offset=40;var height=left_col.offsetHeight-300-60-20+filter_offset;var cat_height=document.getElementById('sidebar_services_panoramas').offsetHeight+100;if(height>cat_height){if(!fuel.isVisible){fuel.isVisible=true;SAPO.Maps.Utils.removeClassName(weather,'hide');SAPO.Maps.Utils.removeClassName(fuel,'hide');SAPO.Maps.Utils.addClassName(weather,'show');SAPO.Maps.Utils.addClassName(fuel,'show');SAPO.Maps.Utils.Fade(document.getElementById('sidebar_label_services_weather'));SAPO.Maps.Utils.Fade(document.getElementById('sidebar_label_services_fuel'));}}else{weather.className='hide';SAPO.Maps.Utils.removeClassName(weather,'show');SAPO.Maps.Utils.removeClassName(fuel,'show');SAPO.Maps.Utils.addClassName(weather,'hide');SAPO.Maps.Utils.addClassName(fuel,'hide');}}
function resizeCategories(){var categoriesMenu=document.getElementById('menu_categories');var middle=Math.floor(categoriesMenu.offsetWidth/2);this.categories_html.style.left=categoriesMenu.offsetLeft+middle+170+'px';checkDimensionsToDisplayExtraCategories();}
function toggleLayers(layerName){var input=document.getElementById(layerName);var icon=input.parentNode;if(input.checked){SAPO.Maps.Utils.addClassName(icon,'checked_cat');}else{SAPO.Maps.Utils.removeClassName(icon,'checked_cat');}
switch(layerName){case'services':if(input.checked){SapoMapsApp.Traffic.activate(map);SapoMapsApp.VirtualVisits.activate();SapoMapsApp.Panoramas.activate();SapoMapsApp.Saber.activate();SapoMapsApp.Weather.activate();SapoMapsApp.Photos.activate();SapoMapsApp.Videos.activate();SapoMapsApp.News.activate();SapoMapsApp.Fuel.activate();SapoMapsApp.Analytics.track("Layers","Services","ActivarLayer");}else{SapoMapsApp.Traffic.deactivate();SapoMapsApp.VirtualVisits.deactivate();SapoMapsApp.Panoramas.deactivate();SapoMapsApp.Saber.deactivate();SapoMapsApp.Weather.deactivate();SapoMapsApp.Photos.deactivate();SapoMapsApp.Videos.deactivate();SapoMapsApp.News.deactivate();SapoMapsApp.Fuel.deactivate();}
break;case'health':if(input.checked){SapoMapsApp.PharmsAtService.activate();SapoMapsApp.POIS.activateLayer(layerName);SapoMapsApp.Analytics.track("Layers",layerName,"ActivarLayer");}else{SapoMapsApp.PharmsAtService.deactivate();SapoMapsApp.POIS.deactivateLayer(layerName);SapoMapsApp.Analytics.track("Layers",layerName,"ActivarLayer");}
break;default:if(input.checked){SapoMapsApp.POIS.activateLayer(layerName);SapoMapsApp.Analytics.track("Layers",layerName,"ActivarLayer");}else{SapoMapsApp.POIS.deactivateLayer(layerName);}
break;}
if(!categoryShownInfo||(categoryShownInfo&&categoryShownInfo.superLayer_id!==layerName)){toggleSubCategoriesHTML({superLayer_id:layerName,id:'sub_'+layerName,arrow:input.parentNode.childNodes[input.parentNode.childNodes.length-1]});}
toogleCategories(layerName,input.checked);}
function toggleLayerCategory(layerName,categoryName,toogleSideBar){if(toogleSideBar){toggleSideBarCategories(layerName+'_'+categoryName,false);}
var sublayerInput=document.getElementById(layerName+'_'+categoryName);if(sublayerInput.checked===true){activateMasterLayer(layerName);}else{if(isAnyChecked(layerName)===false){deactivateMasterLayer(layerName);}}
switch(categoryName){case'saber':if(sublayerInput.checked){SapoMapsApp.Saber.activate();SapoMapsApp.Analytics.track("Layers","Noticias","ActivarLayer");}
else{SapoMapsApp.Saber.deactivate();}
break;case'traffic':if(sublayerInput.checked){SapoMapsApp.Traffic.activate(map);SapoMapsApp.Analytics.track("Layers","Transito","ActivarLayer");}
else{SapoMapsApp.Traffic.deactivate();}
break;case'virtual':if(sublayerInput.checked){SapoMapsApp.VirtualVisits.activate();SapoMapsApp.Analytics.track("Layers","VisitasVirtuais","ActivarLayer");}
else{SapoMapsApp.VirtualVisits.deactivate();}
break;case'panoramas':if(sublayerInput.checked){SapoMapsApp.Panoramas.activate();SapoMapsApp.Analytics.track("Layers","Fotos 360","ActivarLayer");}
else{SapoMapsApp.Panoramas.deactivate();}
break;case'weather':if(sublayerInput.checked){SapoMapsApp.Weather.initialize(map);SapoMapsApp.Weather.activate();SapoMapsApp.Analytics.track("Layers","Meteorologia","ActivarLayer");}
else{SapoMapsApp.Weather.deactivate();}
break;case'photos':if(sublayerInput.checked){SapoMapsApp.Photos.activate();SapoMapsApp.Analytics.track("Layers","Fotos","ActivarLayer");}
else{SapoMapsApp.Photos.deactivate();}
break;case'videos':if(sublayerInput.checked){SapoMapsApp.Videos.activate();SapoMapsApp.Analytics.track("Layers","Videos","ActivarLayer");}
else{SapoMapsApp.Videos.deactivate();}
break;case'news':if(sublayerInput.checked){SapoMapsApp.News.activate();SapoMapsApp.Analytics.track("Layers","Noticias","ActivarLayer");}
else{SapoMapsApp.News.deactivate();}
break;case'fuel':if(sublayerInput.checked){SapoMapsApp.Fuel.activate();SapoMapsApp.Analytics.track("Layers","Fuel","ActivarLayer");}
else{SapoMapsApp.Fuel.deactivate();}
break;case'pharmaciesAtService':if(sublayerInput.checked){SapoMapsApp.PharmsAtService.activate();SapoMapsApp.Analytics.track("Layers",categoryName,"ActivarLayer");}
else{SapoMapsApp.PharmsAtService.deactivate();}
break;default:if(sublayerInput.checked){SapoMapsApp.POIS.activateLayer(layerName,categoryName);SapoMapsApp.Analytics.track("Layers",categoryName,"ActivarLayer");}
else{SapoMapsApp.POIS.deactivateLayer(layerName,categoryName);}
break;}}
function toggleSideBarCategories(e,activateCategoryList,isToActive){if(categories_sidebar[e]){var id='sidebar_'+e;var sidebar_cat=document.getElementById(id);var input=document.getElementById('sidebar_input_'+e);if(sidebar_cat.isActive){if(isToActive===true){return;}
sidebar_cat.isActive=false;SAPO.Maps.Utils.removeClassName(sidebar_cat,'active');SAPO.Maps.Utils.addClassName(sidebar_cat,'disabled');if(id=="sidebar_services_fuel"){var id_filter=id+"_filter";var sidebar_cat_filter=document.getElementById(id_filter);SAPO.Maps.Utils.removeClassName(sidebar_cat_filter,'show');SAPO.Maps.Utils.addClassName(sidebar_cat_filter,'hide');removePubToDisplayPanel(selectedPanel,0,null,false);}
input.checked=false;}else{if(isToActive===false){return;}
sidebar_cat.isActive=true;SAPO.Maps.Utils.removeClassName(sidebar_cat,'disabled');SAPO.Maps.Utils.addClassName(sidebar_cat,'active');if(id=="sidebar_services_fuel"){var id_filter=id+"_filter";var sidebar_cat_filter=document.getElementById(id_filter);SAPO.Maps.Utils.removeClassName(sidebar_cat_filter,'hide');SAPO.Maps.Utils.addClassName(sidebar_cat_filter,'show');removePubToDisplayPanel(selectedPanel,0,null,false);}
input.checked=true;}
if(activateCategoryList){document.getElementById(e).checked=sidebar_cat.isActive;toggleLayerCategory(categories_sidebar[e].layer,categories_sidebar[e].sub_layer,false);}}}
function zoomChanged(){var deactivated_categories_text=document.getElementById('deactivated_categories_text');var activeLayers=document.getElementById('selected_cat_list');var nonActiveLayers=document.getElementById('unselected_cat_list');var curr_zoom=map.getZoom();var li=false;var input=false;var sub_input=false;var sub_li=false;var anyActive=false;var hasDeactiveLayers=false;var sideBarId=false;var sideBarCategory=false;for(var l in SapoMapsApp.Layers){anyActive=false;input=document.getElementById(l);li=input.parentNode;for(var sl in SapoMapsApp.Layers[l].layers){sub_input=document.getElementById(l+'_'+sl);sub_li=sub_input.parentNode;sideBarId=l+'_'+sl;if(curr_zoom>=SapoMapsApp.Layers[l].layers[sl].minZoom){sub_input.disabled=false;sub_li.className='';anyActive=true;if(categories_sidebar[sideBarId]){sideBarCategory=document.getElementById('sidebar_'+sideBarId);document.getElementById('sidebar_input_'+sideBarId).disabled=false;SAPO.Maps.Utils.removeClassName(sideBarCategory,'disabled_cat');}}else{sub_input.disabled=true;sub_li.className='inactive';if(categories_sidebar[sideBarId]){sideBarCategory=document.getElementById('sidebar_'+sideBarId);document.getElementById('sidebar_input_'+sideBarId).disabled=true;SAPO.Maps.Utils.addClassName(sideBarCategory,'disabled_cat');}}}
if(anyActive){if(li.parentNode===nonActiveLayers){nonActiveLayers.removeChild(li);insertElementInOrder(activeLayers,li);input.disabled=false;SAPO.Maps.Utils.Fade(li);}}else{if(li.parentNode===activeLayers){if(categoryShownInfo&&categoryShownInfo.superLayer_id===l){toggleSubCategoriesHTML(categoryShownInfo);}
activeLayers.removeChild(li);insertElementInOrder(nonActiveLayers,li);input.disabled=true;}
hasDeactiveLayers=true;}}
if(hasDeactiveLayers){deactivated_categories_text.className='';}else{deactivated_categories_text.className='hide';}};function insertElementInOrder(holder,element){var child=false;for(var i=0;i<holder.childNodes.length;++i){child=holder.childNodes[i];if(child.nodeName!=='LI'){continue;}
if(isGreatherThan(child,element)){holder.insertBefore(element,child)
return;}}
holder.appendChild(element);};function isGreatherThan(element1,element2){var str1=element1.childNodes[1].innerHTML;var str2=element2.childNodes[1].innerHTML;return str1>str2;};function checkOptionsWhenLoadsState(state){var sub_layers=false;for(var i=0;i<state.length;++i){sub_layers=state[i].split('-');activateMasterLayer(sub_layers[0]);if(sub_layers.length>1){var sub_layer=false;for(var j=1;j<sub_layers.length;++j){sub_layer=document.getElementById(sub_layers[0]+'_'+sub_layers[j]);sub_layer.checked=true;toggleSideBarCategories(sub_layers[0]+'_'+sub_layers[j],false,true);}}else{toogleCategories(sub_layers[0],true);}}}
function activateMasterLayer(layerName){var input=document.getElementById(layerName);var icon=input.parentNode;SAPO.Maps.Utils.addClassName(icon,'checked_cat');input.checked=true;}
function deactivateMasterLayer(layerName){var input=document.getElementById(layerName);var icon=input.parentNode;SAPO.Maps.Utils.removeClassName(icon,'checked_cat');input.checked=false;}
function toogleCategories(layerName,check){var subUl=document.getElementById('sub_'+layerName);var subLayerInput=false;for(var i=0;i<subUl.childNodes.length;++i){subLayerInput=subUl.childNodes[i].firstChild;subLayerInput.checked=check;toggleSideBarCategories(subLayerInput.id,false,check);}}
function toogleCategory(layerName,categoryName,check){var category=document.getElementById(layerName+'_'+categoryName);category.checked=check;}
function isAnyChecked(layerName){var sub_layers=document.getElementById('sub_'+layerName);var input=false;for(var i=0;i<sub_layers.childNodes.length;++i){input=sub_layers.childNodes[i].childNodes[0];if(input.checked==true){return true;}}
return false;}
var fdLocale={fullMonths:["Janeiro","Fevereiro","Mar\u00E7o","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"],monthAbbrs:["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"],fullDays:["Segunda","Ter\u00E7a","Quarta","Quinta","Sexta","S\u00E1bado","Domingo"],dayAbbrs:["Seg","Ter","Qua","Qui","Sex","S\u00E1b","Dom"],titles:["M\u00EAs Anterior","M\u00EAs Seguinte","Ano Anterior","Ano Seguinte","Hoje","Mostrar Calend\u00E1rio","sem","Semana [[%0%]] of [[%1%]]","Semana","Seleccionar data","Arrastar","Mostrar \u201C[[%0%]]\u201D first","Ir para data actual","Desabilitar data"]};
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('k 6c=(B 6c(){k 6d=8U(),U={},8V=0,5u={},2u=G,3Y=1a.aE(aF),55=G,7y=R,6e=G,2v=["-dd","-7z"],7A="d-1J-F-1J-Y",4w="F-1J-d-cc-1J-Y",6f=["57","1J-F-1J-Y"],7B=["Y-1T-m-1T-d","m-1T-d-1T-Y","d-1T-m-1T-Y","Y-2c-m-2c-d","m-2c-d-2c-Y","d-2c-m-2c-Y","d-2c-m-2c-y","d-1T-m-1T-y"],3c={4x:["aG","aH","aI","aJ","8W","aK","aL","aM","aN","aO","aP","aQ"],4y:["aR","aS","aT","aU","8W","aV","aW","aX","aY","aZ","b0","b1"],4z:["b2","b3","b4","b5","b6","b7","b8"],3Z:["b9","ba","bb","bc","bd","be","bf"],2F:["8X 1D","8Y 1D","8X 25","8Y 25","8Z","bg bh","bi","91 [[%0%]] 58 [[%1%]]","91","bj a E","bk \\bl bm 92 bn","bo \\bp[[%0%]]\\bq br","bs 92 8Z\\bt E","bu E"],2G:0,93:G};bv B(){k 4A=q.26(\'7C\')[0].26(\'3d\'),94=4A[4A.X-1].bw.Z(/[\\n\\r\\s\\t]+/g," ").Z(/^\\s+/,"").Z(/\\s+$/,""),3p=95(94);h(2q 3p==="3I"&&!("2R"15 3p)){7D(3p)};h(2q(3q)!="3I"){k 98=4A[4A.X-1].6g.K(0,4A[4A.X-1].6g.bx("/"))+"/7E/",3d;16(k i=0;i<6d.X;i++){3d=q.1N(\'3d\');3d.1o="43/9a";3d.6g=98+6d[i]+".by";3d.2S("bz","bA-8");/*@1U/*@h(@3e)k 5v=q.26(\'bB\');h(5v.X&&5v[0].bC.X){5v[0].18(3d)}J{q.26(\'7C\')[0].18(3d)};5v=1d;@J@*/q.26(\'7C\')[0].18(3d);/*@2i@*/};3d=1d}J{6e=R}}();B 8U(){k 5w=6h.9b?6h.9b.2a():6h.9c?6h.9c.2a():"bD";h(5w.L(/^([a-z]{2})-([a-z]{2})$/)!=-1){u[5w.1z(/^([a-z]{2})-([a-z]{2})$/)[1],5w]}J{u[5w.K(0,2)]}};B 7D(3p){h(2q 3p!=="3I"){u};16(7F 15 3p){1b=3p[7F];7G(7F.2a()){1t"7E":h(1b.L(/^[a-z]{2}(-([a-z]{2}))?$/i)!=-1){6d=[1b.2a()];6e=R};1l;1t"3f":h(2q 1b===\'3I\'){h(1b.X&&1b.X==2){2v=1b}};1l;1t"9d":h(2q 1b===\'3I\'){h(1b.X){k 6i=[];16(k m=0,6j;6j=1b[m];m++){h(6j.1z(/((1J|T|1T|2c|cc)|([d|D|l|j|N|w|S|W|M|F|m|n|t|Y|o|y|O|p]))(-((1J|T|1T|2c|cc)|([d|D|l|j|N|w|S|W|M|F|m|n|t|Y|o|y|O|p])))+/)){6i.2o(6j)}};h(6i.X){7B=6i}}};1l;1t"55":55=!!1b;1l;1t"bE":7y=!!1b;1l;1t"bF":h(2q 1b=="9e"&&1b.1z(/^((1J|T|1T|2c|cc)|([d|D|l|j|N|w|S|W|M|F|m|n|t|Y|o|y|O|p]))(-((1J|T|1T|2c|cc)|([d|D|l|j|N|w|S|W|M|F|m|n|t|Y|o|y|O|p])))+$/)){9f(1b)};1l;1t"bG":h(1b.1z(/((1J|T|1T|2c|cc)|([d|D|l|j|N|w|S|W|M|F|m|n|t|Y|o|y|O|p]))(-((1J|T|1T|2c|cc)|([d|D|l|j|N|w|S|W|M|F|m|n|t|Y|o|y|O|p])))+/)){4w=1b}}}};B 9f(1b){k 1K=1b.3f("-"),4B=[],4C=[],1O;16(k 2H=0;2H<1K.X;2H++){1O=1K[2H];h(1O=="j"||1O=="d"){h(4C.X){4B.2o(4C.5x("-"));4C=[]};4B.2o("57")}J{4C.2o(1O)}};h(4C.X){4B.2o(4C.5x("-"))};h(!4B.X||4B.X>3){6f=1E.6k?["57"]:["57","1J-F-1J-Y"];7A="j-1J-F-1J-Y";u};6f=1E.6k?["57"]:4B;7A=1E.6k?"j-1J-F-1J-Y":1b};B 1i(1b,X){X=X||2;u"bH".K(0,X-2d.5y(1a(1b).X,X))+1b};B 2j(1f,1o,1P){2T{h(1f.9g){1f["e"+1o+1P]=1P;1f[1o+1P]=B(){1f["e"+1o+1P](1E.3r)};1f.9g("59"+1o,1f[1o+1P])}J{1f.bI(1o,1P,R)}}2U(2R){bJ(1f+" "+1o+" "+1P)}};B 1V(1f,1o,1P){2T{h(1f.9h){1f.9h("59"+1o,1f[1o+1P]);1f[1o+1P]=1d}J{1f.bK(1o,1P,R)}}2U(2R){}};B 2w(e){e=e||q.4D.3r;h(e.9i){e.9i();e.bL()};/*@1U@h(@3e)e.bM=R;e.bN=G;@2i@*/u G};B 95(P){h(2q P!==\'9e\'||P==""){u{}};2T{h(2q 6l==="3I"&&6l.9j){u 1E.6l.9j(P)}J h(/7E|3f|9d|55/.5a(P.2a())){k f=6m([\'k q,3J,bO,1E,9k,1Q,1e,bP,6m,\',\'bQ,1a,2d,5z,bR,bS;\',\'u (\',P.Z(/<\\!--.+-->/bT,\'\').Z(/\\bU\\b/g,\'B­\'),\');\'].5x(\'\'));u f()}}2U(e){};u{"2R":"bV bW 6l 3I"}};B 3s(1v,7H){h(1v&&1v.1B){1v.2S("7H",7H)}};B 2x(1v,9l,1b){h(1v&&1v.1B){1v.2S("7I-"+9l,1b)}};B 1p(H){c.2y=1d;c.5A=G;c.3g=G;c.5B=1d;c.5C=1d;c.4E=0;c.4F=0;c.6n=0;c.7J=0;c.7K=0;c.x=0;c.y=0;c.2e=H.2e?H.2e:"",c.E="2e"15 H&&H.2e?17 1e(+H.2e.K(0,4),+H.2e.K(4,2)-1,+H.2e.K(6,2)):17 1e();c.bX={};c.2k=G;c.1u=G;c.A=H.A;c.3t=0;c.2G=2u.2G;c.44="44"15 H?H.44:G;c.1y="1y"15 H?!!H.1y:G;c.2I="2I"15 H&&H.2I.X?H.2I:[0,0,0,0,0,0,0];c.3h="3h"15 H?H.3h:{};c.2J="2J"15 H?H.2J:{};c.1X="1X"15 H?!!H.1X:G;c.1F=H.1F||"";c.1W=H.1W||"";c.4G=55?R:("4G"15 H?!!H.4G:G);c.2K="2K"15 H?H.2K:G;c.5b=c.1y?G:"5b"15 H?!!H.5b:G;c.3u="3u"15 H?!!H.3u:G;c.45=H.45||"d-1T-m-1T-Y";c.2V=H.2V||"";c.3K=H.3K&&H.3K.X?H.3K:[0,0,0,0,0,1,1];c.4H="4H"15 H?!!H.4H:G;c.3L=c.4H||c.1y?99:90;c.3v={};c.46=!!H.46;c.4I=!!H.4I;c.7L=9m(q.1j(H.A));c.4J=c.46&&!!H.4J;c.5D=!c.1y&&"5D"15 H?+H.5D:90;c.7M={};c.6o=G;c.1Y=R;c.47=G;c.5E=G;c.5F=1d;c.bY=1d;c.4a=c.1y;c.7N=G;/*@1U@h(@3e)c.6p=17 1e();c.1L=1d;c.4b=G;@2i@*//*@1U@h(@4K<=5.7)c.4b=q.3i&&2q q.3i.1h.bZ!="7O";@2i@*/16(k 7P 15 H.3v){c.3v[7P]=H.3v[7P]};c.E.6q(12);c.6r=B(){o.4c();h(o.2k){o.2l()}};c.9n=B(){h(2q(1E.7Q)==\'9o\'){u[1E.9p,1E.7Q]}J h(q.3M&&(q.3M.3N||q.3M.4d)){u[q.3M.3N,q.3M.4d]}J h(q.3i&&(q.3i.3N||q.3i.4d)){u[q.3i.3N,q.3i.4d]};u[0,0]};c.6s=B(){h(!o.2k||!o.4e()||o.1y){u};o.Q.1h.4L="3j";o.Q.1h.4f=o.Q.1h.3J="7R";o.Q.1h.2W="6t";k 6u=o.Q.5G,6v=o.Q.6w,C=q.1j(\'1m-I-\'+o.A),3w=o.9q(C),6x=(q.6y&&q.6y!="9r")?q.3i:q.3M,7S=o.9n(),4d=7S[1],3N=7S[0];o.Q.1h.4L="3g";o.Q.1h.4f=1Q(2X(6x.9s+3N)<2X(6v+3w[0])?2d.6z(2X((6x.9s+3N)-6v)):3w[0])+"3x";o.Q.1h.3J=1Q(2X(6x.c0+4d)<2X(6u+3w[1]+C.5G+2)?2d.6z(2X(3w[1]-(6u+2))):2d.6z(2X(3w[1]+C.5G+2)))+"3x";/*@1U@h(@4K<=5.7)h(o.4b)u;o.1L.1h.3J=o.Q.1h.3J;o.1L.1h.4f=o.Q.1h.4f;o.1L.1h.7T=6v+"3x";o.1L.1h.7U=(6u-2)+"3x";@2i@*/};c.5H=B(){k 14=q.1j(o.A+"-E-1G-3O");h(14){2T{14.2S(!/*@1U!@*/G?"3k":"5I","-1");14.3k=-1;14.v=14.v.Z(/E-1G-3O/,"");14.A=""}2U(2R){}}};c.5J=B(){k 14=q.1j(o.A+"-E-1G-3O");h(14){2T{14.2S(!/*@1U!@*/G?"3k":"5I","0");14.3k=0;14.v=14.v.Z(/E-1G-3O/,"")+" E-1G-3O";h(!c.1Y){6A(B(){2T{14.4M()}2U(2R){}},0)}}2U(2R){}}};c.2l=B(c1){h(o.6o)u;o.6o=R;o.5H();h(o.5A){o.E.3y(2d.5y(o.E.1R()+o.6n,2L(o.E.1r()+o.4F,o.E.1s()+o.4E)));o.E.5K(o.E.1r()+o.4F);o.E.7V(o.E.1s()+o.4E)};o.3z();h(!o.4I){o.6B()};o.7W(o.E);k cd=o.E.1R(),cm=o.E.1r(),cy=o.E.1s(),2e=(1a(cy)+1i(cm+1)+1i(cd)),1g=17 1e(cy,cm,1);1g.6q(5);k T,2z,14,i,2Y,4g,1k,2r,9t,6C,5L,7X=(1g.3P()+6)%7,4h=(((7X-o.2G)+7)%7)-1,5c=2L(cm,cy),21=17 1e(),9u=(o.2y!=1d)?o.2y.1s()+1i(o.2y.1r()+1)+1i(o.2y.1R()):G,5M=1a(1g.1s())+1i(1g.1r()+1),4g=[4,4,4,4,4,4],5d=17 1e(cy,cm-1,1),6D=17 1e(cy,cm+1,1),7Y=2L(5d.1r(),5d.1s()),7Z=1a(6D.1s())+1i(6D.1r()+1),80=1a(5d.1s())+1i(5d.1r()+1),9v=(6D.3P()+6)%7,9w=(5d.3P()+6)%7,21=21.1s()+1i(21.1r()+1)+1i(21.1R()),5N=q.1N(\'1n\'),2J=o.6E(cy,cm+1);o.2Z=!o.4J&&o.46&&(0-4h<1)?1a(80)+(7Y+(0-4h)):5M+"2f";o.3a=!o.4J&&o.46?7Z+1i(41-4h-5c):5M+1a(5c);o.5O=5M;6C=o.6F("6G",{A:o.A,dd:1i(cd),7z:1i(cm+1),3l:cy,c2:o.2Z,c3:o.3a})||{};o.7M=o.6H(cy,cm+1);5N.v="1m-9x-9y";h(c.5F!=1d){2x(c.5F,"6I",G);c.5F=1d};16(k 3A=0;3A<42;3A++){1M=2d.c4(3A/7);14=o.81[3A];5L=5N.9z(G);2m(14.2p)14.3B(14.2p);h((3A>4h&&3A<=(4h+5c))||o.46){2r=5M;3C=7X;T=3A-4h;2z=[];4N=R;h(T<1){T=7Y+T;2r=80;3C=9w;4N=!o.4J;2z.2o("1D-3Q")}J h(T>5c){T-=5c;2r=7Z;3C=9v;4N=!o.4J;2z.2o("1D-3Q")};3C=(3C+T+6)%7;2z.2o("22-"+3c.3Z[3C].2a());2Y=2r+1a(T<10?"0":"")+T;h(o.1F&&+2Y<+o.1F||o.1W&&+2Y>+o.1W){14.v="3Q-58-1A";14.2g="";14.18(q.2h(T));h(o.1X){4g[1M]=2d.5y(4g[1M],2)}}J{h(4N){14.2g=4w?3m(17 1e(+1a(2r).K(0,4),+1a(2r).K(4,2)-1,+T),4w,R):"";2z.2o("cd-"+2Y+" 9A-"+2r+" 9B-"+2r.K(4,2)+1i(T))}J{14.2g=4w?1H(13)+" "+3m(17 1e(+1a(2r).K(0,4),+1a(2r).K(4,2)-1,+T),4w,R):"";2z.2o("9A-"+2r+" 9B-"+2r.K(4,2)+1i(T)+" 6J-4N")};h(2Y==21){2z.2o("E-1G-21")};h(9u==2Y){2z.2o("E-1G-6I-E");2x(14,"6I","R");c.5F=14};h((o.2I[3C]&&!(2Y 15 2J))||2Y 15 o.7M){2z.2o("22-1u");h(4w&&4N){14.2g=1H(13)+" "+14.2g}}h(2Y 15 6C){2z.2o(6C[2Y])}h(o.3K[3C]){2z.2o("E-1G-3R")};h(2e==2Y){14.A=o.A+"-E-1G-3O"};14.v=2z.5x(" ");h(o.47||o.4a){16(k 2H=0,1O;1O=6f[2H];2H++){h(1O=="57"){14.18(q.2h(T))}J{5L=5N.9z(5N);5L.18(q.2h(3m(17 1e(+1a(2r).K(0,4),+1a(2r).K(4,2)-1,+T),1O,R)));14.18(5L)}}}J{14.18(q.2h(T))};h(o.1X){4g[1M]=2d.5y(2z[0]=="1D-3Q"?3:1,4g[1M])}}}J{14.v="E-1G-82";14.18(q.2h(3Y));14.2g=""};h(o.1X&&3A-(1M*7)==6){2m(o.5e[1M].2p)o.5e[1M].3B(o.5e[1M].2p);o.5e[1M].18(q.2h(4g[1M]==4&&!o.46?3Y:83(cy,cm,3A-4h-6)));o.5e[1M].v="E-1G-3S-5f"+(["",""," 3Q-58-1A"," 1D-3Q",""][4g[1M]])}};o.7N=o.47||o.4a;k 1n=o.5P.26("1n");2m(1n[0].2p)1n[0].3B(1n[0].2p);2m(1n[1].2p)1n[1].3B(1n[1].2p);1n[0].18(q.2h(9C(cm,G)+3Y));1n[1].18(q.2h(cy));h(o.5A){o.5Q=50+2d.4i(((o.5Q-50)/1.8));o.5C=1E.6A(o.2l,o.5Q)};o.6o=G;o.5J()};c.6K=B(4O){h(c.1y){u};k C=c.4e();h(!C||(C&&C.1u)){u};c.1Y=R;h(!q.1j(\'1m-\'+c.A)){c.2k=G;c.5E=G;c.2A();c.5E=R}J{c.4c();c.6s()};c.1Y=!!!4O;h(c.1Y){2j(q,"4P",c.2M)};c.2l();c.3L=c.5D;c.Q.1h.2W="6t";/*@1U@h(@4K<=5.7)h(!o.4b){c.1L.1h.7T=c.Q.6w+"3x";c.1L.1h.7U=c.Q.5G+"3x";c.1L.1h.2W="6t"};@2i@*/c.5J();c.5g();k 4j=q.1j(\'1m-I-\'+c.A);h(4j){4j.v=4j.v.Z("1q-3T-5h","")+" 1q-3T-5h"}};c.3D=B(){h(!c.3g||!c.2k||!q.1j(\'1m-\'+c.A))u;c.3n();c.5R();h(c.1y){u};k 4j=q.1j(\'1m-I-\'+c.A);h(4j)4j.v=4j.v.Z("1q-3T-5h","");1V(q,"4P",c.2M);/*@1U@h(@4K<=5.7)h(!c.4b){c.1L.1h.2W="6L"};@2i@*/c.3L=0;c.5g();c.Q.v=c.Q.v.Z("4k-4M","");h(c.2B){c.4Q(1H(9))}};c.4R=B(){h(q.1j("1m-I-"+c.A)){q.1j("1m-I-"+c.A).2b.3B(q.1j("1m-I-"+c.A))};h(!c.2k){u};1V(c.1C,"4P",o.2M);1V(c.1C,"c5",o.4S);1V(c.1C,"84",o.4T);1V(q,"4P",o.2M);1V(q,"5i",o.4U);o.5R();5S(o.5B);5S(o.5C);/*@1U@h(@4K<=5.7)h(!o.1y&&!o.4b){2T{o.1L.2b.3B(o.1L);o.1L=1d}2U(2R){}};@2i@*/h(c.Q&&c.Q.2b){c.Q.2b.3B(c.Q)};o=1d};c.9D=B(){o.Q.1h.7T=o.1C.6w+"3x";o.Q.1h.7U=o.1C.5G+"3x"};c.2A=B(){h(c.2k){u};c.1Y=R;B 5T(2N){k 23=q.1N(\'23\');h(2N.6M)23.v=2N.6M;h(2N.4V){/*@1U/*@h(@3e)23.2S(\'c6\',2N.4V);@J@*/23.2S(\'4V\',2N.4V);/*@2i@*/};/*@1U/*@h(@3e)23.5U="59";/*@2i@*/u 23};B 85(1S,1f){16(k i=0,2N;2N=1f[i];i++){k 23=5T(2N);1S.18(23);k I=q.1N(\'1n\');I.v=2N.v;I.A=o.A+2N.A;I.18(q.2h(2N.43||o.3Y));I.2g=2N.2g||"";/*@1U/*@h(@3e)23.5U=I.5U="59";/*@2i@*/23.18(I)}};c.Q=q.1N(\'Q\');c.Q.A="1m-"+c.A;c.Q.v="1p";c.Q.1h.4L="3j";c.Q.1h.2W="6L";h(q.1j("1m-4k-7I-6N")){2x(c.Q,"6N","1m-4k-7I-6N")};h(c.7L){2x(c.Q,"c7",c.7L.A)};k 1S,1M,1k,4W,5V,6O;c.1C=q.1N(\'1C\');c.1C.v="c8";c.1C.4S=c.4S;c.1C.4T=c.4T;c.1C.4l=c.4l;h(c.1y){c.1C.2M=c.2M};c.Q.18(c.1C);k 5j=!c.4G?" 5W-6P":"";h(!c.1y){c.Q.1h.4L="3j";c.Q.v+=5j;q.26(\'3M\')[0].18(c.Q);/*@1U@h(@4K<=5.7)h(!c.4b){c.1L=q.1N(\'c9\');c.1L.6g="9a:\'<9E></9E>\';";c.1L.2S(\'v\',\'ca\');c.1L.2S("3k",-1);3s(c.1L,"86");2x(c.1L,"3j","R");c.1L.cb="5k";c.1L.ce="0";c.1L.cf=c.1L.A=c.A+"-cg";q.3M.18(c.1L)};@2i@*/2x(c.Q,"3j","R")}J{C=c.2K?q.1j(c.2K):c.4e();h(!C){c.Q=1d;ch c.2K?"9F 6J 9G a U 9H 9k 1v 6Q an A:"+c.2K:"9F 6J 9G a U 9H 2n 6Q an A:"+c.A;};c.Q.v+=" ci-4k";h(c.2K){C.18(c.Q)}J{C.2b.9I(c.Q,C.87)};h(c.5b){k 4m=[C];h(c.3u){4m[4m.X]=q.1j(c.A+2v[1]);4m[4m.X]=q.1j(c.A+2v[0])};16(k i=0;i<4m.X;i++){h(4m[i].1B)4m[i].v+=" 1m-3j-2n"}};6A(c.9D,cj)};3s(c.Q,"88");h(c.2V){6O=q.1N(\'9J\');c.1C.18(6O);1S=q.1N(\'1S\');1S.v="E-1G-9J";6O.18(1S);c.2B=5T({6M:"E-1G-ck"+5j,4V:c.1X?8:7});1S.18(c.2B);c.4Q()};4W=q.1N(\'9K\');c.1C.18(4W);1S=q.1N(\'1S\');3s(1S,"86");4W.18(1S);c.5P=5T({6M:"E-1G-2g"+5j,4V:c.1X?8:7});1S.18(c.5P);1S=1d;k 1n=q.1N(\'1n\');1n.18(q.2h(3Y));1n.v="1D-2W"+5j;c.5P.18(1n);1n=q.1N(\'1n\');1n.18(q.2h(3Y));1n.v="25-2W"+5j;c.5P.18(1n);1n=1d;1S=q.1N(\'1S\');3s(1S,"86");4W.18(1S);85(1S,[{v:"2C-I 2C-25",A:"-2C-25-I",43:"\\cl",2g:1H(2)},{v:"2C-I 2C-1D",A:"-2C-1D-I",43:"\\cn",2g:1H(0)},{4V:c.1X?4:3,v:"21-I",A:"-21-I",43:1H(4)},{v:"2D-I 2D-1D",A:"-2D-1D-I",43:"\\co",2g:1H(1)},{v:"2D-I 2D-25",A:"-2D-25-I",43:"\\cp",2g:1H(3)}]);5V=q.1N(\'6R\');c.1C.18(5V);k 5X=c.1X?8:7,5l=c.1X?0:-1,I,9t;16(k 3E=0;3E<7;3E++){1M=q.1N(\'1S\');h(3E!=0){3s(1M,"1M");5V.18(1M)}J{4W.18(1M)};16(k 4n=0;4n<5X;4n++){h(3E===0||(c.1X&&4n===0)){1k=q.1N(\'23\')}J{1k=q.1N(\'14\');1k.8a=c.8a;1k.8b=c.8b;2x(1k,"6N",c.A+"-1k-"+4n+(c.1X?" "+c.A+"-1M-"+3E:""));2x(1k,"6I","G")};/*@1U@*//*@h(@3e)1k.5U="59";/*@2i@*/1M.18(1k);h((c.1X&&4n>0&&3E>0)||(!c.1X&&3E>0)){3s(1k,"cq")}J{h(3E===0&&4n>5l){1k.v="E-1G-22-5f";1k.9L="1k";3s(1k,"cr");1k.A=c.A+"-1k-"+4n}J{1k.v="E-1G-3S-5f";1k.9L="1M";3s(1k,"cs");1k.A=c.A+"-1M-"+3E}}}};1k=1M=1d;c.2E=c.1C.26(\'9K\')[0].26(\'1S\')[2].26(\'23\');16(k y=0;y<5X;y++){h(y==0&&c.1X){c.2E[y].18(q.2h(1H(6)));c.2E[y].2g=1H(8);2s};h(y>(c.1X?0:-1)){I=q.1N("1n");I.v="1m-22-5f";/*@1U@*//*@h(@3e)I.5U="59";/*@2i@*/c.2E[y].18(I)}};I=1d;c.ct=c.1C.26(\'6R\')[0].26(\'1S\');c.81=c.1C.26(\'6R\')[0].26(\'14\');c.6S=q.1j(c.A+"-2C-25-I");c.6T=q.1j(c.A+"-2C-1D-I");c.5Y=q.1j(c.A+"-21-I");c.6U=q.1j(c.A+"-2D-25-I");c.6V=q.1j(c.A+"-2D-1D-I");h(c.4I){c.5Y.1h.2W="6L"};h(c.1X){c.5e=c.1C.26(\'6R\')[0].26(\'23\');c.Q.v+=" cu-cv"};5V=4W=1S=85=5T=1d;h(c.1F&&c.1W&&(c.1W-c.1F<7)){c.9M()};c.4c();c.6W();c.2k=R;c.6F("2A",{A:c.A});c.2l();h(c.1y){c.3g=R;c.3t=c.3L;c.Q.1h.4L="3g";c.Q.1h.2W="6t";c.1Y=R;c.5g()}J{c.6s();c.Q.1h.4L="3g";c.5g();c.1Y=R};c.4a=G};c.5g=B(){1E.5S(o.5B);o.5B=1d;k 8c=2d.4i(o.3t+((o.3L-o.3t)/4));o.8d(8c);h(2d.6z(o.3L-8c)>3&&!o.4H){o.5B=1E.6A(o.5g,50)}J{o.8d(o.3L);h(o.3L==0){o.Q.1h.2W="6L";o.Q.1h.4L="3j";2x(o.Q,"3j","R");o.3g=G}J{2x(o.Q,"3j","G");o.3g=R}}};c.8e=B(e){e=e||1E.3r;k 8f=(e.6X?e.6X:e.6Y?e.6Y:e.x)-o.7J;k 8g=(e.6Z?e.6Z:e.70?e.70:e.Y)-o.7K;o.Q.1h.4f=2d.4i(o.x+8f)>0?2d.4i(o.x+8f)+\'3x\':"7R";o.Q.1h.3J=2d.4i(o.y+8g)>0?2d.4i(o.y+8g)+\'3x\':"7R";/*@1U@h(@4K<=5.7)h(o.1y||o.4b)u;o.1L.1h.3J=o.Q.1h.3J;o.1L.1h.4f=o.Q.1h.4f;@2i@*/};c.8h=B(e){1V(q,\'9N\',o.8e,G);1V(q,\'5i\',o.8h,G);o.Q.1h.9O=cw};c.2M=B(e){e=e||q.4D.3r;k V=e.4o!=1d?e.4o:e.71,5m=V,8i=R,9P=17 5z("^1m-(I-)?"+o.A+"$");o.5Z=1d;2m(V){h(V.A&&V.A.X&&V.A.L(9P)!=-1){8i=G;1l};2T{V=V.2b}2U(2R){1l}};h(8i){60();u R};h((o.Q.v+5m.v).L(\'1m-1u\')!=-1){u R};h(5m.A.L(17 5z("^"+o.A+"(-2C-25-I|-2C-1D-I|-2D-1D-I|-2D-25-I)$"))!=-1){o.5Z=5m;2j(q,"5i",o.4U);2j(5m,"84",o.4U);k 72={"-2C-25-I":[0,-1,0],"-2C-1D-I":[0,0,-1],"-2D-25-I":[0,1,0],"-2D-1D-I":[0,0,1]},73=5m.A.Z(o.A,""),8j=1Q(o.E.1s()+1i(o.E.1r()+1));o.5Q=(o.5O>8j||o.5O<8j)?cx:9Q;o.5A=R;o.6n=72[73][0];o.4E=72[73][1];o.4F=72[73][2];o.4a=G;o.2l()}J h(V.v.L("5W-6P")!=-1){o.7J=e.6X?e.6X:e.6Y?e.6Y:e.x;o.7K=e.6Z?e.6Z:e.70?e.70:e.Y;o.x=2X(o.Q.1h.4f);o.y=2X(o.Q.1h.3J);2j(q,\'9N\',o.8e,G);2j(q,\'5i\',o.8h,G);o.Q.1h.9O=cz};u R};c.4l=B(e){h(o.3t!=o.3L||o.1u)u 2w(e);e=e||q.4D.3r;k V=e.4o!=1d?e.4o:e.71;2m(V.2b){h(V.1B&&V.1B.2a()=="14"){h(V.v.L(/cd-([0-9]{8})/)==-1||V.v.L(/E-1G-82|3Q-58-1A|22-1u|5k-9R|6J-4N/)!=-1)u 2w(e);k 4p=V.v.1z(/cd-([0-9]{8})/)[1];o.E=17 1e(4p.K(0,4),4p.K(4,2)-1,4p.K(6,2));o.2y=17 1e(o.E);o.1Y=R;o.74();o.3D();o.3n();1l}J h(V.A&&V.A==o.A+"-21-I"){o.E=17 1e();o.2l();o.3n();1l}J h(V.v.L(/E-1G-22-5f/)!=-1){k 8k=o.1X?-1:0,C=V;2m(C.9S){C=C.9S;h(C.1B.2a()=="23")8k++};o.2G=(o.2G+8k)%7;o.6W();1l};2T{V=V.2b}2U(2R){1l}};u 2w(e)};c.8a=B(e){e=e||q.4D.3r;k V=e.4o!=1d?e.4o:e.71;2m(V.2b){h(V.A&&V.A=="1m-"+o.A){u R};2T{V=V.2b}2U(2R){1l}};h(o.47)o.5R();o.Q.v=o.Q.v.Z("4k-4M","");o.1Y=R;o.4a=G;o.3D();h(o.2B){o.4Q(1H(9))}};c.8b=B(e){h(o.1y){o.1Y=G;h(!o.7N){o.4a=R;o.2l()}};o.9T()};c.3o=B(e){o.3n();h(!o.3g)u G;h(e==1d)e=q.4D.3r;k 1w=e.75?e.75:e.9U;h(1w==13){k 14=q.1j(o.A+"-E-1G-3O");h(!14||14.v.L(/cd-([0-9]{8})/)==-1||14.v.L(/5k-9R|3Q-58-1A|22-1u/)!=-1){u 2w(e)};o.2y=17 1e(o.E);o.74();o.3D();u 2w(e)}J h(1w==27){o.3D();u 2w(e)}J h(1w==32||1w==0){o.E=17 1e();o.2l();u 2w(e)};/*@1U@h(@3e)h(17 1e().76()-o.6p.76()<50){u 2w(e)};o.6p=17 1e();@2i@*/h((1w>49&&1w<56)||(1w>97&&1w<cA)){h(1w>96)1w-=(96-48);1w-=49;o.2G=(o.2G+1w)%7;o.6W();u 2w(e)};h(1w<33||1w>40)u R;k d=17 1e(o.E),2O,8l=o.E.1s()+1i(o.E.1r()+1);h(1w==36){d.3y(1)}J h(1w==35){d.3y(2L(d.1r(),d.1s()))}J h(1w==33||1w==34){k 77=(1w==34)?1:-1;h(e.9V){d.7V(d.1s()+77)}J{h(!((1w==33&&o.5O>8l)||(1w==34&&o.5O<8l))){2O=17 1e(d);2O.3y(2);2O.5K(d.1r()+77);d.3y(2d.5y(d.1R(),2L(2O.1r(),2O.1s())));d.5K(d.1r()+77)}}}J h(1w==37){d=17 1e(o.E.1s(),o.E.1r(),o.E.1R()-1)}J h(1w==39||1w==34){d=17 1e(o.E.1s(),o.E.1r(),o.E.1R()+1)}J h(1w==38){d=17 1e(o.E.1s(),o.E.1r(),o.E.1R()-7)}J h(1w==40){d=17 1e(o.E.1s(),o.E.1r(),o.E.1R()+7)};h(o.3z(d)){u 2w(e)};o.E=d;h(o.2B){o.4Q(3m(o.E,o.2V,R))};k t=1a(o.E.1s())+1i(o.E.1r()+1)+1i(o.E.1R());h(e.9V||(1w==33||1w==34)||t<o.2Z||t>o.3a){o.2l();/*@1U@h(@3e)o.6p=17 1e();@2i@*/}J{h(!o.4I){o.6B()};o.5H();k T="cd-"+o.E.1s()+1i(o.E.1r()+1)+1i(o.E.1R());16(k i=0,14;14=o.81[i];i++){h(14.v.L(T)==-1){2s};o.7W(o.E);14.A=o.A+"-E-1G-3O";o.5J();1l}};u 2w(e)};c.4T=B(e){e=e||q.4D.3r;k p=e.cB||e.cC;2m(p&&p!=c)2T{p=p.2b}2U(e){p=c};h(p==c)u G;h(o.4X){o.4X.v="";o.4X=1d};h(o.2B){o.4Q(3m(o.E,o.2V,R))}};c.4S=B(e){e=e||q.4D.3r;k V=e.4o!=1d?e.4o:e.71;2m(V.9W!=1){V=V.2b};h(!V||!V.1B){u};k 2t=1H(9);7G(V.1B.2a()){1t"14":h(V.v.L(/E-1G-82|3Q-58-1A/)!=-1){2t=1H(9)}h(V.v.L(/cd-([0-9]{8})/)!=-1){o.3n();k 4p=V.v.1z(/cd-([0-9]{8})/)[1];o.5H();V.A=o.A+"-E-1G-3O";o.5J();o.E=17 1e(+4p.K(0,4),+4p.K(4,2)-1,+4p.K(6,2));h(!o.4I){o.6B()};2t=3m(o.E,o.2V,R)};1l;1t"23":h(!o.2B){1l};h(V.v.L(/5W-6P/)!=-1){2t=1H(10)}J h(V.v.L(/E-1G-3S-5f/)!=-1){k 4q=V.2p?V.2p.cD:"";2t=4q.L(/^(\\d+)$/)!=-1?1H(7,[4q,4q<3&&o.E.1r()==11?8m(o.E.1s())+1:8m(o.E.1s())]):1H(9)};1l;1t"1n":h(!o.2B){1l};h(V.v.L(/5W-6P/)!=-1){2t=1H(10)}J h(V.v.L(/22-([0-6])/)!=-1){k 22=V.v.1z(/22-([0-6])/)[1];2t=1H(11,[61(22,G)])}J h(V.v.L(/2C-25/)!=-1){2t=1H(2)}J h(V.v.L(/2C-1D/)!=-1){2t=1H(0)}J h(V.v.L(/2D-25/)!=-1){2t=1H(3)}J h(V.v.L(/2D-1D/)!=-1){2t=1H(1)}J h(V.v.L(/21-I/)!=-1&&V.v.L(/1u/)==-1){2t=1H(12)};1l;9X:2t=""};2m(V.2b){V=V.2b;h(V.9W==1&&V.1B.2a()=="1S"){h(o.4X){h(V==o.4X)1l;o.4X.v=""};V.v="1q-1M-3R";o.4X=V;1l}};h(o.2B&&2t){o.4Q(2t)}};c.4U=B(){o.3n();o.5Q=9Q;o.4E=0;o.4F=0;o.6n=0;1V(q,"5i",o.4U);h(o.5Z!=1d){1V(o.5Z,"84",o.4U)};o.5Z=1d};k o=c;h(c.1y){c.2A()}J{c.8n()};c.4c();(B(){k C=o.4e();h(C&&C.1B&&C.1B.L(/3U|2n/i)!=-1){2j(C,"8o",o.6r);h(c.3u){2j(q.1j(o.A+2v[1]),"8o",o.6r);2j(q.1j(o.A+2v[0]),"8o",o.6r)}};h(!C||C.1u==R){o.8p()}})();c.5E=R};1p.1x.8q=B(I){I.3o=I.4l=B(e){e=e||1E.3r;k 78=c.A.Z(\'1m-I-\',\'\'),8r=9Y(78),4O=G;h(e.1o=="79"){k 1w=e.75!=1d?e.75:e.9U;h(1w!=13)u R;h(8r){c.v=c.v.Z("1q-3T-5h","");60();u G};4O=R};c.v=c.v.Z("1q-3T-5h","");h(!8r){c.v+=" 1q-3T-5h";60(78);8s(78,4O)}J{60()};u G};h(!7y){I.2S(!/*@1U!@*/G?"3k":"5I","-1");I.3k=-1;I.3o=1d}J{I.2S(!/*@1U!@*/G?"3k":"5I","0");I.3k=0}};1p.1x.8n=B(){h(c.1y||q.1j("1m-I-"+c.A)){u};k 3b=c.4e(),1n=q.1N(\'1n\'),I=q.1N(\'a\');I.cE="#"+c.A;I.v="E-1G-cF";I.2g=1H(5);I.A="1m-I-"+c.A;1n.18(q.2h(3Y));I.18(1n);1n=q.1N(\'1n\');1n.v="1m-9x-9y";1n.18(q.2h(I.2g));I.18(1n);3s(I,"3T");2x(I,"cG",R);h(c.44&&q.1j(c.44)){q.1j(c.44).18(I)}J h(3b.87){3b.2b.9I(I,3b.87)}J{3b.2b.18(I)};c.8q(I);I=1d};1p.1x.8t=B(1A){c.1F=(1a(1A).L(/^(\\d\\d\\d\\d)(0[1-9]|1[2P])(0[1-9]|[12][0-9]|3[2f])$/)==-1)?G:1A;c.62();h(c.2k){c.2l()}};1p.1x.8u=B(1A){c.1W=(1a(1A).L(/^(\\d\\d\\d\\d)(0[1-9]|1[2P])(0[1-9]|[12][0-9]|3[2f])$/)==-1)?G:1A;c.62();h(c.2k){c.2l()}};1p.1x.cH=B(9Z){c.2I=9Z;c.62();h(c.2k){c.2l()}};1p.1x.8v=B(3V){c.3h={};c.7a(3V)};1p.1x.7a=B(3V){k cI={};h(2q 3V!=="3I")3V=[3V];16(k i=3V.X;i--;){h(3V[i].1z(/^(\\d\\d\\d\\d|\\*\\*\\*\\*)(0[1-9]|1[2P]|\\*\\*)(0[1-9]|[12][0-9]|3[2f])$/)!=-1){c.3h[3V[i]]=1}};c.62();h(c.2k){c.2l()}};1p.1x.62=B(){h(!c.2y)u;h(!c.7b(c.2y)){c.2y=1d}};1p.1x.9T=B(){h(c.47||c.1Y){u};c.Q.v=c.Q.v.Z(/4k-4M/,"")+" 4k-4M";2j(q,"7c",c.3o);2j(q,"4P",c.2M);/*@1U@h(@3e)1V(q,"7c",c.3o);2j(q,"79",c.3o);@2i@*/h(1E.cJ){1V(q,"7c",c.3o);2j(q,"79",c.3o)};c.1Y=G;c.47=R};1p.1x.5R=B(){h(!c.47){u};c.Q.v=c.Q.v.Z(/4k-4M/,"");1V(q,"7c",c.3o);1V(q,"79",c.3o);1V(q,"4P",c.2M);c.1Y=R;c.47=G};1p.1x.3n=B(){c.5A=G;1E.5S(c.5C)};1p.1x.8d=B(7d){c.Q.1h.3t=7d/8w;c.Q.1h.cK=\'cL(3t=\'+7d+\')\';c.3t=7d};1p.1x.4e=B(){u q.1j(c.A.Z(/^1m-/,\'\'))||G};1p.1x.6E=B(y,m){m=1i(m);k 1f={},3F=c.2Z,3G=c.3a,1I,1Z,4r,4s;h(!3G||!3F){3F=c.2Z=y+1i(m)+"2f";3G=c.3a=y+1i(m)+1i(2L(m,y))};16(T 15 c.2J){1I=T.Z(/^(\\*\\*\\*\\*)/,y).Z(/^(\\d\\d\\d\\d)(\\*\\*)/,"$1"+m);1Z=c.2J[T];h(1Z==1){1f[1I]=1;2s};h(1Q(1I.K(0,6))==1Q(1Z.K(0,6))){16(k i=1I;i<=1Z;i++){1f[i]=1};2s};4r=1Q(1I.K(0,6))==+1a(c.2Z).K(0,6)?1I:3F;4s=1Q(1Z.K(0,6))==+1a(c.3a).K(0,6)?1Z:3G;16(k i=+4r;i<=+4s;i++){1f[i]=1}};u 1f};1p.1x.6H=B(y,m){m=1i(m);k 1f={},3F=c.2Z,3G=c.3a,1I,1Z,4r,4s;h(!3G||!3F){3F=c.2Z=y+1i(m)+"2f";3G=c.3a=y+1i(m)+1i(2L(m,y))};16(k T 15 c.3h){1I=T.Z(/^(\\*\\*\\*\\*)/,y).Z(/^(\\d\\d\\d\\d)(\\*\\*)/,"$1"+m);1Z=c.3h[T];h(1Z==1){h(+3F<=+1I&&+3G>=+1I){1f[1I]=1};2s};h(1Q(1I.K(0,6))<=+1a(c.2Z).K(0,6)&&1Q(1Z.K(0,6))>=+1a(c.3a).K(0,6)){h(1Q(1I.K(0,6))==1Q(1Z.K(0,6))){16(k i=1I;i<=1Z;i++){1f[i]=1};2s};4r=1Q(1I.K(0,6))==+1a(c.2Z).K(0,6)?1I:3F;4s=1Q(1Z.K(0,6))==+1a(c.3a).K(0,6)?1Z:3G;16(k i=+4r;i<=+4s;i++){1f[i]=1}}};16(T 15 c.2J){1I=T.Z(/^(\\*\\*\\*\\*)/,y).Z(/^(\\d\\d\\d\\d)(\\*\\*)/,"$1"+m);1Z=c.2J[T];h(1Z==1){h(1I 15 1f){1f[1I]=1d;5n 1f[1I]};2s};h(1Q(1I.K(0,6))<=+1a(c.2Z).K(0,6)&&1Q(1Z.K(0,6))>=+1a(c.3a).K(0,6)){h(1Q(1I.K(0,6))==1Q(1Z.K(0,6))){16(k i=1I;i<=1Z;i++){h(i 15 1f){1f[i]=1d;5n 1f[i]}};2s};4r=1Q(1I.K(0,6))==+1a(c.2Z).K(0,6)?1I:3F;4s=1Q(1Z.K(0,6))==+1a(c.3a).K(0,6)?1Z:3G;16(k i=+4r;i<=+4s;i++){h(i 15 1f){1f[i]=1d;5n 1f[i]}}}};u 1f};1p.1x.9q=B(1v){k 3w=c.a0(1v);h(1E.6k){u 3w};k 8x=(q.6y&&q.6y!="9r")?q.3i:q.3M,a1=q.a2?8x.3N:1E.9p,a3=q.a2?8x.4d:1E.7Q,8y=c.a4(1v);u[3w[0]-8y[0]+a1,3w[1]-8y[1]+a3]};1p.1x.a4=B(1v){k t=0,l=0;a5{t+=1v.4d||0;l+=1v.3N||0;1v=1v.2b}2m(1v);u[l,t]};1p.1x.a0=B(1v){k t=0,l=0;a5{t+=1v.cM||0;l+=1v.cN||0;1v=1v.cO}2m(1v);u[l,t]};1p.1x.9M=B(){k 8z=G,1g;16(k i=c.1F;i<=c.1W;i++){1g=1a(i);h(!c.2I[17 1e(1g.K(0,4),1g.K(6,2),1g.K(4,2)).3P()-1]){8z=R;1l}};h(!8z){c.2I=[0,0,0,0,0,0,0]}};1p.1x.3z=B(1g){h(!c.1F&&!c.1W){u G};k 7e=G;h(!1g){7e=R;1g=c.E};k d=1i(1g.1R()),m=1i(1g.1r()+1),y=1g.1s(),T=1a(y)+1a(m)+1a(d);h(c.1F&&+T<+c.1F){h(!7e){u R};c.E=17 1e(c.1F.K(0,4),c.1F.K(4,2)-1,c.1F.K(6,2),5,0,0);u G};h(c.1W&&+T>+c.1W){h(!7e){u R};c.E=17 1e(c.1W.K(0,4),c.1W.K(4,2)-1,c.1W.K(6,2),5,0,0)};u G};1p.1x.7b=B(1g){h(!1g)u G;k d=1i(1g.1R()),m=1i(1g.1r()+1),y=1g.1s(),T=1a(y)+1a(m)+1a(d),dd=c.6H(+y,+m),a6=c.6E(+y,+m),a7=3m(1g,"N");h((c.1F&&+T<+c.1F)||(c.1W&&+T>+c.1W)||(T 15 dd)||(c.2I[a7-1]&&!(T 15 a6))){u G};u R};1p.1x.4Q=B(4t){2m(c.2B.2p){c.2B.3B(c.2B.2p)};h(4t&&c.2V.L(/-S|S-/)!=-1&&4t.L(/([0-9]{1,2})(63|3H|64|23)/)!=-1){4t=4t.Z(/([0-9]{1,2})(63|3H|64|23)/,"$1<4u>$2</4u>").3f(/<4u>|<\\/4u>/);k dc=q.cP();16(k i=0,3H;3H=4t[i];i++){h(/^(63|3H|64|23)$/.5a(3H)){k 4u=q.1N("4u");4u.18(q.2h(3H));dc.18(4u)}J{dc.18(q.2h(3H))}};c.2B.18(dc)}J{c.2B.18(q.2h(4t?4t:1H(9)))}};1p.1x.4c=B(){c.2y=1d;k C=c.4e(),7f=G,T;h(!C||C.1B.L(/3U|2n/i)==-1)u;h(!c.3u&&C.1b.Z(/\\s/g,"")!==""){k a8=7B.a9([c.45]).cQ();16(k i=0,3W;3W=a8[i];i++){T=7g(C.1b,3W);h(T){7f=R;1l}}}J h(c.3u){k 65=q.1j(c.A+2v[1]),66=q.1j(c.A+2v[0]),5o=2X(65.1B.2a()=="2n"?65.1b:65.H[65.7h||0].1b,10),14=2X(66.1B.2a()=="2n"?66.1b:66.H[66.7h||0].1b,10),5p=2X(C.1B.2a()=="2n"?C.1b:C.H[C.7h||0].1b,10);h(!(/\\d\\d\\d\\d/.5a(5p))||!(/^(0?[1-9]|1[2P])$/.5a(5o))||!(/^(0?[1-9]|[12][0-9]|3[2f])$/.5a(14))){T=G}J{h(+14>2L(+5o-1,+5p)){7f=R;14=2L(+5o-1,+5p);T=17 1e(5p,5o-1,14)}J{T=17 1e(5p,5o-1,14)}}};h(!T||7i(T)){c.E=c.2e?17 1e(+c.2e.K(0,4),+c.2e.K(4,2)-1,+c.2e.K(6,2)):17 1e();c.E.6q(5);c.3z();u};T.6q(5);c.E=17 1e(T);c.3z();h(T.76()==c.E.76()&&c.7b(c.E)){c.2y=17 1e(c.E)};h(7f){c.74(R)}};1p.1x.7j=B(C,aa){16(k 67=C.H.X-1;67>=0;67--){h(C.H[67].1b==+aa){C.7h=67;u}}};1p.1x.74=B(1Y){k C=c.4e();h(!C||c.2y==1d)u;1Y=!!1Y;k d=1i(c.E.1R()),m=1i(c.E.1r()+1),3l=c.E.1s(),3h=c.6H(+3l,+m),2J=c.6E(+3l,+m),3C=(c.E.3P()+6)%7,T=1a(3l)+1a(m)+1a(d);h(!(c.2I[3C]&&!(T 15 2J))||!(1a(3l)+m+d 15 c.3h)){h(c.3u){k 68=q.1j(c.A+2v[0]),69=q.1j(c.A+2v[1]),ab=C.1b,ac=69.1b,ad=68.1b;h(+ab==+3l&&+ac==+m&&+ad==+d){u};h(68.1B.2a()=="2n"){68.1b=d}J{c.7j(68,d)};h(69.1B.2a()=="2n"){69.1b=m}J{c.7j(69,m)};h(C.1B.2a()=="2n")C.1b=3l;J{c.7j(C,3l)}}J h(C.1B.2a()=="2n"){k ae=C.1b,8A=3m(c.E,c.45,6e);h(ae==8A){u};C.1b=8A};h(c.1y){c.1Y=R;c.2l();c.1Y=G};h(c.5E){h(C.1o&&C.1o!="3j"&&!1Y){C.4M()};c.6F("7k",{"A":c.A,"E":c.2y,"dd":d,"7z":m,"3l":3l})}}};1p.1x.8p=B(){h(c.1u)u;h(c.1y){c.5R();c.1Y=R;c.Q.v=c.Q.v.Z(/1q-1u/,"")+" 1q-1u";c.1C.4S=c.1C.4l=c.1C.4T=c.1C.2M=1d;1V(q,"4P",c.2M);1V(q,"5i",c.4U)}J{h(c.3g)c.3D();k I=q.1j("1m-I-"+c.A);h(I){I.v=I.v.Z(/1q-1u/,"")+" 1q-1u";2x(I,"1u",R);I.3o=I.4l=B(){u G};I.2S(!/*@1U!@*/G?"3k":"5I","-1");I.3k=-1}};5S(c.5C);c.1u=R};1p.1x.af=B(){h(!c.1u)u;h(c.1y){c.5H();c.1Y=R;c.4a=R;c.2l();c.Q.v=c.Q.v.Z(/1q-1u/,"");c.1u=G;c.1C.4S=c.4S;c.1C.4T=c.4T;c.1C.4l=c.4l;c.1C.2M=c.2M}J{k I=q.1j("1m-I-"+c.A);h(I){I.v=I.v.Z(/1q-1u/,"");2x(I,"1u",G);c.8q(I)}};c.1u=G};1p.1x.6B=B(){k 21=17 1e();c.5Y.v=c.5Y.v.Z("1m-1u","");h(c.3z(21)||(c.E.1R()==21.1R()&&c.E.1r()==21.1r()&&c.E.1s()==21.1s())){c.5Y.v+=" 1m-1u"}};1p.1x.6W=B(){k 5X=c.1X?8:7,5l=c.1X?1:0,d,I;16(k 1k=5l;1k<5X;1k++){d=(c.2G+(1k-5l))%7;c.2E[1k].2g=61(d,G);h(1k>5l){I=c.2E[1k].26("1n")[0];2m(I.2p){I.3B(I.2p)};I.18(q.2h(61(d,R)));I.2g=c.2E[1k].2g;I.v=I.v.Z(/22-([0-6])/,"")+" 22-"+d;I=1d}J{2m(c.2E[1k].2p){c.2E[1k].3B(c.2E[1k].2p)};c.2E[1k].18(q.2h(61(d,R)))};c.2E[1k].v=c.2E[1k].v.Z(/E-1G-3R/g,"");h(c.3K[d]){c.2E[1k].v+=" E-1G-3R"}};h(c.2k){c.2l()}};1p.1x.6F=B(1o,ag){h(!1o||!(1o 15 c.3v))u G;k 7l=G;16(k 3X=0;3X<c.3v[1o].X;3X++){7l=c.3v[1o][3X](ag||c.A);h(!7l)u G};u 7l};1p.1x.7W=B(1g){k 4Y=1g.1r(),4Z=1g.1s();c.6S.v=c.6S.v.Z("1m-1u","");h(c.3z(17 1e((4Z-1),4Y,2L(+4Y,4Z-1)))){c.6S.v+=" 1m-1u";h(c.4E==-1)c.3n()};c.6T.v=c.6T.v.Z("1m-1u","");h(c.3z(17 1e(4Z,(+4Y-1),2L(+4Y-1,4Z)))){c.6T.v+=" 1m-1u";h(c.4F==-1)c.3n()};c.6U.v=c.6U.v.Z("1m-1u","");h(c.3z(17 1e((4Z+1),+4Y,1))){c.6U.v+=" 1m-1u";h(c.4E==1)c.3n()};c.6V.v=c.6V.v.Z("1m-1u","");h(c.3z(17 1e(4Z,+4Y+1,1))){c.6V.v+=" 1m-1u";h(c.4F==1)c.3n()}};k ah=B(51){k 1A=[];16(k i=0;i<51.H.X;i++){h(51.H[i].1b.L(/^\\d\\d\\d\\d$/)==-1){2s};h(!1A[0]||1Q(51.H[i].1b)<1A[0]){1A[0]=1Q(51.H[i].1b)};h(!1A[1]||1Q(51.H[i].1b)>1A[1]){1A[1]=1Q(51.H[i].1b)}};u 1A};k ai=B(){h(!8B.X){u[]}k 7m=[];16(k i=0;i<8B.X;i++){16(k j=0,8C;8C=8B[i][j];j++){7m[7m.X]=8C}};u 7m};k 8D=B(){k 1q;16(1q 15 U){h(!q.1j(U[1q].A)){U[1q].4R();U[1q]=1d;5n U[1q]}}};k 60=B(8E){k 1q;16(1q 15 U){h(!U[1q].2k||(8E&&8E==U[1q].A))2s;U[1q].3D()}};k aj=B(1c){h(1c 15 U){h(!U[1c].2k||U[1c].1y)u;U[1c].3D()}};k 8s=B(1c,4O){h(!(1c 15 U))u G;U[1c].6K(4O);u R};k 4R=B(){16(1q 15 U){U[1q].4R();U[1q]=1d;5n U[1q]};U=1d;1V(1E,\'8F\',6c.2A);1V(1E,\'ak\',6c.4R)};k al=B(A){h(A&&(A 15 U)){U[A].4R();U[A]=1d;5n U[A]}};k 1H=B(8G,52){52=52||[];h(2u.2F.X>8G){k 4q=2u.2F[8G];h(52&&52.X){16(k i=0;i<52.X;i++){4q=4q.Z("[[%"+i+"%]]",52[i])}};u 4q.Z(/[[%(\\d)%]]/g,"")};u""};k 61=B(22,7n){k 2F=2u[7n?"3Z":"4z"];u 2F.X&&2F.X>22?2F[22]:""};k 9C=B(1D,7n){k 2F=2u[7n?"4y":"4x"];u 2F.X&&2F.X>1D?2F[1D]:""};k 2L=B(6a,7o){6a=(6a+12)%12;u(((0==(7o%4))&&((0!=(7o%8w))||(0==(7o%cR))))&&6a==1)?29:[31,28,31,30,31,30,31,31,30,31,30,31][6a]};k 8m=B(Y){h(Y 15 5u){u 5u[Y]};k 8H,8I,cS;6Q(8H=17 1e(Y,0,4)){3y(1R()-(6+3P())%7)};6Q(8I=17 1e(Y,11,28)){3y(1R()+(7-3P())%7)};5u[Y]=2d.4i((8I-8H)/cT);u 5u[Y]};k 8J=B(P){h(!P)u"";k 1F=P.L(/^1A-1F-/)!=-1;P=P.Z(/1A-(1F|1W)-/,"");h(P.L(/^(\\d\\d\\d\\d)(0[1-9]|1[2P])(0[1-9]|[12][0-9]|3[2f])$/)!=-1){u P};k 1g=17 1e();h(P.L(/^21$/)!=-1){u 1g.1s()+1i(1g.1r()+1)+1i(1g.1R())};k 8K=/^(\\d)-(22|3S|1D|25)$/;h(P.L(8K)!=-1){k 1K=P.1z(8K),5q={22:0,3S:0,1D:0,25:0};5q[1K[2]]=1F?-(+1K[1]):+1K[1];1g.7V(1g.1s()+ +5q.25);1g.5K(1g.1r()+ +5q.1D);1g.3y(1g.1R()+ +5q.22+(7*+5q.3S));u!1g||7i(1g)?"":1g.1s()+1i(1g.1r()+1)+1i(1g.1R())};u""};k 83=B(y,m,d){k d=17 1e(y,m,d,0,0,0);k am=d.3P();d.3y(d.1R()-(am+6)%7+3);k ao=d.ap();d.5K(0);d.3y(4);u 2d.4i((ao-d.ap())/(7*cU))+1};k 3m=B(E,3W,53){h(!E||7i(E)){u""};k 1K=3W.3f("-"),P=[],d=E.1R(),D=E.3P(),m=E.1r(),y=E.1s(),8L={"1J":" ","T":".","1T":"/","2c":"-","cc":",","d":1i(d),"D":53?2u.3Z[D==0?6:D-1]:3c.3Z[D==0?6:D-1],"l":53?2u.4z[D==0?6:D-1]:3c.4z[D==0?6:D-1],"j":d,"N":D==0?7:D,"w":D,"W":83(E),"M":53?2u.4y[m]:3c.4y[m],"F":53?2u.4x[m]:3c.4x[m],"m":1i(m+1),"n":m+1,"t":2L(m+1,y),"Y":y,"o":y,"y":1a(y).K(2,2),"S":["23","63","3H","64"][d%10>3?0:(d%8w-d%10!=10)*d%10]};16(k 2H=0,1O;1O=1K[2H];2H++){P.2o(!(1O 15 8L)?"":8L[1O])};u P.5x("")};k 7g=B(P,3W){k d=G,m=G,y=G,7p=17 1e(),1K=3W.Z(/-1J(-1J)+/g,"-1J").3f("-"),aq={"T":".","1T":"/","2c":"-","cc":","};8M:16(k 2H=0,1O;1O=1K[2H];2H++){h(P.X==0){u G};7G(1O){1t"1J":h(P.6b(0).L(/\\s/)!=-1){2m(P.6b(0).L(/\\s/)!=-1){P=P.K(1)};1l}J u"";1t"T":1t"1T":1t"2c":1t"cc":h(P.6b(0)==aq[1O]){P=P.K(1);1l}J u"";1t"d":1t"j":h(P.L(/^(3[2f]|[12][0-9]|0?[1-9])/)!=-1){d=+P.1z(/^(3[2f]|[12][0-9]|0?[1-9])/)[0];P=P.K(P.1z(/^(3[2f]|[12][0-9]|0?[1-9])/)[0].X);1l}J u"";1t"D":1t"l":l=1O=="D"?3c.3Z:3c.4z;16(k i=0;i<7;i++){h(17 5z("^"+l[i],"i").5a(P)){P=P.K(l[i].X);2s 8M}};u"";1t"N":1t"w":h(P.L(1O=="N"?/^([1-7])/:/^([0-6])/)!=-1){P=P.K(1);1l}J u"";1t"S":h(P.L(/^(63|3H|64|23)/i)!=-1){P=P.K(2);1l}J u"";1t"z":h(P.L(/^([0-9]|[1-9][0-9]|[12][0-9]{2}|3[0-5][0-9]|36[0-5])/)!=-1){P=P.K(P.1z(/^([0-9]|[1-9][0-9]|[12][0-9]{2}|3[0-5][0-9]|36[0-5])/)[0].X);1l}J u"";1t"W":h(P.L(/^([1-9]|[ar[0-9]|5[0-3])/)!=-1){P=P.K(P.1z(/^([1-9]|[ar[0-9]|5[0-3])/)[0].X);1l}J u"";1t"M":1t"F":l=3c.4x.a9(3c.4y);16(k i=0;i<24;i++){h(P.L(17 5z("^"+l[i],"i"))!=-1){P=P.K(l[i].X);m=((i+12)%12);2s 8M}};u"";1t"m":1t"n":l=/^(1[2P]|0?[1-9])/;h(P.L(l)!=-1){m=+P.1z(l)[0]-1;P=P.K(P.1z(l)[0].X);1l}J u"";1t"t":h(P.L(/2[89]|3[2f]/)!=-1){P=P.K(2);1l}J u"";1t"Y":1t"o":h(P.L(/^(\\d{4})/)!=-1){y=P.K(0,4);P=P.K(4);1l}J u"";1t"y":h(P.L(/^(\\d{4})/)!=-1){y=P.K(0,4);P=P.K(4);1l}J h(P.L(/^(0[0-9]|[1-9][0-9])/)!=-1){y=P.K(0,2);y=+y<50?\'20\'+1a(y):\'19\'+1a(y);P=P.K(2);1l}J u"";9X:u""}};d=d===G?7p.1R():d;m=m===G?7p.1r()-1:m;y=y===G?7p.1s():y;k 1g=17 1e(y,m,d);u 7i(1g)?"":1g};k 7q=B(e){16(1q 15 U){h(!U[1q].2k||U[1q].1y||(!U[1q].1y&&!U[1q].4G))2s;U[1q].6s()}};k 9m=B(1v){k 4v;h(1v.2b&&1v.2b.1B.2a()=="4v")cV=1v.2b;J{k 5r=q.26(\'4v\');16(k 54=0;54<5r.X;54++){h((5r[54][\'as\']&&5r[54][\'as\']==1v.A)||(5r[54].cW(\'16\')==1v.A)){4v=5r[54];1l}}};h(4v&&!4v.A){4v.A=1v.A+"cX"};u 4v};k 8N=B(H){h(2q(3q)=="3I"&&!2u){2u={2F:3q.2F,4x:3q.4x,4y:3q.4y,4z:3q.4z,3Z:3q.3Z,2G:("2G"15 3q&&1a(3q.2G).L(/^([0-6]{1})$/)!=-1)?3q.2G:0,93:R}}J h(!2u){2u=3c};h(!H.A||(H.A 15 U)){u};k C=q.1j(H.A);h(!C||!C.1B||1a(C.1B).L(/^(2n|3U)$/i)==-1){u};h(!H.1y){H.5b=G}J{H.4H=R;H.4G=R};U[H.A]=17 1p(H)};k at=B(8O){h(8O==1d){u{}};k 3X,1o,5s={},1K,1f;16(k i=0,1P;1P=8O[i];i++){1o=1P.1z(/(7r(7k|6G|2A)7s)([^\\s|$]+)/i)[1].Z(/^7r/i,"").Z(/7s$/,"");1P=1P.Z(/7r(7k|6G|2A)7s/i,"").Z(/-/g,".");2T{h(1P.cY(".")!=-1){1K=1P.3f(\'.\');1f=1E;16(k x=0,1O;1O=1f[1K[x]];x++){h(1O au 6m){(B(){k av=1O;3X=B(aw){av.cZ(1f,[aw])}})()}J{1f=1O}}}J{3X=1E[1P]};h(!(3X au 6m))2s;h(!(1o 15 5s)){5s[1o]=[]};5s[1o][5s[1o].X]=3X}2U(2R){}};u 5s};k 9Y=B(A){u(!A||!(A 15 U))?G:U[A].3g};k 2A=B(3b){h(!(2q q.1N!="7O"&&2q q.3i!="7O"&&2q q.3i.6w=="9o")){u};k ax=(3b&&3b.1B)?[3b]:ai(q.26(\'2n\'),q.26(\'3U\')),8P=/5t-7t-([1-7]){1,6}/g,3R=/3R-7t-([1-7]{1,7})/,8Q=/1A-1F-(((\\d\\d\\d\\d)(0[1-9]|1[2P])(0[1-9]|[12][0-9]|3[2f]))|((\\d)-(22|3S|1D|25))|(21))/,8R=/1A-1W-(((\\d\\d\\d\\d)(0[1-9]|1[2P])(0[1-9]|[12][0-9]|3[2f]))|((\\d)-(22|3S|1D|25))|(21))/,2e=/d0-((\\d\\d\\d\\d)(0[1-9]|1[2P])(0[1-9]|[12][0-9]|3[2f]))/,7u=/ay(-((1J|T|1T|2c|cc)|([d|D|l|j|N|w|S|W|M|F|m|n|t|Y|o|y|O|p])))+/,2V=/az(-((1J|T|1T|2c|cc)|([d|D|l|j|N|w|S|W|M|F|m|n|t|Y|o|y|O|p])))+/,aA=/5t((-(\\d\\d\\d\\d)(0[1-9]|1[2P])(0[1-9]|[12][0-9]|3[2f])){2}|(-((\\d\\d\\d\\d)|(7v))((0[1-9]|1[2P])|(7w))(0[1-9]|[12][0-9]|3[2f])))/g,aB=/8S((-(\\d\\d\\d\\d)(0[1-9]|1[2P])(0[1-9]|[12][0-9]|3[2f])){2}|(-((\\d\\d\\d\\d)|(7v))((0[1-9]|1[2P])|(7w))(0[1-9]|[12][0-9]|3[2f])))/g,3v=/((7r(7k|6G|2A)7s)([^\\s|$]+))/d1,2K=/2W-aC-([^\\s|$]+)/i,8T=/3T-([^\\s|$]+)/i,1A,2O,j,t,H,2Q,1K;16(k i=0,C;C=ax[i];i++){h(C.v&&(C.v.L(7u)!=-1||C.v.L(/3f-E/)!=-1)&&((C.1B.2a()=="2n"&&(C.1o=="43"||C.1o=="3j"))||C.1B.2a()=="3U")){h(C.A&&C.A 15 U){h(!U[C.A].1y){U[C.A].8n()}J{h(!q.1j("1m-"+C.A)){U[C.A].2k=G;U[C.A].2A()}J h(3b){U[C.A].4c();U[C.A].2l()}};2s};h(!C.A){C.A="d2-"+8V++};H={A:C.A,1F:"",1W:"",45:"d-1T-m-1T-Y",2V:"",3K:[0,0,0,0,0,1,1],2I:[0,0,0,0,0,0,0],3h:{},2J:{},4H:C.v.L(/5k-d3/i)!=-1,1y:C.v.L(/2W-aC/i)!=-1,5b:C.v.L(/3D-2n/i)!=-1,4I:C.v.L(/5k-21-3T/i)!=-1,1X:C.v.L(/6K-3S/i)!=-1,4G:55?R:C.v.L(/5t-5W/i)!=-1,2K:G,46:C.v.L(/aD-88/i)!=-1,4J:C.v.L(/aD-88-5k-3U/i)!=-1,3v:at(C.v.1z(3v)),44:"",2e:""};h(C.v.L(2e)!=-1){H.2e=C.v.1z(2e)[1]};h(H.1y&&C.v.L(2K)!=-1){H.2K=C.v.1z(2K)[1]};h(!H.1y&&C.v.L(8T)!=-1){H.44=C.v.1z(8T)[1]};h(!H.1y){H.5D=C.v.L(/3t-([1-9]{1}[0-9]{1})/i)!=-1?C.v.1z(/3t-([1-9]{1}[0-9]{1})/i)[1]:90};2Q=C.v.1z(aA);h(2Q){16(t=0;t<2Q.X;t++){1K=2Q[t].Z(/7v/,"****").Z(/7w/,"**").Z("5t-","").3f("-");H.3h[1K[0]]=(1K.X&&1K.X==2)?1K[1]:1}};2Q=C.v.1z(aB);h(2Q){16(t=0;t<2Q.X;t++){1K=2Q[t].Z(/7v/,"****").Z(/7w/,"**").Z("8S-","").3f("-");H.2J[1K[0]]=(1K.X&&1K.X==2)?1K[1]:1}};H.3u=(C.v.L(/3f-E/)!=-1&&q.1j(C.A+2v[0])&&q.1j(C.A+2v[1])&&q.1j(C.A+2v[0]).1B.L(/2n|3U/i)!=-1&&q.1j(C.A+2v[1]).1B.L(/2n|3U/i)!=-1);h(!H.3u&&C.v.L(7u)!=-1){H.45=C.v.1z(7u)[0].Z(\'ay-\',\'\')};h(C.v.L(2V)!=-1){H.2V=C.v.1z(2V)[0].Z(\'az-\',\'\')};h(C.v.L(3R)!=-1){2O=C.v.1z(3R)[0].Z(/3R-7t-/,\'\');H.3K=[0,0,0,0,0,0,0];16(j=0;j<2O.X;j++){H.3K[2O.6b(j)-1]=1}};h(C.v.L(8P)!=-1){2O=C.v.1z(8P)[0].Z(/5t-7t-/,\'\');H.2I=[0,0,0,0,0,0,0];16(j=0;j<2O.X;j++){H.2I[2O.6b(j)-1]=1}};h(C.v.L(8Q)!=-1){H.1F=8J(C.v.1z(8Q)[0])};h(C.v.L(8R)!=-1){H.1W=8J(C.v.1z(8R)[0])};h(C.1B.L(/3U/i)!=-1){1A=ah(C);H.1F=H.1F?1A[0]+1a(H.1F).K(4,4):1A[0]+"d4";H.1W=H.1W?1A[1]+1a(H.1W).K(4,4):1A[1]+"d5"};8N(H)}}};2j(1E,\'8F\',2A);2j(1E,\'ak\',4R);2j(1E,\'d6\',7q);u{2j:B(1f,1o,1P){u 2j(1f,1o,1P)},1V:B(1f,1o,1P){u 1V(1f,1o,1P)},2w:B(e){u 2w(e)},6K:B(1c){u 8s(1c,G)},3D:B(1c){u aj(1c)},2A:B(3b){2A(3b)},d7:B(H){8N(H)},d8:B(){1V(1E,\'8F\',2A)},d9:B(1c){al(1c)},8D:B(){8D()},7q:B(){7q()},3m:B(T,3W,53){u 3m(T,3W,53)},4c:B(1c){h(!1c||!(1c 15 U)||!U[1c].2k)u G;U[1c].4c()},8t:B(1c,7x){h(!1c||!(1c 15 U))u G;U[1c].8t(7x)},8u:B(1c,7x){h(!1c||!(1c 15 U))u G;U[1c].8u(7x)},7g:B(P,45){u 7g(P,45)},da:B(3p){7D(3p)},db:B(1c,T){h(!1c||!(1c 15 U))u G;U[1c].7b(T)},7a:B(1c,2Q){h(!1c||!(1c 15 U))u G;U[1c].7a(2Q)},8v:B(1c,2Q){h(!1c||!(1c 15 U))u G;U[1c].8v(2Q)},5t:B(1c){h(!1c||!(1c 15 U))u G;U[1c].8p()},8S:B(1c){h(!1c||!(1c 15 U))u G;U[1c].af()}}})();',62,820,'||||||||||||this|||||if|||var||||||document||||return|className|||||id|function|elem||date||false|options|but|else|substr|search||||str|div|true||dt|datePickers|el||length||replace|||||td|in|for|new|appendChild||String|value|inpID|null|Date|obj|tmpDate|style|pad|getElementById|col|break|fd|span|type|datePicker|dp|getMonth|getFullYear|case|disabled|element|kc|prototype|staticPos|match|range|tagName|table|month|window|low|picker|getTitleTranslation|dt1|sp|parts|iePopUp|row|createElement|part|fn|Number|getDate|tr|sl|cc_on|removeEvent|high|showWeeks|noFocus|dt2||today|day|th||year|getElementsByTagName||||toLowerCase|parentNode|ds|Math|cursorDate|01|title|createTextNode|end|addEvent|created|updateTable|while|input|push|firstChild|typeof|currentStub|continue|statusText|localeImport|splitAppend|stopEvent|setARIAProperty|dateSet|cName|create|statusBar|prev|next|ths|titles|firstDayOfWeek|pt|disabledDays|enabledDates|positioned|daysInMonth|onmousedown|details|tmp|012|dts|err|setAttribute|try|catch|statusFormat|display|parseInt|currentDate|firstDateShown|||||||||||lastDateShown|inp|localeDefaults|script|_win32|split|visible|disabledDates|documentElement|hidden|tabIndex|yyyy|printFormattedDate|stopTimer|onkeydown|json|fdLocale|event|setARIARole|opacity|splitDate|callbacks|pos|px|setDate|outOfRange|curr|removeChild|weekDay|hide|rows|lower|upper|nd|object|top|highlightDays|opacityTo|body|scrollLeft|hover|getDay|out|highlight|week|button|select|dateArray|fmt|func|nbsp|dayAbbrs||||text|buttonWrapper|format|fillGrid|kbEventsAdded|||addSpans|isIE7|setDateFromInput|scrollTop|getElem|left|cellAdded|firstColIndex|round|butt|datepicker|onclick|elemList|cols|target|cellDate|txt|rngLower|rngUpper|msg|sup|label|titleFormat|fullMonths|monthAbbrs|fullDays|scriptFiles|fullParts|tmpParts|parentWindow|yearInc|monthInc|dragDisabled|noFadeEffect|noToday|constrainSelection|_jscript_version|visibility|focus|selectable|autoFocus|mousedown|updateStatus|destroy|onmouseover|onmouseout|clearTimer|colspan|tableHead|currentTR|tdm|tdy||sel|replacements|useImportedLocale|lbl|nodrag||placeholder|of|on|test|hideInput|dpm|lm|wkThs|header|fade|active|mouseup|dragEnabledCN|no|colOffset|origEl|delete|tm|ty|acc|labelList|cbObj|disable|weeksInYearCache|bases|languageTag|join|min|RegExp|timerSet|fadeTimer|timer|finalOpacity|fullCreate|selectedTD|offsetHeight|removeOldFocus|tabindex|setNewFocus|setMonth|spnC|stub|spn|currentYYYYMM|titleBar|timerInc|removeFocusEvents|clearTimeout|createTH|unselectable|tableBody|drag|colspanTotal|butToday|mouseDownElem|hideAll|getDayTranslation|checkSelectedDate|st|rd|mmN|ddN|opt|ddE|mmE|nMonth|charAt|datePickerController|languageInfo|returnLocaleDate|formatParts|src|navigator|tmpMasks|msk|opera|JSON|Function|dayInc|inUpdate|interval|setHours|changeHandler|reposition|block|osh|osw|offsetWidth|trueBody|compatMode|abs|setTimeout|disableTodayButton|bespokeRenderClass|nm|getEnabledDates|callback|redraw|getDisabledDates|selected|not|show|none|thClassName|describedby|tableFoot|enabled|with|tbody|butPrevYear|butPrevMonth|butNextYear|butNextMonth|updateTableHeaders|pageX|clientX|pageY|clientY|srcElement|incs|check|returnFormattedDate|keyCode|getTime|add|inpId|keydown|addDisabledDates|canDateBeSelected|keypress|op|level|upd|parseDateString|selectedIndex|isNaN|setSelectIndex|dateselect|ret|nodeList|abbreviation|nYear|now|repositionDatePickers|cb_|_|days|dateFormat|xxxx|xx|yyyymmdd|buttonTabIndex|mm|cellFormat|formatMasks|head|affectJSON|lang|key|switch|role|aria|mx|my|labelledBy|dynDisabledDates|spansAdded|undefined|thing|pageYOffset|0px|sOffsets|width|height|setFullYear|showHideButtons|weekDayC|daySub|stubN|stubP|tds|unused|getWeekNumber|mouseout|createThAndButton|presentation|nextSibling|grid||onblur|onfocus|diff|setOpacity|trackDrag|diffx|diffy|stopDrag|hideDP|dateYYYYMM|cnt|cursorYYYYMM|getWeeksInYear|createButton|change|disableDatePicker|addButtonEvents|dpVisible|showDatePicker|setRangeLow|setRangeHigh|setDisabledDates|100|iebody|posReal|clearDayFound|newVal|arguments|item|cleanUp|exception|load|num|X1|X2|parseRangeFromString|regExp|flags|loopLabel|addDatePicker|cbs|disableDays|rangeLow|rangeHigh|enable|bPositioned|parseNavigatorLanguage|uniqueId|May|Previous|Next|Today||Week|to|imported|scriptInner|parseJSON|||loc||javascript|language|userLanguage|formats|string|parseCellFormat|attachEvent|detachEvent|stopPropagation|parse|parent|property|findLabelForElement|getScrollOffsets|number|pageXOffset|truePosition|BackCompat|clientWidth|abbr|dateSetD|weekDayN|weekDayP|screen|reader|cloneNode|yyyymm|mmdd|getMonthTranslation|resizeInlineDiv|html|Could|locate|associated|insertBefore|tfoot|thead|scope|equaliseDates|mousemove|zIndex|reg|800|selection|previousSibling|addFocusEvents|charCode|ctrlKey|nodeType|default|isVisible|dayArray|cumulativeOffset|dsocleft|all|dsoctop|realOffset|do|de|wd|dynFormatMasks|concat|indx|tY|tM|tD|oldVal|enableDatePicker|args|grepRangeLimits|joinNodeLists|hideDatePicker|unload|destroySingleDatePicker|DoW||ms|valueOf|divds|1234|htmlFor|parseCallbacks|instanceof|method|data|formElements|dateformat|statusformat|disableDates|enableDates|inline|fill|fromCharCode|160|January|February|March|April|June|July|August|September|October|November|December|Jan|Feb|Mar|Apr|Jun|Jul|Aug|Sep|Oct|Nov|Dec|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday|Mon|Tue|Wed|Thu|Fri|Sat|Sun|Show|Calendar|wk|Select|Click|u0026|Drag|move|Display|u201C|u201D|first|Go|u2019s|Disabled|void|innerHTML|lastIndexOf|js|charset|utf|base|childNodes|en|buttontabindex|cellformat|titleformat|0000|addEventListener|alert|removeEventListener|preventDefault|cancelBubble|returnValue|self|Object|Array|Image|ActiveXObject|gim|bfunction|Trouble|parsing|defaults|cursorTD|maxHeight|clientHeight|noCallback|firstDateDisplayed|lastDateDisplayed|floor|mouseover|colSpan|labelledby|datePickerTable|iframe|iehack|scrolling|||frameBorder|name|iePopUpHack|throw|static|300|statusbar|u00AB||u2039|u203A|u00BB|gridcell|columnheader|rowheader|trs|weeks|displayed|9999|1600||10000|104|toElement|relatedTarget|nodeValue|href|control|haspopup|setDisabledDays|disabledDateObj|devicePixelRatio|filter|alpha|offsetTop|offsetLeft|offsetParent|createDocumentFragment|reverse|400|NW|604800000|864e5|lebel|getAttribute|_label|indexOf|apply|cursor|ig|fdDatePickerInput|animation|0101|1231|resize|createDatePicker|removeOnloadEvent|destroyDatePicker|setGlobalVars|dateValidForSelection||'.split('|'),0,{}))
function test(){}
SapoMapsApp.POIS={urlToGetSimplePOI:{baseUrl:'http://services.sapo.pt/Maps/GetPOIByBoundingBoxJSON?',fl:'POIId,Name,Latitude,Longitude,Detail,CategoryId',latitude1:null,longitude1:null,latitude2:null,longitude2:null,pageNumber:1,recordsPerPage:null,matchlevelId:10},nrPixelsToRequest:50,lastRequestCoords:null,maxPOIsPerRequested:100,PoisPerLayer:20,map:null,inactivityTimer:null,inactivityTime:500,requester:null,requests:0,responses:0,selectedPOI:null,stateToRecover:null,status:null,categoriesStr:null,activeLayers:{},nrActiveLayers:0,lastZoom:0,initialize:function(map){this.requester=SAPO.Maps.Request.prototype.getRequester();this.map=map;},activate:function(){this.map.events.register('movestart',this,function(){if(SapoMapsApp.POIS.inactivityTimer){debug('clear timer');window.clearTimeout(SapoMapsApp.POIS.inactivityTimer);SapoMapsApp.POIS.inactivityTimer=null;}});this.map.events.register('moveend',this,function(){SapoMapsApp.POIS.inactivityTimer=window.setTimeout(function(){if(SapoMapsApp.POIS.lastZoom!=SapoMapsApp.POIS.map.getZoom()){SapoMapsApp.POIS.categoriesStr=null;SapoMapsApp.POIS.nrActiveLayers=0;}
SapoMapsApp.POIS.refresh();SapoMapsApp.POIS.lastZoom=SapoMapsApp.POIS.map.getZoom();},SapoMapsApp.POIS.inactivityTime);});this.lastZoom=this.map.getZoom();},deactivate:function(){},activateLayer:function(layer,sublayer,doNotShowPOIS){if(!SapoMapsApp.Layers[layer]){return;}
if(!SapoMapsApp.Layers[layer].markers){SapoMapsApp.Layers[layer].markers=new SAPO.Maps.Markers(layer,{cluster:false});this.map.addMarkers(SapoMapsApp.Layers[layer].markers);}
if(!this.activeLayers[layer]){++this.nrActiveLayers;this.activeLayers[layer]={};}
var categories=false;if(!sublayer){for(var sl in SapoMapsApp.Layers[layer].layers){this.activeLayers[layer][sl]=true;}
categories=this.getCategoriesArrayFromLayer(layer);}else{if(this.activeLayers[layer]&&this.activeLayers[layer][sublayer]){return;}
this.activeLayers[layer][sublayer]=true;if(this.map.getZoom()<SapoMapsApp.Layers[layer].layers[sublayer].minZoom){return;}
categories=SapoMapsApp.Layers[layer].layers[sublayer].categories;}
if(categories.length===0){return;}
var requestCategories=categories.toString();if(this.categoriesStr===null){this.categoriesStr=requestCategories;}else{this.categoriesStr+=","+requestCategories;}
var bounds=this.map.getBounds();this.urlToGetSimplePOI.longitude1=bounds.left.toFixed(6);this.urlToGetSimplePOI.latitude1=bounds.bottom.toFixed(6);this.urlToGetSimplePOI.longitude2=bounds.right.toFixed(6);this.urlToGetSimplePOI.latitude2=bounds.top.toFixed(6);this.urlToGetSimplePOI.recordsPerPage=this.PoisPerLayer;if(!this.status||!this.status.cancel){this.status={cancel:false};}
if(!doNotShowPOIS){this.request(requestCategories,layer,this.status);}},deactivateLayer:function(layer,sublayer){if(!SapoMapsApp.Layers[layer]||!SapoMapsApp.Layers[layer].markers){return;}
if(!sublayer){for(var sl in SapoMapsApp.Layers[layer].layers){this.activeLayers[layer][sl]=false;}
SapoMapsApp.Layers[layer].markers.removeMarkers();delete this.activeLayers[layer];--this.nrActiveLayers;}else{if(!this.activeLayers[layer]||!this.activeLayers[layer][sublayer]){return;}
this.clearPOISFromSubLayer(layer,sublayer);delete this.activeLayers[layer][sublayer];if(this.isEmpty(this.activeLayers[layer])){delete this.activeLayers[layer];}}
this.categoriesStr=null;},isEmpty:function(obj){for(var e in obj){if(obj[e]){return false;}}
return true;},hasAllActives:function(obj1,obj2){if(!obj1||!obj2){return false;}
var contains=false;for(var p in obj1){contains=false;for(var p2 in obj2){if(p==p2){contains=true;break;}}
if(!contains){return false;}}
return true;},getActiveLayers:function(){var layers="";for(var l in this.activeLayers){if(layers.length){layers+=',';}
layers+=l;if(!this.hasAllActives(SapoMapsApp.Layers[l].layers,this.activeLayers[l])){var slayers='';for(var sl in this.activeLayers[l]){if(slayers.length){slayers+='-';}
slayers+=sl;}
layers+='-'+slayers;}}
return layers;},getState:function(){if(!this.selectedPOI){return'';}
return this.selectedPOI.IsAtLayer+','+this.selectedPOI.POIId;},setStateAfterLoad:function(state){this.stateToRecover=state;},setState:function(state){var arr=state.split(',');var layer=arr[0];var poiid=arr[1];var dmarkers=null;if(!layer){return;}
dmarkers=SapoMapsApp.Layers[layer].markers.getMarkers();for(var i=0;i<dmarkers.length;++i){if(poiid==dmarkers[i].POIId){this.selectedPOI=dmarkers[i];var tmpSelectedPOI=this.selectedPOI;SapoMapsApp.getPOI(this.selectedPOI.POIId,this.requester,{timeout:4,onComplete:function(obj){SapoMapsApp.closeInfoWindows();this.selectedPOI=tmpSelectedPOI;this.selectedPOI.html=SAPO.Maps.PoiInfoRenderer.getHTML(obj.GetPOIByIdResponse.GetPOIByIdResult,this.selectedPOI,SapoMapsApp.Search.search,[{name:'Itinerário',func:this.itineraryOptionClicked,context:this}]);this.selectedPOI.openPopup(this.selectedPOI.html,{borders:SapoMapsApp.borders});}.bindObj(this)});this.stateToRecover=null;return;}}
var url='http://services.sapo.pt/GIS/GetPOIByIdJSON?poiId='+poiid;var reqId=this.requester.request(url,{timeout:8,onComplete:function(poi,layer){try{poi=poi.GetPOIByIdResponse.GetPOIByIdResult;lon=Number(poi.Longitude);lat=Number(poi.Latitude);lonlat=new OpenLayers.LonLat(lon,lat);var markerImg=false;if(poi.DetailXml.Details.Icon){markerImg=poi.DetailXml.Details.Icon.value||poi.DetailXml.Details.Icon;}else{markerImg='icon_'+markerLayer;}
var style={markerImage:markerImg,size:new OpenLayers.Size(16,16),markerAnchor:new OpenLayers.Pixel(-8,-8)};var marker=new SAPO.Maps.Marker(lonlat,{popupAnchor:new OpenLayers.Pixel(0,-8)},style);marker.html=SAPO.Maps.PoiInfoRenderer.getHTML(poi,marker,SapoMapsApp.Search.search,[{name:'Itinerário',func:this.itineraryOptionClicked,context:this}]);marker.POIId=poi.POIId;marker.registerEvent('click',SapoMapsApp.POIS,function(m){SapoMapsApp.closeInfoWindows();this.selectedPOI=m;m.openPopup(m.html,{borders:SapoMapsApp.borders});});marker.registerEvent('popupclosed',SapoMapsApp.POIS,function(){this.selectedPOI=null;});SapoMapsApp.Layers[layer].markers.addMarker(marker);SapoMapsApp.closeInfoWindows();marker.openPopup(marker.html,{borders:SapoMapsApp.borders});SapoMapsApp.POIS.selectedPOI=marker;}catch(e){debug("erro a repor o estado... obter o poi: "+e);}}.bindObj(this),optOnComplete:layer});this.stateToRecover=null;},closeOpenedPopup:function(){if(!this.selectedPOI){return;}
this.selectedPOI.closePopup();this.selectedPOI=null;},refresh:function(){var bounds=this.map.getBounds();if(this.lastRequestCoords){var lastpx=this.map.getContainerPixelFromLonLat(this.lastRequestCoords);var px=this.map.getContainerPixelFromLonLat(new OpenLayers.LonLat(bounds.right,bounds.top));var deltax=lastpx.x-px.x;var deltay=lastpx.y-px.y;if(deltax<0){deltax*=-1;}
if(deltay<0){deltay*=-1;}
if(deltax<this.nrPixelsToRequest&&deltay<this.nrPixelsToRequest){debug('donot request! Move the map');return;}}
if(this.requests>0){this.cancelRequest();}
if(!this.categoriesStr){var clear=this.lastZoom>this.map.getZoom();var categories=this.getCategoriesArray(clear);if(categories.length===0){this.lastRequestCoords=null;this.clearPOIS();return;}
this.categoriesStr=categories.toString();}
var requestFor=this.PoisPerLayer*this.nrActiveLayers;this.urlToGetSimplePOI.longitude1=bounds.left.toFixed(6);this.urlToGetSimplePOI.latitude1=bounds.bottom.toFixed(6);this.urlToGetSimplePOI.longitude2=bounds.right.toFixed(6);this.urlToGetSimplePOI.latitude2=bounds.top.toFixed(6);this.urlToGetSimplePOI.recordsPerPage=requestFor>this.maxPOIsPerRequested?this.maxPOIsPerRequested:requestFor;this.status={cancel:false};this.request(this.categoriesStr,null,this.status);this.lastRequestCoords=new OpenLayers.LonLat(bounds.right,bounds.top);},request:function(categories,layer,status){debug('newRequest');++this.requests;this.urlToGetSimplePOI.categoryId=categories;var url=SapoMapsApp.getUrl(this.urlToGetSimplePOI);this.requester.request(url,{timeout:4,onComplete:function(obj,args){try{if(args.s.cancel){return;}
debug('arrive');SapoMapsApp.POIS.processRequest(obj,args.l);if(SapoMapsApp.POIS.requests===0&&SapoMapsApp.POIS.stateToRecover){SapoMapsApp.POIS.setState(SapoMapsApp.POIS.stateToRecover);}}catch(e){debug("  exception: "+e);}},optOnComplete:{l:layer,s:status},onTimeout:function(){++SapoMapsApp.POIS.responses;if(SapoMapsApp.POIS.responses==SapoMapsApp.POIS.requests)
{SapoMapsApp.POIS.requests=0;SapoMapsApp.POIS.responses=0;if(SapoMapsApp.POIS.stateToRecover){SapoMapsApp.POIS.setState(SapoMapsApp.POIS.stateToRecover);}}
SapoMapsApp.POIS.lastRequestCoords=null;debug('timeout');}});},processRequest:function(objs,layer){try{if(this.requests===0){return;}
++this.responses;if(this.responses==this.requests){this.requests=0;this.responses=0;}
if(!objs.Response||!objs.Response.Result||!objs.Response.Result.POI){debug('nr: 0');return;}
var pois=objs.Response.Result.POI;if(!(pois instanceof Array)){pois=[pois];}
debug('nr: '+pois.length);var lonlat=false,lon,lat,marker,markerLayer,poi,style,markerSubLayer;var markers=false;var markerImg=false;for(var i=0;i<pois.length;++i){try{poi=pois[i];markerLayer=layer?layer:SapoMapsApp.Categories[Number(poi.CategoryId)].l;markerSubLayer=SapoMapsApp.Categories[Number(poi.CategoryId)].sl;markers=SapoMapsApp.Layers[markerLayer].markers;if(this.checkIfExists(markers,poi)||!this.activeLayers[markerLayer][markerSubLayer]){continue;}
lon=Number(poi.Longitude);lat=Number(poi.Latitude);lonlat=new OpenLayers.LonLat(lon,lat);if(poi.DetailXml&&poi.DetailXml.Details&&poi.DetailXml.Details.Icon){markerImg=poi.DetailXml.Details.Icon.value||poi.DetailXml.Details.Icon;}else{markerImg='http://imgs.sapo.pt/fotos_gis/poi/icon_'+markerLayer+'.gif';}
style={markerImage:markerImg,size:new OpenLayers.Size(16,16),markerAnchor:new OpenLayers.Pixel(-8,-8)};marker=new SAPO.Maps.Marker(lonlat,{popupAnchor:new OpenLayers.Pixel(0,-8)},style);marker.POIId=poi.POIId;marker.IsAtLayer=markerLayer;marker.IsAtSubLayer=markerSubLayer;marker.registerEvent('click',this,this.markerClicked);marker.registerEvent('rightclick',this,this.markerRightClicked);marker.registerEvent('popupclosed',this,function(){this.selectedPOI=null;});marker.registerEvent("mouseover",this,function(){this.map.div.style.cursor="pointer";});marker.registerEvent("mouseout",this,function(){this.map.div.style.cursor="";});markers.addMarker(marker);}
catch(e1){if(poi.CategoryId!=73){debug("category: "+poi.CategoryId+" MISSING");}}}}catch(e2){debug("  -- Error at processRequest: "+e2+" --  ");}},markerClicked:function(marker){SapoMapsApp.closeInfoWindows();this.selectedPOI=marker;function displayHtml(obj){marker.html=SAPO.Maps.PoiInfoRenderer.getHTML(obj.GetPOIByIdResponse.GetPOIByIdResult,marker,SapoMapsApp.Search.search,[{name:'Itinerário',func:this.itineraryOptionClicked,context:this}]);if(this.selectedPOI===marker){marker.openPopup(marker.html,{borders:SapoMapsApp.borders});}}
function displayError(){}
if(marker.html){marker.openPopup(marker.html,{borders:SapoMapsApp.borders});}else{SapoMapsApp.getPOI(marker.POIId,this.requester,{timeout:4,onComplete:displayHtml.bindObj(this),onTimeout:displayError.bindObj(this)});}
try{SapoMapsApp.Analytics.track("Layers",marker.IsAtSubLayer,"AbrirPin");}catch(e){}},markerRightClicked:function(marker){var px=map.getContainerPixelFromLonLat(marker.getLonLat());contextMenu.show({xy:px});return false;},itineraryOptionClicked:function(poi){var coords;if(poi&&poi.Latitude&&poi.Longitude){coords=new OpenLayers.LonLat(Number(poi.Longitude),Number(poi.Latitude));}
if(selectedPanel===Panels.ItinerariesAndSearch){selectedPanel.Itineraries.style.display='none';selectedPanel.Search.style.display='none';}
else{selectedPanel.style.display='none';}
selectedPanel=Panels.Itineraries;selectPanel('itinerary');SapoMapsApp.Itineraries.toHere(coords,true);},cancelRequest:function(){if(!this.status){return;}
debug('cancel');this.status.cancel=true;this.status=null;this.requests=0;this.responses=0;},checkIfExists:function(layer,poi){var markers=layer.getMarkers();for(var i=0;i<markers.length;++i){if(markers[i].POIId==poi.POIId){return true;}}
return false;},clearPOIS:function(){for(var layer in SapoMapsApp.Layers){if(!SapoMapsApp.Layers[layer].markers){continue;}
var markers=SapoMapsApp.Layers[layer].markers.getMarkers();var marker;for(var i=markers.length-1;i>=0;--i){marker=markers[i];marker.html=null;marker.POIId=null;marker.IsAtLayer=null;marker.IsAtSubLayer=null;SapoMapsApp.Layers[layer].markers.removeMarker(marker);}}},clearPOISFromSubLayer:function(layer,sublayer){var markers=SapoMapsApp.Layers[layer].markers.getMarkers();var marker;for(var i=markers.length-1;i>=0;--i){marker=markers[i];if(marker.IsAtSubLayer==sublayer){SapoMapsApp.Layers[layer].markers.removeMarker(marker);marker.html=null;marker.POIId=null;marker.IsAtLayer=null;marker.IsAtSubLayer=null;}}},clearOutOfBoundsPOIS:function(markersLayer){if(!markersLayer){return;}
var markers=markersLayer.getMarkers(),marker=false,bounds=this.map.getBounds(),lonlat=false;for(var i=markers.length-1;i>=0;--i){marker=markers[i];lonlat=marker.getLonLat();if(lonlat.lon>bounds.left&&lonlat.lon<bounds.right&&lonlat.lat<bounds.top&&lonlat.lat>bounds.bottom){continue;}
if(marker.hasOpenedPopup()){continue;}
marker.html=null;marker.POIId=null;marker.IsAtLayer=null;marker.IsAtSubLayer=null;markersLayer.removeMarker(marker);}},getCategoriesArray:function(clearOutOfBounds){var categories=[];var layerCategories=false;var sl=false;this.nrActiveLayers=0;for(var l in this.activeLayers){layerCategories=this.getCategoriesArrayFromLayer(l,clearOutOfBounds);if(layerCategories.length>0){++this.nrActiveLayers;categories=categories.concat(layerCategories);}}
return categories;},getCategoriesArrayFromLayer:function(layer,clearOutOfBounds){var curr_zoom=this.map.getZoom();var categories=[];for(var sl in this.activeLayers[layer]){if(curr_zoom<SapoMapsApp.Layers[layer].layers[sl].minZoom){debug('clear subcategories '+sl+' in layer '+layer);this.clearPOISFromSubLayer(layer,sl);continue;}
if(SapoMapsApp.Layers[layer].layers[sl].categories){categories=categories.concat(SapoMapsApp.Layers[layer].layers[sl].categories);if(clearOutOfBounds){this.clearOutOfBoundsPOIS(SapoMapsApp.Layers[layer].markers);}}}
return categories;}};
SapoMapsApp.Search={map:null,panel:null,bbox:null,holder:null,queryBox:null,search:null,query:null,queryWhatsHere:null,centerAt:null,zoomTo:null,selectedResultIdx:null,pageToLoad:null,zoneToOpen:null,showAllZones:null,pubElem:null,firstTime:true,initialize:function(map,panel,holder,queryBox,pubElem){this.map=map;this.panel=panel;this.holder=holder;this.queryBox=queryBox;this.pubElem=pubElem;this.search=new SAPO.Maps.Search(map,panel,{borders:SapoMapsApp.borders});this.search.registerEvent('error',this,this.error);this.search.registerEvent('beforeSearch',this,this.beforeSearch);this.search.registerEvent('completed',this,this.completed);this.search.registerEvent('timeout',this,this.centerAndZoom);this.search.registerEvent('selected',this,this.selectedResult);this.search.registerEvent('selectedOnPanel',this,this.selectedResultOnPanel);this.search.registerEvent('selectedOnMap',this,this.selectedResultOnMap);this.search.registerEvent('beforeSelected',this,this.beforeSelectedResult);this.search.registerEvent('unselected',this,this.unSelectedResult);this.search.registerEvent('pageChanged',this,this.pageChanged);this.search.registerEvent('dashboardTabOpened',this,this.setZoneHeights);this.search.registerEvent('zoneClosed',this,this.zoneClosed);},getResults:function(query,searchpois){showSearchFilters();this.query=query;if(!this.bbox){this.bbox=this.map.getBounds();}
var filter_all=document.getElementById('search_filter_all');var filter_streets=document.getElementById('search_filter_streets');var filter_pois=document.getElementById('search_filter_pois');var searchForPOIS,searchForStreetsAndLocations;if(filter_all.checked){searchForPOIS=searchForStreetsAndLocations=true;}
else{searchForPOIS=searchForStreetsAndLocations=false;if(filter_streets.checked){searchForStreetsAndLocations=true;}
else{searchForPOIS=true;}}
this.search.search(this.query,{allowPaging:true,categorizedSearch:true,bbox:this.bbox,searchForPOIS:searchForPOIS,searchForStreetsAndLocations:searchForStreetsAndLocations});var coords=SAPO.Maps.Utils.checkQuery(query);if(coords){hideSearchFilters();SapoMapsApp.Analytics.track("Pesquisa","Coordenadas",coords.Latitude+"--"+coords.Longitude);}
else{SapoMapsApp.Analytics.track("Pesquisa","geral",query);}},whatsHere:function(lonlat,zoom){hideSearchFilters();if(this.holder){this.holder.style.display='block';}
if(this.pubElem){this.pubElem.style.display='none';}
this.queryWhatsHere={lonlat:lonlat,zoom:zoom};this.search.searchWhatsHere(lonlat,zoom);},isActive:function(){return(this.query&&this.query.length>0)||this.queryWhatsHere;},clear:function(){this.search.cancel();if(!this.query&&!this.queryWhatsHere){return;}
this.query=null;this.queryWhatsHere=null;this.selectedResultIdx=null;this.search.clear();if(this.holder){this.holder.style.display='none';}
if(this.pubElem){this.pubElem.style.display='block';}
this.firstTime=true;this.bbox=null;},centerOnComplete:function(center,zoom){this.centerAt=center;this.zoomTo=zoom;},setState:function(state){var arr=state.split(',');try{if(state.indexOf('wh:')!=-1){arr=state.split('wh:')[1].split(',');var lonlat=new OpenLayers.LonLat(Number(arr[1]),Number(arr[0]));var zoom=Number(arr[2]);if(arr.length>3){this.resultToSelect=Number(arr[3]);}
this.whatsHere(lonlat,zoom);}else{var q=decodeURIComponent(arr[0]);if(this.queryBox){this.queryBox.value=q;}
if(arr.length>1){this.pageToLoad=Number(arr[1]);}
if(arr.length>2){this.resultToSelect=Number(arr[2]);}
if(arr.length>3){this.zoneToOpen=decodeURIComponent(decodeURIComponent(arr[3]));}
if(arr.length>4){this.showAllZones=decodeURIComponent(decodeURIComponent(arr[4]));}
if(arr.length>5){var bboxString=decodeURIComponent(decodeURIComponent(arr[5]));this.bbox=OpenLayers.Bounds.fromString(bboxString.replace(/;/g,","));}
this.getResults(q);}}catch(e){}},getState:function(){if(!this.isActive()){return'';}
var state='';if(this.query){state=encodeURIComponent(encodeURIComponent(this.query))+','+this.search.getCurrentPage(this.search.openedZone);}else{state='wh:'+this.queryWhatsHere.lonlat.lat+','+this.queryWhatsHere.lonlat.lon+','+this.queryWhatsHere.zoom;}
if(this.selectedResultIdx!==null){state+=','+this.selectedResultIdx;}
else{state+=',-1';}
if(this.search.openedZone!==null){state+=','+encodeURIComponent(encodeURIComponent(this.search.openedZone));}
else{state+=',none';}
if(this.search.showEmptyZones){state+=",true";}
else{state+=",false";}
if(this.bbox){state+=","+encodeURIComponent(encodeURIComponent(this.bbox.toBBOX().replace(/,/g,";")));}
return state;},error:function(search,msg){},centerAndZoom:function(){try{if(this.centerAt&&this.zoomTo&&this.resultToSelect!==null){var idx=this.resultToSelect;this.selectedResultIdx=null;if(idx>=0){this.search.selectResult(idx,this.search.openedZone);}}
if(this.centerAt){this.map.setMapCenter(this.centerAt);}
if(this.zoomTo){this.map.zoomTo(this.zoomTo);}
if(!this.pageToLoad){this.centerAt=null;this.zoomTo=null;}
var markers=this.search.getMarkers();for(var i=0;i<markers.length;++i){markers[i].registerEvent("mouseover",this,function(){this.map.div.style.cursor="pointer";});markers[i].registerEvent("mouseout",this,function(){this.map.div.style.cursor="";});}}catch(e){}},closeOpenedPopup:function(){this.search.unselectResult(this.search.getSelectedIndex());},beforeSelectedResult:function(search,poi,idx){SapoMapsApp.closeInfoWindows();},selectedResult:function(search,poi,idx){if(this.selectedResultIdx!==idx){this.selectedResultIdx=idx;if(poi.SourceId==='28'||poi.SourceId==='31'){SapoMapsApp.Analytics.track("Pesquisa","Utilizacao","SeleccionarResultadoPAI");}
else{SapoMapsApp.Analytics.track("Pesquisa","Utilizacao","SeleccionarResultado");}}},selectedResultOnPanel:function(search,poi,idx){if(this.selectedResultIdx!==idx){if(poi.SourceId==='28'||poi.SourceId==='31'){SapoMapsApp.WebtrendsAnalytics.track(['DCSext.linktype','flyout','DCSext.linkplace','result list'],poi);}}},selectedResultOnMap:function(search,poi,idx){if(this.selectedResultIdx!==idx){if(poi.SourceId==='28'||poi.SourceId==='31'){SapoMapsApp.WebtrendsAnalytics.track(['DCSext.linktype','flyout','DCSext.linkplace','map'],poi);}}},unSelectedResult:function(search,poi,idx){this.selectedResultIdx=null;},zoneClosed:function(search,zoneName){this.selectedResultIdx=null;},beforeSearch:function(search,query){if(search.nearSearch){resetSearchFilter();search.searchForPOIS=false;search.searchForStreetsAndLocations=false;}
try{selectPanel('search');}catch(e){}
if(this.holder){this.holder.style.display='block';}
if(this.pubElem){this.pubElem.style.display='none';}
this.query=query;},completed:function(s){document.getElementById("results").className=document.getElementById("results").className.replace(/itineraries/,"");if(this.showAllZones==="true"){this.showAllZones=null;s.showAllZones();return;}
if(this.zoneToOpen!==null&&this.zoneToOpen!==s.openedZone){s.openZone(this.zoneToOpen);this.zoneToOpen=null;this.completed(s);}
else{if(this.pageToLoad!==null&&this.pageToLoad>=0){s.goToPage(this.pageToLoad,s.openedZone,true);return;}
else{this.centerAndZoom();}}
var nrResults=s.getTotalResults();if(nrResults>0){nrResults=1;}
SapoMapsApp.WebtrendsAnalytics.pageView(['DCSext.search_what',this.query,'WT.oss_r',nrResults]);},pageChanged:function(s,page){this.centerAndZoom();this.pageToLoad=null;if(this.panel){var aditionalContentHeight=selectedPanel===Panels.ItinerariesAndSearch?255:86;removePubToDisplayPanel(this.panel.childNodes[0],aditionalContentHeight,this.panel);}
this.setZoneHeights(s);SapoMapsApp.WebtrendsAnalytics.setWebtrendsParams();SapoMapsApp.Analytics.track("Pesquisa","Utilizacao","MudancaDePagina");}};
SAPO.Maps.Geocoder.prototype.categorizedUrl="http://services.sapo.pt/Maps/SearchJSON";SAPO.Maps.Geocoder.prototype.getLocationsCategorized=function(query,onCompleteCallback,onErrorCallback,opts){var options=OpenLayers.Util.extend({bbox:null,resultsPerPage:10,pageNumber:1,context:null,searchForPOIS:false,dashboard:true},opts);var url=this.categorizedUrl+'?version=2.0&isRecordsPerPagePerResultType=true&searchType=merged&q='+encodeURIComponent(query);url+='&recordsPerPage='+options.resultsPerPage+'&pageNumber='+options.pageNumber;if(options.bbox){var bbox=opts.bbox.toArray();url+="&xMin="+bbox[0]+"&yMin="+bbox[1]+"&xMax="+bbox[2]+"&yMax="+bbox[3];}
if(options.category){url+="&lf="+encodeURIComponent(options.category);}
if(options.dashboard){url+="&dashboard=true";}
if(!options.searchForPOIS||!options.searchForStreetsAndLocations){if(options.searchForPOIS){url+='&f=allpois';}
if(options.searchForStreetsAndLocations){url+="&lf=LocalidadesOuRuas";}}
if(options.randomToken){url+="&rt="+options.randomToken;}
function timeout(){try{onErrorCallback.apply(this,[options.context]);}catch(e3){}}
this.requester.request(url,{timeout:4,onComplete:this.processRequestCategorized.bindObj(this),onTimeout:timeout.bindObj(this),optOnComplete:{onComplete:onCompleteCallback,onTimeout:onErrorCallback,options:options}});};SAPO.Maps.Geocoder.prototype.processRequestCategorized=function(obj,args){var pois=[],totalResults=0,randomToken;try{pois=obj.SearchResponse.SearchResult.Category;if(!pois.length){pois=[pois];}
totalResults=Number(obj.SearchResponse.SearchResult.totalResults);randomToken=obj.SearchResponse.SearchResult.randomToken;}
catch(e1){pois=[];if(args.onComplete){this.notifyCallbacks(args.onComplete,this,[pois,args.options.context,totalResults,randomToken]);}
return;}
if(!pois){pois=[];}
if(args.onComplete){this.notifyCallbacks(args.onComplete,this,[pois,args.options.context,totalResults,randomToken]);}};SAPO.Maps.Geocoder.prototype.transform=function(obj){var categories=obj.SearchResponse.SearchResult.Category;var pois=[];for(var e in categories){if(e==="totalResults"){continue;}
pois.push({POIs:categories[e].POIs,name:categories[e].name,totalResults:categories[e].totalResults});}
return pois;};
SAPO.Maps.Search.prototype.complete=function(pois,context,totalresults,randomToken){if(this.panel){if(this.categorizedSearch&&this.openedZone){SAPO.Maps.Utils.removeWaitIcon(this.zones[this.openedZone].content);}
else{SAPO.Maps.Utils.removeWaitIcon(this.panel);}}
try{if(context.cancel){return;}
this.status=SAPO.Maps.Request.Status.OK;this.totalResults=totalresults;this.randomToken=randomToken;this.pois=pois;if((this.totalResults>1||this.totalResults===1&&this.displaySingleResult)&&(this.panel||this.map)){if(this.categorizedSearch){this.parseZones(pois);this.displayResultsCategorized();if(this.openedZone){var zoneToOpen=this.openedZone;this.openedZone=null;this.openZone(zoneToOpen);}
else{for(var e in this.zones){this.openZone(e);break;}}}
else{this.displayResults(pois,totalresults);}}
else{if((pois.length===0||!this.zones)&&this.panel){var elem=document.createElement('div');elem.className='search_results_smapi';if(this.whatsHereSearch){SAPO.Maps.Utils.displayMessageHTML(elem,"Lamentamos mas não existem resultados para o local seleccionado.","","",SAPO.Maps.Utils.MessageType.WARNING);this.panel.appendChild(elem);this.div=elem;}else{if(this.categorizedSearch){if(this.pageChanged){SAPO.Maps.Utils.displayMessageHTML(elem,"Lamentamos mas de momento não existem resultados para esta categoria.","","",SAPO.Maps.Utils.MessageType.WARNING);}
else{SAPO.Maps.Utils.displayMessageHTML(elem,"A sua pesquisa por: ",this.query," não devolveu qualquer resultado.",SAPO.Maps.Utils.MessageType.WARNING);}
if(this.openedZone){this.zones[this.openedZone].content.appendChild(elem);}
else{this.panel.appendChild(elem);this.div=elem;}}
else{SAPO.Maps.Utils.displayMessageHTML(elem,"A sua pesquisa por: ",this.query," não devolveu qualquer resultado.",SAPO.Maps.Utils.MessageType.WARNING);this.panel.appendChild(elem);this.div=elem;}}}}
var evtType=this.pageChanged===false?'completed':'pageChanged';var params=this.pageChanged===false?[this,this.pois,this.totalResults]:[this,this.currentPage,this.pois];this.pageChanged=false;try{this.notifyListeners(evtType,params);}
catch(e3){try{this.notifyListeners('error',[this,e3]);}catch(e4){}}
if(this.getNrZones()===1&&this.zones.Localidades){this.zones.Localidades.content.style.height=(this.panel.clientHeight-this.zones.Localidades.content.offsetTop-11)+"px";}}catch(e1){try{this.notifyListeners('error',[this,e1]);}catch(e2){}}};SAPO.Maps.Search.prototype.getResults=function(lonlat,zoom){var isCoords=SAPO.Maps.Utils.checkQuery(this.query);this.isCoords=isCoords;if(isCoords){this.pois=[isCoords];this.status=SAPO.Maps.Request.Status.OK;if(this.displaySingleResult){if(!this.categorizedSearch){this.displayResults(this.pois);}
else{this.zones={};this.zones.Coordenadas={currentPage:1,nrOfPages:1,totalResults:1,pois:[{Name:isCoords.Latitude+", "+isCoords.Longitude,Category:"Coordenadas",Latitude:isCoords.Latitude,Longitude:isCoords.Longitude}]};this.totalResults=1;this.displayResultsCategorized();this.openZone("Coordenadas");}}
this.totalResults=this.pois.length;try{this.notifyListeners('completed',[this,this.pois,this.totalResults]);}
catch(e3){try{this.notifyListeners('error',[this,e3]);}catch(e4){}}
return;}
if(this.checkIfTheQueryMatchesWithMadeiraOrAzores_hack()){return;}
if(this.panel){if(!this.categorizedSearch||!this.pageChanged){SAPO.Maps.Utils.displayWaitIcon(this.panel);}
else{if(this.pageChanged===this.openedZone){this.clearZone(this.openedZone);SAPO.Maps.Utils.displayWaitIcon(this.zones[this.openedZone].content);}}}
this.request={cancel:false};if(this.whatsHereSearch){this.geocoder.findWhatsHere(lonlat,zoom,this.onComplete,this.onTimeout,{context:this.request});}else{if(this.categorizedSearch){var opts={resultsPerPage:this.resultsPerPage,pageNumber:this.pageChanged?this.zones[this.pageChanged].currentPage:1,bbox:this.bbox,context:this.request,searchForPOIS:this.searchForPOIS,searchForStreetsAndLocations:this.searchForStreetsAndLocations,dashboard:this.showDashboard};if(this.pageChanged){opts.category=this.pageChanged;opts.randomToken=this.randomToken;}
this.geocoder.getLocationsCategorized(this.query,this.onComplete,this.onTimeout,opts);}
else{this.geocoder.getLocations(this.query,this.onComplete,this.onTimeout,{resultsPerPage:this.resultsPerPage,pageNumber:this.currentPage,bbox:this.bbox,context:this.request,searchForPOIS:this.searchForPOIS,randomToken:this.randomToken?this.randomToken:null});}}};SAPO.Maps.Search.prototype.getCategorizedPanelHTML=function(zoneName,poi,number,showImg,displayDashboard){var div_item=document.createElement("div");var div_marker=document.createElement("div");var div_content=document.createElement("div");var div_cleaner=document.createElement("div");div_item.className="item";div_marker.className="marker";div_content.className="item_content";div_cleaner.className="floater_cleaner";var img_marker=document.createElement("img");var a_magnifier=document.createElement("a");img_marker.width=22;img_marker.height=28;img_marker.alt="Mini Marker";img_marker.src="http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Markers/new/m"+number+".png";a_magnifier.className="lupa";a_magnifier.href="#";div_marker.appendChild(img_marker);div_marker.appendChild(a_magnifier);a_magnifier.onclick=function(e){this.zoomInResult(number);}.bindObj(this);switch(zoneName){case"Localidades":case"Ruas":this.getCategorizedLocalityPanelHTML(poi,div_content);break;default:this.getCategorizedCommonPanelHTML(poi,div_content);break;}
var div_dashboardWrapper=document.createElement("div");div_dashboardWrapper.style.display="none";var div_tabsContentWrapper=document.createElement("div");div_tabsContentWrapper.className="shortlist_info";var div_weather=null;var ul_tabsHeader=null;var ul_tabNews=null;var ul_tabTraffic=null;var div_tabPhotos=null;var div_tabVideos=null;if(displayDashboard){if(!this.dashboard){this.dashboard={};}
this.dashboard[poi.POIId]={};this.dashboard[poi.POIId].html=div_dashboardWrapper;if(poi.Dashboard&&poi.Dashboard.Weather){div_weather=this.buildDashboardWeather(poi,div_weather);}
var tabs=[];if(poi.Dashboard){for(var e in poi.Dashboard){if(e==="Weather"){continue;}
if(e==="Videos"){continue;}
if(poi.Dashboard[e]){this.dashboard[poi.POIId][poi.Dashboard[e].Name]={};tabs.push(poi.Dashboard[e].Name);}}
ul_tabsHeader=this.buildDashboardTabs(tabs,poi);if(poi.Dashboard.News){ul_tabNews=this.buildDashboardNews(poi.Dashboard.News.Item);if(ul_tabNews){ul_tabNews.style.display="none";this.dashboard[poi.POIId]["Notícias"].content=ul_tabNews;div_tabsContentWrapper.appendChild(ul_tabNews);}}
if(poi.Dashboard.Traffic){ul_tabTraffic=this.buildDashboardTraffic(poi.Dashboard.Traffic.Item);if(ul_tabTraffic){ul_tabTraffic.style.display="none";this.dashboard[poi.POIId]["Trânsito"].content=ul_tabTraffic;div_tabsContentWrapper.appendChild(ul_tabTraffic);}}
if(poi.Dashboard.Photos){div_tabPhotos=this.buildDashboardPhotos(poi.Dashboard.Photos.Item);if(div_tabPhotos){div_tabPhotos.style.display="none";this.dashboard[poi.POIId].Fotos.content=div_tabPhotos;div_tabsContentWrapper.appendChild(div_tabPhotos);}}}}
div_item.appendChild(div_marker);div_item.appendChild(div_content);if(div_weather){div_dashboardWrapper.appendChild(div_weather);}
div_dashboardWrapper.appendChild(div_cleaner);if(ul_tabsHeader){div_dashboardWrapper.appendChild(ul_tabsHeader);div_dashboardWrapper.appendChild(div_tabsContentWrapper);}
div_item.appendChild(div_dashboardWrapper);div_item.appendChild(div_cleaner.cloneNode(true));return div_item;};SAPO.Maps.Search.prototype.getCategorizedCommonPanelHTML=function(poi,holder){var div_metadata=document.createElement("div");var div_description=document.createElement("div");div_metadata.className="metadata";div_description.className="item_description";div_metadata.innerHTML=poi.Name+"<br/>";var h_category=document.createElement("h5");h_category.className="search_panel_category_name";h_category.innerHTML="("+poi.Category+")";div_metadata.appendChild(h_category);var span_metadata=document.createElement("span");var span_address=document.createElement("span");span_address.className="address_line1";var span_address2=document.createElement("span");span_address.className="address_line2";var span_site=document.createElement("span");span_site.className="address_line2";span_site.className="site";var a_phone=document.createElement("a");a_phone.href="#";a_phone.className="phone";if(poi.Street&&poi.Street.length>0){span_address.innerHTML+=poi.Street;}
if(poi.ZipCode&&poi.ZipCode.length>0&&poi.ZipCode!=="0"){var zc=poi.ZipCode;if(poi.ZipCode.length>4){zc=(poi.ZipCode.substring(0,4)+"-"+poi.ZipCode.substring(4));}
span_address2.innerHTML+=zc;}
if(poi.Locality&&poi.Locality.length>0){if(span_address2.innerHTML!==""){span_address2.innerHTML+=", ";}
span_address2.innerHTML+=poi.Locality;}else{if(poi.Parish&&poi.Parish.length>0){if(span_address2.innerHTML!==""){span_address2.innerHTML+=", ";}
span_address2.innerHTML+=poi.Parish;}}
if(poi.Municipality&&poi.Municipality.length>0){if(poi.Locality!==poi.Municipality&&poi.Parish!==poi.Municipality){if(span_address2.innerHTML!==""){span_address2.innerHTML+=", ";}
span_address2.innerHTML+=poi.Municipality;}}
if(poi.District&&poi.District.length>0&&poi.Municipality!==poi.District){if(span_address2.innerHTML!==""){span_address2.innerHTML+=", ";}
span_address2.innerHTML+=poi.District;}
if(poi.Phone&&poi.Phone.length>0){a_phone.innerHTML+=poi.Phone;}
if(poi.URL&&poi.URL.length>0){var site=document.createElement('a');site.href=poi.URL;site.target='blank';site.appendChild(document.createTextNode('Site'));span_site.appendChild(site);if(poi.SourceId==='28'||poi.SourceId==='31'){OpenLayers.Event.observe(site,"click",function(evt){SapoMapsApp.WebtrendsAnalytics.track(['DCSext.linktype','website','DCSext.linkplace','result list'],poi);});}}
span_metadata.appendChild(span_address);span_metadata.appendChild(span_address2);if(span_site.innerHTML!==""){span_metadata.appendChild(span_site);}
if(a_phone.innerHTML!==""){span_metadata.appendChild(a_phone);}
div_metadata.appendChild(span_metadata);if(poi.Description){div_description.innerHTML=poi.Description.length>125?poi.Description.substr(0,125)+"[...]":poi.Description;}
if(poi.DetailXml&&poi.DetailXml.Details&&poi.DetailXml.Details.Pictures&&poi.DetailXml.Details.Pictures.Picture){var image=null;var images=poi.DetailXml.Details.Pictures.Picture.length?poi.DetailXml.Details.Pictures.Picture:[poi.DetailXml.Details.Pictures.Picture];if(!(images instanceof Array)){images=[images];}
for(var i=0;i<images.length;++i){if(images[i]&&images[i].primary==="true"){image=images[i];break;}}
if(!image){image=images[0]!==null?images[0]:'';}
var div_img=document.createElement("div");div_img.className="search_panel_img_wrapper";div_img.style.width="0px";div_img.style.height="0px";div_img.style.overflow="hidden";var img=document.createElement("img");img.width=88;img.height=66;OpenLayers.Event.observe(img,'load',function(){div_img.style.width="88px";div_img.style.height="66px";});var src=image.thumbnail;if(!src){src=image.value;}
if(!src){src=image;}
if(window.location.protocol.indexOf('https')!==-1){src=src.replace(/http:\/\/map/,'https://imgs');if(src.indexOf('https://')===-1){src='';}}
img.src=src;div_img.appendChild(img);holder.appendChild(div_img);}
holder.appendChild(div_metadata);holder.appendChild(div_description);};SAPO.Maps.Search.prototype.getPOIHTML=function(poi,marker){return SAPO.Maps.PoiInfoRenderer.getHTML(poi,marker,this,[{name:'Itinerário',func:SapoMapsApp.Itineraries.itineraryOptionClicked,context:SapoMapsApp.Itineraries}]);};SAPO.Maps.PoiInfoRenderer.getCommonHTML=function(poi,header,content,marker,holder){var name=document.createElement('h1');name.appendChild(document.createTextNode(poi.Name));header.appendChild(name);if(poi.Category&&poi.Category.length>0){var h2=document.createElement('h2');var categoryStr=poi.Category;h2.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(categoryStr)));header.appendChild(h2);}
if(poi.DetailXml&&poi.DetailXml.Details&&poi.DetailXml.Details.Pictures&&poi.DetailXml.Details.Pictures.Picture){var image=null;var images=poi.DetailXml.Details.Pictures.Picture.length?poi.DetailXml.Details.Pictures.Picture:[poi.DetailXml.Details.Pictures.Picture];if(!(images instanceof Array)){images=[images];}
for(var i=0;i<images.length;++i){if(images[i]&&images[i].primary==="true"){image=images[i];break;}}
if(!image){image=images[0]!==null?images[0]:'';}
var div_img=document.createElement("div");div_img.className="search_photo";div_img.style.width="0px";div_img.style.height="0px";div_img.style.display='none';var img=document.createElement("img");var a_img=document.createElement("a");a_img.target="_blank";a_img.href=image.value?image.value:image;img.style.width="150px";img.style.height="auto";var imgLoaded=function(){OpenLayers.Event.stopObservingElement(img);div_img.style.width="150px";div_img.style.height="auto";div_img.style.display='block';if(OpenLayers.Util.getRenderedDimensions(holder.innerHTML).w>500){holder.style.width='500px';}
if(marker.hasOpenedPopup()){marker.popup.contentUpdated();}};OpenLayers.Event.observe(img,'load',imgLoaded);var src=image.value?image.value:image;if(window.location.protocol.indexOf('https')!==-1){src=src.replace(/http:\/\/map/,'https://imgs');if(src.indexOf('https://')===-1){src='';}}
img.src=src;a_img.appendChild(img);div_img.appendChild(a_img);content.appendChild(div_img);}
var addressAndContacts=document.createElement('div');addressAndContacts.className='search_text';var address1=document.createElement('span');var address2=document.createElement('span');address1.className='address_pop_content_smapi';address2.className='address_pop_content_smapi';if(poi.Street&&poi.Street.length>0){address1.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(poi.Street)));}
if(poi.Parish&&poi.Parish.length>0){if(address1.innerHTML.length>0){address1.appendChild(document.createTextNode(', '));}
address1.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(poi.Parish)));}
if(poi.Municipality&&poi.Municipality.length>0&&poi.Municipality!==poi.Parish){if(address1.innerHTML.length>0){address1.appendChild(document.createTextNode(', '));}
address2.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(poi.Municipality)));}
if(poi.District&&poi.District.length>0&&poi.District!==poi.Municipality){if(address2.innerHTML.length>0){address2.appendChild(document.createTextNode(', '));}
address2.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(poi.District)));}
addressAndContacts.appendChild(address1);addressAndContacts.appendChild(address2);if(poi.ZipCode&&poi.ZipCode.length>0){var zc=poi.ZipCode;if(poi.ZipCode.length>4){zc=(poi.ZipCode.substring(0,4)+'-'+poi.ZipCode.substring(4));}
var postalCodeElement=document.createElement('span');postalCodeElement.className='address_pop_content_smapi zipcode_address_pop_content_smapi';postalCodeElement.appendChild(document.createTextNode(SAPO.Maps.Utils.htmlEntityDecode(zc)));addressAndContacts.appendChild(postalCodeElement);}
if(poi.Phone&&poi.Phone.length>0){var phoneElement=document.createElement('span');phoneElement.className='phone_pop_content_smapi';var phoneNumber=poi.Phone.substring(0,3)+' '+poi.Phone.substring(3,6)+' '+poi.Phone.substring(6,9);phoneElement.appendChild(document.createTextNode(phoneNumber));addressAndContacts.appendChild(phoneElement);}
if(poi.Fax&&poi.Fax.length>0){var faxElement=document.createElement('span');faxElement.className='fax_pop_content_smapi';var faxNumber=poi.Fax.substring(0,3)+' '+poi.Fax.substring(3,6)+' '+poi.Fax.substring(6,9);faxElement.appendChild(document.createTextNode(faxNumber));addressAndContacts.appendChild(faxElement);}
if(poi.URL&&poi.URL.length>0){var siteElement=document.createElement('span');var site=document.createElement('a');siteElement.className='url_pop_content_smapi';site.href=poi.URL;site.target='_blank';site.innerHTML='Ver Site';siteElement.appendChild(site);addressAndContacts.appendChild(siteElement);if(poi.SourceId==='28'||poi.SourceId==='31'){if(poi.URL.indexOf('pai.pt')!==-1){site.href=poi.URL+'?adrecip=sapomaps';}
OpenLayers.Event.observe(siteElement,"click",function(evt){SapoMapsApp.WebtrendsAnalytics.track(['DCSext.linktype','website','DCSext.linkplace','map'],poi);});}}
if(poi.EMail&&poi.EMail.length>0){var mailElement=document.createElement('span');var mail=document.createElement('a');mailElement.className='mail_pop_content_smapi';mail.href='mailto:'+poi.EMail;mail.innerHTML=poi.EMail;mailElement.appendChild(mail);addressAndContacts.appendChild(mailElement);if(poi.SourceId==='28'||poi.SourceId==='31'){OpenLayers.Event.observe(mailElement,"click",function(evt){SapoMapsApp.WebtrendsAnalytics.track(['DCSext.linktype','email address','DCSext.linkplace','map','DCSext.linkvalue',poi.EMail],poi);});}}
if(poi.DetailXml&&poi.DetailXml!=='null'){var moreInfoElement=document.createElement('span');var moreInfoLink=document.createElement('a');moreInfoElement.className='moreinfo_pop_content_smapi';moreInfoLink.id='moreInfoId';moreInfoLink.href='http://mapas.sapo.pt/POIDetails.aspx?poiid='+poi.POIId;moreInfoLink.innerHTML='Mais informa&ccedil;&otilde;es';moreInfoLink.target='_blank';moreInfoElement.appendChild(moreInfoLink);addressAndContacts.appendChild(moreInfoElement);}
content.appendChild(addressAndContacts);var sourceElement=document.createElement('p');sourceElement.className='smapi_popup_content_datasource';if(poi.Source&&poi.Source!==''){sourceElement.appendChild(document.createTextNode('Fonte: '));var sources=poi.Source.split('&');var source;var sourceLink;for(var j=0;j<sources.length;++j){source=sources[j];source=source.trim();sourceLink=document.createElement('a');sourceLink.target='_blank';if(source==='Páginas Amarelas'){source='pai.pt';if(poi.DetailXml.Details.YellowPages&&poi.DetailXml.Details.YellowPages.CustomerInfo&&poi.DetailXml.Details.YellowPages.CustomerInfo.ListingId){sourceLink.href='http://www.pai.pt/restaurantes/y:'+poi.DetailXml.Details.YellowPages.CustomerInfo.ListingId+'.html?adrecip=sapomaps';}}
else{if(source==='InfoPortugal'){source='SAPO Mapas';}
sourceLink.href='http://mapas.sapo.pt';}
sourceLink.innerHTML=source;if(j>0&&j<sources.length){sourceElement.appendChild(document.createTextNode(' & '));}
sourceElement.appendChild(sourceLink);}}
content.appendChild(sourceElement);if(poi.SourceId==='28'||poi.SourceId==='31'){OpenLayers.Event.observe(moreInfoLink,"click",function(evt){SapoMapsApp.WebtrendsAnalytics.track(['DCSext.linktype','business name','DCSext.linkplace','map'],poi);});}};
SapoMapsApp.Itineraries={map:null,panel:null,holder:null,itineraries:null,itinerariesTransports:null,mode:null,from:null,fromSelectedIndex:null,fromSelectedPage:null,to:null,toSelectedIndex:null,toSelectedPage:null,resultSelectedIndex:null,resultSelectedPage:null,middlePoints:null,startInput:null,endInput:null,itTypeElem:null,centerAt:null,zoomTo:null,pubElem:null,showsCheckBox:false,f_here:null,t_here:null,startMarker:null,endMarker:null,modeMap:{fastest:0,shortest:1,walk:2,transports:3},state:null,initialize:function(map,panel,holder,startInput,endInput,itTypeElem,pubElem,showsCheckBox,excludeTransports){this.map=map;this.panel=panel;this.holder=holder;this.startInput=startInput;this.endInput=endInput;this.itTypeElem=itTypeElem;this.pubElem=pubElem;this.showsCheckBox=showsCheckBox;var swapBt=document.getElementById('reverse_wrapper_img');if(swapBt){if(OpenLayers.Util.getBrowserName()==='msie'){document.getElementById('reverse_wrapper').className='reverse_wrapper_ie';}
OpenLayers.Event.observe(swapBt,'click',function(evt){var startValue=this.startInput.value;this.startInput.value=this.endInput.value;this.endInput.value=startValue;var from=this.from;this.from=this.to;this.to=from;var fromSelectedIndex=this.fromSelectedIndex;this.fromSelectedIndex=this.toSelectedIndex;this.toSelectedIndex=fromSelectedIndex;var fromSelectedPage=this.fromSelectedPage;this.fromSelectedPage=this.toSelectedPage;this.toSelectedPage=fromSelectedPage;getItinerary();OpenLayers.Event.stop(evt);}.bindObj(this));}
this.itineraries=new SAPO.Maps.Itineraries(map,panel,{language:'pt',borders:SapoMapsApp.borders,displayStartEndMarkers:true,displayMiddlePointsMarkers:true,editableRoute:true});this.itineraries.registerEvent('complete',this,this.complete);this.itineraries.registerEvent('complete',this,this.centerAndZoom);this.itineraries.registerEvent('timeout',this,this.centerAndZoom);this.itineraries.registerEvent('startSelected',this,this.startSelected);this.itineraries.registerEvent('endSelected',this,this.endSelected);this.itineraries.registerEvent('startingPOIS',this,this.startResults);this.itineraries.registerEvent('endingPOIS',this,this.endResults);this.itineraries.registerEvent('resultSelect',this,this.resultSelected);this.itineraries.registerEvent('resultUnselect',this,this.resultUnselected);this.itineraries.registerEvent('startEndMarkerMoved',this,this.startEndMarkerMoved);this.itineraries.registerEvent('complete',this,this.removeMarkers);this.itineraries.registerEvent('timeout',this,this.removeMarkers);this.itineraries.registerEvent('error',this,this.error);if(!excludeTransports){this.itinerariesTransports=new SapoMapsApp.TransportItineraries(map,panel,{language:'pt',borders:SapoMapsApp.borders});this.itinerariesTransports.registerEvent('complete',this,this.centerAndZoom);this.itinerariesTransports.registerEvent('timeout',this,this.centerAndZoom);this.itinerariesTransports.registerEvent('startSelected',this,this.startSelected);this.itinerariesTransports.registerEvent('endSelected',this,this.endSelected);this.itinerariesTransports.registerEvent('startingPOIS',this,this.startResults);this.itinerariesTransports.registerEvent('endingPOIS',this,this.endResults);this.itinerariesTransports.registerEvent('resultSelect',this,this.resultSelected);this.itinerariesTransports.registerEvent('resultUnselect',this,this.resultUnselected);this.itinerariesTransports.registerEvent('complete',this,this.removeMarkers);this.itinerariesTransports.registerEvent('error',this,this.error);}},getRoute:function(from,to,_mode,options){if(!from||!to){return;}
try{hideSearchFilters();}
catch(e1){}
try{document.getElementById("transporlis").style.display="none";calcResultPanelDimensionsForItineraries();}
catch(e2){}
if(!_mode){_mode=document.getElementById('mode').options[document.getElementById('mode').selectedIndex].value;}
this.f_here=null;this.t_here=null;this.from=from;this.to=to;this.mode=_mode;if(this.holder){this.holder.style.display='block';}
if(this.pubElem){this.pubElem.style.display='none';}
if(_mode==="transports"){this.itinerariesTransports.getItinerary(from,to,options);}
else{this.itineraries.getItinerary(from,to,{mode:_mode,showMapCheckbox:this.showsCheckBox,middlePoints:this.middlePoints});}
from=from.split(",");if(!isNaN(from[0])){from="Coordenadas";}
else{from=from.join(",");}
to=to.split(",");if(!isNaN(to[0])){to="Coordenadas";}
else{to=to.join(",");}
SapoMapsApp.Analytics.track("Itinerario","Percurso",from+"--"+to);},fromHere:function(lonlat,selectOposite){var stringLonLat=lonlat.lat.toFixed(6)+", "+lonlat.lon.toFixed(6);this.f_here=stringLonLat;if(this.startInput){this.startInput.value=stringLonLat;}
if(selectOposite){this.endInput.focus();this.endInput.select();}
if(this.startMarker){this.map.removeOverlay(this.startMarker);}
this.addStartMarker(new OpenLayers.LonLat(lonlat.lon,lonlat.lat));if(this.t_here){this.getRoute(this.f_here,this.t_here,this.itTypeElem.options[this.itTypeElem.selectedIndex].value);}},toHere:function(lonlat,selectOposite){var stringLonLat=lonlat.lat.toFixed(6)+", "+lonlat.lon.toFixed(6);this.t_here=stringLonLat;if(this.endInput){this.endInput.value=stringLonLat;}
if(selectOposite){this.startInput.focus();this.startInput.select();}
if(this.endMarker){this.map.removeOverlay(this.endMarker);}
this.addEndMarker(new OpenLayers.LonLat(lonlat.lon,lonlat.lat));if(this.f_here){this.getRoute(this.f_here,this.t_here,this.itTypeElem.options[this.itTypeElem.selectedIndex].value);}},showMiniMaps:function(){var directions=this.itineraries.getDirections();if(!directions){return;}
directions.showAllMaps();},hideMiniMaps:function(){var directions=this.itineraries.getDirections();if(!directions){return;}
directions.hideAllMaps();},isActive:function(){return this.from&&this.to;},closeOpenedPopup:function(){if(this.resultSelectedIndex!==null){if(this.mode==="transports"){this.itinerariesTransports.unselectResult(this.resultSelectedIndex);}
else{this.itineraries.unselectResult(this.resultSelectedIndex);}}},clear:function(clearStartState,clearEndState){if(typeof(clearStartState)==='undefined'){clearStartState=true;}
if(typeof(clearEndState)==='undefined'){clearEndState=true;}
this.itineraries.cancel();this.itinerariesTransports.cancel();if(clearStartState){this.from=null;this.fromSelectedIndex=null;this.fromSelectedPage=null;}
if(clearEndState){this.to=null;this.toSelectedIndex=null;this.toSelectedPage=null;}
if(clearStartState&&clearEndState){this.resultSelectedIndex=null;this.resultSelectedPage=null;}
this.middlePoints=[];if(this.mode==="transports"){this.itinerariesTransports.clear();}
else{this.itineraries.clear();}
if(this.holder){this.holder.style.display='none';}
if(this.pubElem){this.pubElem.style.display='block';}
this.removeMarkers();},getState:function(){if(!this.isActive()){return'';}
var state=encodeURIComponent(encodeURIComponent(this.from))+','+encodeURIComponent(encodeURIComponent(this.to))+','+encodeURIComponent(encodeURIComponent(this.mode));if(this.resultSelectedIndex!==null){state+=',idx'+this.resultSelectedIndex;if(this.resultSelectedPage){state+='-'+this.resultSelectedPage;}}
if(this.fromSelectedIndex!==null){state+=','+this.fromSelectedIndex+','+this.fromSelectedPage;}
if(this.toSelectedIndex!==null){state+=','+this.toSelectedIndex+','+this.toSelectedPage;}
if(this.middlePoints&&this.middlePoints.length>0){state+=',mp';var middlePoint;for(var i=0;i<this.middlePoints.length;++i){middlePoint=this.middlePoints[i];state+=','+middlePoint.lat+','+middlePoint.lon;}}
if(this.mode==="transports"){var all=document.getElementById("transportes_todos");state+=",transportsQuery,";if(all.checked){state+="all";}
else{var train=document.getElementById("transportes_comboios");var boat=document.getElementById("transportes_barco");var metro=document.getElementById("transportes_metro");var bus=document.getElementById("transportes_autocarro");if(!train.checked&&!boat.checked&&!metro.checked&&!bus.checked){state+="all";}
else{if(train.checked){state+="train";}
if(boat.checked){state+="-boat";}
if(metro.checked){state+="-metro";}
if(bus.checked){state+="-bus";}}}
var opts=this.itinerariesTransports.getOptions();state+=","+opts.routeMode;state+=","+opts.dateAndTime;}
return state;},setState:function(state){this.state={};var arr=state.split(',');try{var start=decodeURIComponent(arr[0]);var end=decodeURIComponent(arr[1]);var mode=decodeURIComponent(arr[2]);if(this.startInput){this.startInput.value=start;}
if(this.endInput){this.endInput.value=end;}
if(!start&&end){SapoMapsApp.Tooltip.showTooltip('Introduza o ponto de partida.');}
if(!end&&start){SapoMapsApp.Tooltip.showTooltip('Introduza o ponto de chegada.');}
if(document.getElementById('mode')){document.getElementById('mode').selectedIndex=this.modeMap[mode];}
if(arr.length>3){var idx=0;if(arr[3].substring(0,3)==='idx'){idx=1;var arr2=arr[3].split('-');var select=arr2[0].substring(3,arr2[0].length);this.state.resultSelectedIndex=Number(select);if(arr2.length>1){var page=arr2[1];this.state.resultSelectedPage=Number(page);}}
if(arr.length>(3+idx)){this.state.fromSelectedIndex=Number(arr[3+idx]);this.state.fromSelectedPage=Number(arr[4+idx]);}
if(arr.length>(5+idx)){this.state.toSelectedIndex=Number(arr[5+idx]);this.state.toSelectedPage=Number(arr[6+idx]);}}
var mp=state.indexOf('mp,');if(mp!==-1){mp=state.substring(mp+3,state.length);mp=mp.split(',');this.middlePoints=[];var lon,lat,lonlat;for(var l=0;l<mp.length;l+=2){lat=Number(mp[l]);lon=Number(mp[l+1]);lonlat=new OpenLayers.LonLat(lon,lat);this.middlePoints.push(lonlat);}}
if(mode==="transports"){var options=null;try{itinerariesModeChanged(false,true);}
catch(e3){}
var i;for(i=0;i<arr.length;++i){if(arr[i]==="transportsQuery"){break;}}
try{var modes=arr[i+1];modes=modes.split("-");document.getElementById("transportes_todos").checked=false;document.getElementById("transportes_comboios").checked=false;document.getElementById("transportes_barco").checked=false;document.getElementById("transportes_metro").checked=false;document.getElementById("transportes_autocarro").checked=false;for(var j=0;j<modes.length;++j){if(modes[j]==="all"){document.getElementById("transportes_todos").checked=true;}
if(modes[j]==="train"){document.getElementById("transportes_comboios").checked=true;}
if(modes[j]==="boat"){document.getElementById("transportes_barco").checked=true;}
if(modes[j]==="metro"){document.getElementById("transportes_metro").checked=true;}
if(modes[j]==="bus"){document.getElementById("transportes_autocarro").checked=true;}}
var routeMode=arr[i+2];if(routeMode==="LessStopOvers"){document.getElementById("transportes_transbordo").checked=true;}
if(routeMode==="Fastest"){document.getElementById("transportes_rapido").checked=true;}
if(routeMode==="LessPedestrian"){document.getElementById("transportes_pedonal").checked=true;}
var dateAndTime=arr[i+3];var date=dateAndTime.split("T")[0];date=date.split("-");document.getElementById("transporlis_data").value=date[2]+"/"+date[1]+"/"+date[0];var time=dateAndTime.split("T")[1].split(":");document.getElementById("transporlis_horas").selectedIndex=Number(time[0]);document.getElementById("transporlis_minutos").selectedIndex=Number(time[1]);}
catch(e2){options={};options.travelModes=[];var omodes=arr[i+1];omodes=omodes.split("-");for(var k=0;k<omodes.length;++k){if(omodes[k]==="all"){delete options.travelModes;break;}
if(omodes[k]==="train"){options.travelModes.push("Train");}
if(omodes[k]==="boat"){options.travelModes.push("Boat");}
if(omodes[k]==="metro"){options.travelModes.push("Metro");}
if(omodes[k]==="bus"){options.travelModes.push("Bus");}}
var orouteMode=arr[i+2];options.routeMode=orouteMode;var odateAndTime=arr[i+3];var odate=odateAndTime.split("T")[0];odate=odate.split("-");options.dateAndTime=odate[0]+"-"+odate[1]+"-"+odate[2]+"T";var otime=odateAndTime.split("T")[1].split(":");options.dateAndTime+=Number(otime[0])<10?("0"+Number(otime[0]).toString()):Number(otime[0]).toString();options.dateAndTime+=":";options.dateAndTime+=Number(otime[1])<10?("0"+Number(otime[1]).toString()):Number(otime[1]).toString();options.dateAndTime+=":00";}}
this.getRoute(start,end,mode,options);}catch(e1){var x=1;}},centerOnComplete:function(lonlat,zoom){this.centerAt=lonlat;this.zoomTo=zoom;},complete:function(directions){this.middlePoints=directions.getMiddlePoints();},centerAndZoom:function(){var resultSelectedPage,resultSelectedIndex;if(this.state!==null){resultSelectedPage=this.state.resultSelectedPage;resultSelectedIndex=this.state.resultSelectedIndex;}
else{resultSelectedPage=this.resultSelectedPage;resultSelectedIndex=this.resultSelectedIndex;}
var itineraries=this.mode==="transports"?this.itinerariesTransports:this.itineraries;try{if(resultSelectedPage&&resultSelectedPage!==itineraries.getSearch().getCurrentPage()){itineraries.registerEvent('pageChanged',this,this.centerAndZoom);itineraries.goToPage(resultSelectedPage);this.resultSelectedPage=null;return;}
if(this.centerAt){this.map.setMapCenter(this.centerAt);this.centerAt=null;}
if(this.zoomTo){this.map.zoomTo(this.zoomTo);this.zoomTo=null;}
if(resultSelectedIndex!==null){var idx=resultSelectedIndex;var page=resultSelectedPage;this.resultSelectedIndex=null;this.resultSelectedPage=null;itineraries.selectResult(idx);itineraries.unRegisterEvent('pageChanged',this,this.centerAndZoom);}}catch(e){}
this.state=null;},addStartMarker:function(lonlat){this.startMarker=new SAPO.Maps.Marker(lonlat,null,{markerImage:'http://imgs.sapo.pt/fotos_gis/site/iti2_markerA.png',markerAnchor:new OpenLayers.Pixel(-5,-28),size:new OpenLayers.Size(22,28)});this.map.addOverlay(this.startMarker);},addEndMarker:function(lonlat){this.endMarker=new SAPO.Maps.Marker(lonlat,null,{markerImage:'http://imgs.sapo.pt/fotos_gis/site/iti2_markerB.png',markerAnchor:new OpenLayers.Pixel(-5,-28),size:new OpenLayers.Size(22,28)});this.map.addOverlay(this.endMarker);},adjustMarkers:function(directions){if(this.mode==="transports"){this.removeMarkers();return;}
var start=directions.getStartLonLat();var end=directions.getEndLonLat();this.startMarker.setLonLat(start);this.endMarker.setLonLat(end);},removeMarkers:function(){if(this.startMarker){this.map.removeOverlay(this.startMarker);this.startMarker=null;}
if(this.endMarker){this.map.removeOverlay(this.endMarker);this.endMarker=null;}},startSelected:function(poi,index,page){this.fromSelectedIndex=index;this.fromSelectedPage=page;if(poi.Name){this.startInput.value=poi.Name;this.from=poi.Name;}
if(!this.startMarker){this.addStartMarker(new OpenLayers.LonLat(poi.Longitude,poi.Latitude));}else{this.startMarker.setLonLat(new OpenLayers.LonLat(poi.Longitude,poi.Latitude));}},endSelected:function(poi,index,page){this.toSelectedIndex=index;this.toSelectedPage=page;if(poi.Name){this.endInput.value=poi.Name;this.to=poi.Name;}
if(!this.endMarker){this.addEndMarker(new OpenLayers.LonLat(poi.Longitude,poi.Latitude));}else{this.endMarker.setLonLat(new OpenLayers.LonLat(poi.Longitude,poi.Latitude));}},resultSelected:function(idx,page){SapoMapsApp.closeInfoWindows();this.resultSelectedIndex=idx;this.resultSelectedPage=page;SapoMapsApp.Analytics.track("Itinerario","Percurso","PassoSeleccionado");},resultUnselected:function(){this.resultSelectedIndex=null;this.resultSelectedPage=null;},startResults:function(itinerary){var fromSelectedIndex,fromSelectedPage;if(this.state!==null){fromSelectedIndex=this.state.fromSelectedIndex;fromSelectedPage=this.state.fromSelectedPage;}
else{fromSelectedIndex=this.fromSelectedIndex;fromSelectedPage=this.fromSelectedPage;}
var pois=itinerary.getStartingPOIS();if(fromSelectedIndex===null||pois.length<=fromSelectedIndex){this.centerAndZoom(itinerary);}else{if(pois.length>1){itinerary.selectStartPOI(fromSelectedIndex,fromSelectedPage);}}},endResults:function(itinerary){var toSelectedIndex,toSelectedPage;if(this.state!==null){toSelectedIndex=this.state.toSelectedIndex;toSelectedPage=this.state.toSelectedPage;}
else{toSelectedIndex=this.toSelectedIndex;toSelectedPage=this.toSelectedPage;}
var pois=itinerary.getEndingPOIS();if(toSelectedIndex===null||pois.length<=toSelectedIndex){this.centerAndZoom(itinerary);}else{if(pois.length>1){itinerary.selectEndPOI(toSelectedIndex,toSelectedPage);}}},startEndMarkerMoved:function(itinerary,positions,start){if(start){this.from=positions.start.lat.toFixed(6)+', '+positions.start.lon.toFixed(6);document.getElementById('from').value=this.from;}
else{this.to=positions.end.lat.toFixed(6)+', '+positions.end.lon.toFixed(6);document.getElementById('to').value=this.to;}},itineraryOptionClicked:function(poi){var coords;if(poi&&poi.Latitude&&poi.Longitude){coords=new OpenLayers.LonLat(Number(poi.Longitude),Number(poi.Latitude));}
selectPanel('itineraryAndSearch',true);SapoMapsApp.Itineraries.toHere(coords,true);var aditionalContentHeight=selectedPanel===Panels.ItinerariesAndSearch?255:86;removePubToDisplayPanel(resultsElem.childNodes[0],aditionalContentHeight,resultsElem,false);itinerariesModeChanged();},error:function(iti,e){}};
SapoMapsApp.WhereAmI={map:null,markers:[],selectedMarker:null,addingAMarker:false,imgDiv:null,updateImgDivFunc:null,cancelFunc:null,firstUpdate:true,markerOut:true,lockMarker:false,panTimer:null,borders:null,BORDER_TOP:120,BORDER_LEFT:25,BORDER_BOTTOM:5,BORDER_RIGHT:10,MOVE_X:100,MOVE_Y:100,TIMER_INTERVAL:100,initialize:function(map,options){this.map=map;OpenLayers.Util.extend(this,options);this.map.events.register('click',this,this.click);},addMarker:function(lonlat){if(!lonlat){if(this.addingAMarker){return;}
this.map.events.register('mouseout',this,this.mouseout);this.map.events.register('mousemove',this,this.mousemove);this.map.events.register('click',this,this.markerAnchored);this.addDivImg();this.addingAMarker=true;}else{var marker=new SAPO.Maps.Marker(lonlat,{draggable:true});this.map.addOverlay(marker);this.markers.push(marker);marker.idx=this.markers.length-1;marker.title='';marker.description='';marker.registerEvent('click',this,this.openPopup);this.openPopup(marker);}},cancel:function(evt){if((!evt&&this.addingAMarker)||(evt&&evt.keyCode==27)||(evt&&evt.type==='mouseup')){this.map.events.unregister('mouseout',this,this.mouseout);this.map.events.unregister('mousemove',this,this.mousemove);this.map.events.unregister('click',this,this.markerAnchored);this.removeDivImg();this.addingAMarker=false;}},addDivImg:function(){var div=document.createElement('div');var img=document.createElement('img');img.src='http://imgs.sapo.pt/fotos_gis/mapas_api/v1.1/Markers/new/pin.png';img.width=22;img.height=28;div.style.position='absolute';div.style.zIndex='1000';div.appendChild(img);if(SAPO.Maps.Utils.checkIE6()){div.className+=' search_item_marker_ie6';img.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',src='"+img.src+"')";}
this.updateImgDivFunc=OpenLayers.Function.bindAsEventListener(this.updateDivImg,this);this.cancelFunc=OpenLayers.Function.bindAsEventListener(this.cancel,this);OpenLayers.Event.observe(document.body,'mousemove',this.updateImgDivFunc,true);OpenLayers.Event.observe(document.body,'keydown',this.cancelFunc,true);this.map.events.register('singlerightclick',this,this.cancelFunc);this.imgDiv=div;},removeDivImg:function(){this.imgDiv.parentNode.removeChild(this.imgDiv);OpenLayers.Event.stopObserving(document.body,'mousemove',this.updateImgDivFunc,true);OpenLayers.Event.stopObserving(document.body,'keydown',this.cancelFunc,true);this.map.events.unregister('singlerightclick',this,this.cancelFunc);this.firstUpdate=true;this.markerOut=true;this.imgDiv=null;this.updateImgDivFunc=null;this.cancelFunc=null;},updateDivImg:function(evt){if(this.lockMarker){return;}
if(this.firstUpdate){document.body.appendChild(this.imgDiv);this.firstUpdate=false;}
this.imgDiv.style.top=(evt.clientY-33)+'px';this.imgDiv.style.left=(evt.clientX-11)+'px';},mouseout:function(evt){this.mousemove(evt);},mousemove:function(evt){var size=this.map.size;if(evt.xy.x<=this.borders.left||evt.xy.y<=(this.borders.top-30)){this.panUp(evt.xy);}else{if(evt.xy.x+this.borders.right>=size.w||evt.xy.y+this.borders.bottom>=size.h){this.panDown(evt.xy);}
else{if(this.panTimer){window.clearInterval(this.panTimer);this.lockMarker=false;this.panTimer=null;}}}},panUp:function(xy){if(this.panTimer){return;}
if(this.markerOut){this.markerOut=false;return;}
this.lockMarker=true;var x=0;var y=0;if(xy.x<=this.borders.left&&xy.y<=(this.borders.top-30)){x=-1*this.MOVE_X;y=-1*this.MOVE_Y;}else{if(xy.x<=this.borders.left){x=-1*this.MOVE_X;}else{y=-1*this.MOVE_Y;}}
var map=this.map;this.panTimer=window.setInterval(function(){map.pan(x,y);},100);},panDown:function(xy){if(this.panTimer){return;}
if(this.markerOut){this.markerOut=false;return;}
this.lockMarker=true;var size=this.map.size;var x=0;var y=0;if(xy.x+this.borders.right>=size.w&&xy.y+this.borders.bottom>=size.h){x=this.MOVE_X;y=this.MOVE_Y;}else{if(xy.x+this.borders.right>=size.w){x=this.MOVE_X;}else{y=this.MOVE_Y;}}
var map=this.map;this.panTimer=window.setInterval(function(){map.pan(x,y);},100);},markerAnchored:function(evt){this.map.events.unregister('mouseout',this,this.mouseout);this.map.events.unregister('mousemove',this,this.mousemove);this.map.events.unregister('click',this,this.markerAnchored);this.removeDivImg();this.addingAMarker=false;var lonlat=this.map.getLonLatFromContainerPixel(evt.xy);var marker=new SAPO.Maps.Marker(lonlat,{draggable:true});map.addOverlay(marker);this.markers.push(marker);marker.idx=this.markers.length-1;marker.title='';marker.description='';marker.registerEvent('click',this,this.openPopup);this.openPopup(marker);},removeMarker:function(marker){this.markers.splice(marker.idx,1);this.map.removeOverlay(marker);},closeOpenedPopup:function(){if(this.selectedMarker){this.selectedMarker.closePopup();this.selectedMarker=null;}},setState:function(state){var markers=state.split('@');var m=false;var mInfo=false;var lat=false;var lon=false;var opened=false;var title=false;var desc=false;for(var i=0;i<markers.length;++i){mInfo=markers[i].split(',');try{lon=Number(mInfo[0]);lat=Number(mInfo[1]);opened=Number(mInfo[2]);title=mInfo.length>3?mInfo[3]:'';desc=mInfo.length>4?mInfo[4]:'';m=new SAPO.Maps.Marker(new OpenLayers.LonLat(lon,lat),{draggable:true});m.title=decodeURIComponent(title);m.description=decodeURIComponent(desc);m.idx=this.markers.length;m.registerEvent('click',this,this.openPopup);if(opened){this.openPopup(m);}
this.markers.push(m);this.map.addOverlay(m);}catch(e){}}},getState:function(){var str='';var m=false;var opened=false;var lonlat=false;var title=false;var desc=false;for(var i=0;i<this.markers.length;++i){m=this.markers[i];lonlat=m.getLonLat();opened=m.hasOpenedPopup()?1:0;title=encodeURIComponent(encodeURIComponent(m.title));desc=encodeURIComponent(encodeURIComponent(m.description));str+=lonlat.lon+','+lonlat.lat+','+opened+','+
title+','+desc;if(i<this.markers.length-1){str+='@';}}
return str;},openPopup:function(marker){var html=this.getHTML(marker);SapoMapsApp.closeInfoWindows();this.selectedMarker=marker;marker.openPopup(html,{borders:SapoMapsApp.borders});},getHTML:function(marker){if((marker.title&&marker.title.length>0)||(marker.description&&marker.description.length>0)){var html=document.createElement('div');var h3=document.createElement('h3');var div_content=document.createElement("div");var div_bts=document.createElement('div');var p_submit=document.createElement('p');var dummy=document.createElement('span');var span_holder_submit=document.createElement('span');var input_submit=document.createElement('input');var clearDiv=document.createElement("div");html.className="WhereAmI";div_content.className="description";div_bts.id='markerformcontrols';p_submit.className='submit_btn';span_holder_submit.className='rimg_button';input_submit.type='submit';input_submit.className='iti_submit';input_submit.value='Apagar';clearDiv.style.clear="both";div_bts.appendChild(p_submit);p_submit.appendChild(dummy);p_submit.appendChild(span_holder_submit);span_holder_submit.appendChild(input_submit);html.appendChild(h3);html.appendChild(div_content);html.appendChild(div_bts);html.appendChild(clearDiv);h3.appendChild(document.createTextNode(marker.title));var texts=marker.description.split("\n");var textNode;for(var i=0;i<texts.length;++i){if(i!==0){div_content.appendChild(document.createElement("br"));}
textNode=document.createTextNode(texts[i]);div_content.appendChild(textNode);}
var size=OpenLayers.Util.getRenderedDimensions(div_content.innerHTML);if(size.w>400){div_content.style.width="400px";html.style.width="420px";size=OpenLayers.Util.getRenderedDimensions(html.innerHTML);}
if(size.h>600){div_content.style.height="600px";div_content.style.overflow="auto";}
input_submit.onclick=function(){SapoMapsApp.WhereAmI.removeMarker(marker);return false;};return html;}
return this.createHTML(marker);},createHTML:function(marker){var html=document.createElement('div');var title_content=document.createElement('div');var title=document.createElement('h3');var title_span=document.createElement('span');var title_input=document.createElement('input');var description=document.createElement('h3');var textarea=document.createElement('textarea');var clearDiv=document.createElement("div");var markerBts=document.createElement('div');var a=document.createElement('a');var p=document.createElement('p');var dummy=document.createElement('span');var span=document.createElement('span');var saveBt=document.createElement('input');html.className="WhereAmI";title_content.className='marker_data';title_span.className='input_start';title_input.className='pop_input';p.className='submit_btn';span.className='rimg_button';saveBt.className='iti_submit';clearDiv.style.clear="both";title_input.id='pop_title_input';markerBts.id='markerformcontrols';title.innerHTML='T&iacute;tulo';title_input.type='text';description.innerHTML='Descri&ccedil;&atilde;o';textarea.rows=5;textarea.cols=20;a.innerHTML='Cancelar';saveBt.type='submit';saveBt.value='Guardar';title_content.appendChild(title);title_content.appendChild(title_span);title_content.appendChild(title_input);title_content.appendChild(description);title_content.appendChild(textarea);markerBts.appendChild(a);markerBts.appendChild(p);p.appendChild(dummy);p.appendChild(span);span.appendChild(saveBt);html.appendChild(title_content);html.appendChild(markerBts);html.appendChild(clearDiv);a.onclick=function(){SapoMapsApp.WhereAmI.removeMarker(marker);return false;};saveBt.onclick=function(){if(title_input.value.length===0&&textarea.value.length===0){return false;}
marker.title=title_input.value;marker.description=textarea.value;marker.closePopup();SapoMapsApp.WhereAmI.openPopup(marker);return false;};return html;}};
SapoMapsApp.Social={initialize:function(){SAPO.Maps.PoiInfoRenderer.getCommonHTML=(function(originalGetCommonHtml){return function(poi,header,content,marker,holder){originalGetCommonHtml.call(SAPO.Maps.PoiInfoRenderer,poi,header,content,marker,holder);if(!poi.DetailXml||poi.DetailXml==='null'){return;}
var divShare=SAPO.Maps.Utils.createNewElement('div',{className:'share'});for(var i=0;i<content.childNodes.length;++i){if(content.childNodes[i].className==='smapi_popup_content_datasource'){var divClear=SAPO.Maps.Utils.createNewElement('div',{className:'clear'});content.insertBefore(divClear,content.childNodes[i]);content.insertBefore(divShare,content.childNodes[i+1]);break;}}
var url=SapoMapsApp.Social.POIDetailsLink+poi.POIId;getPunyUrl(url,function(obj){SapoMapsApp.Social.appendShareIcons(obj.punyURL.ascii,url,poi,marker,divShare);},function(obj){SapoMapsApp.Social.appendShareIcons(url,url,poi,marker,divShare);});var divLike=SAPO.Maps.Utils.createNewElement('div',{className:'like'});header.appendChild(divLike);var iframeLike=SapoMapsApp.Social.getFacebookLikeButton(url);marker.registerEvent('popupopened',this,function(){divLike.appendChild(iframeLike);});marker.registerEvent('popupclosed',this,function(){divLike.innerHTML='';});};})(SAPO.Maps.PoiInfoRenderer.getCommonHTML);},appendShareIcons:function(url,baseUrl,poi,marker,divShare){ul=SAPO.Maps.Utils.createNewElement('ul');li=SAPO.Maps.Utils.createNewElement('li');li.appendChild(SapoMapsApp.Social.generateShareLink(SapoMapsApp.Social.Shortcuts.Facebook,baseUrl,poi.Name,marker));ul.appendChild(li);li=SAPO.Maps.Utils.createNewElement('li');li.appendChild(SapoMapsApp.Social.generateShareLink(SapoMapsApp.Social.Shortcuts.Twitter,url,poi.Name,marker));ul.appendChild(li);li=SAPO.Maps.Utils.createNewElement('li');li.appendChild(SapoMapsApp.Social.generateShareLink(SapoMapsApp.Social.Shortcuts.Stumble,baseUrl,poi.Name,marker));ul.appendChild(li);li=SAPO.Maps.Utils.createNewElement('li');li.appendChild(SapoMapsApp.Social.generateShareLink(SapoMapsApp.Social.Shortcuts.Digg,url,poi.Name,marker));ul.appendChild(li);divShare.appendChild(ul);},POIDetailsLink:'http://mapas.sapo.pt/POIDetails.aspx?poiid=',Shortcuts:{Facebook:0,Twitter:1,Buzz:2,Stumble:3,Digg:4},ShortcutsConfig:{Facebook:{text:'Partilhar no Facebook',title:'Vejam %name% nos Mapas do Sapo.',options:{'href':'http://www.facebook.com/sharer.php?u=%target%&t=%title%','target':'_blank','title':'Facebook'},icon:'http://js.sapo.pt/Assets/Images/ShareThis/facebook.gif'},Twitter:{text:'Partilhar no Twitter',title:'Acabei de visitar %name% no @sapomapas em %target%',options:{'href':'http://twitter.com/home?status=%title%','target':'_blank','title':'Twitter'},icon:'http://js.sapo.pt/Assets/Images/ShareThis/twitter.gif',maxTitleLength:140},Stumble:{text:'Partilhar no Stumble Upon',options:{'href':'http://www.stumbleupon.com/submit?url=%target%&title=%title%','target':'_blank','title':'StumbleUpon'},icon:'http://www.stumbleupon.com/images/stumbleit.gif'},Buzz:{text:"Partilhar no Buzz",options:{'href':'http://www.google.com/buzz/post?url=%target%&title=%title%','target':'_blank','title':'Buzz'}},Digg:{text:"Partilhar no Digg",options:{'href':'http://digg.com/submit?url=%target%&title=%title%','target':'_blank','title':'Digg'},icon:'http://js.sapo.pt/Assets/Images/ShareThis/digg.gif'}},generateShareLink:function(shareLinkType,target,name,marker){var anchor=null;var configurationOptions=null;switch(shareLinkType){case SapoMapsApp.Social.Shortcuts.Facebook:configurationOptions=this.ShortcutsConfig.Facebook;break;case SapoMapsApp.Social.Shortcuts.Twitter:configurationOptions=this.ShortcutsConfig.Twitter;break;case SapoMapsApp.Social.Shortcuts.Buzz:configurationOptions=this.ShortcutsConfig.Buzz;case SapoMapsApp.Social.Shortcuts.Stumble:configurationOptions=this.ShortcutsConfig.Stumble;break;case SapoMapsApp.Social.Shortcuts.Digg:configurationOptions=this.ShortcutsConfig.Digg;break;}
anchor=SAPO.Maps.Utils.createNewElement('a',configurationOptions.options);var title=null;if(configurationOptions.title!==undefined){title=SAPO.Maps.Utils.stringReplace(configurationOptions.title,{target:target,name:name});}else{title=name;}
if(configurationOptions.maxTitleLength!==undefined){if(title.length>configurationOptions.maxTitleLength){var excess=title.length-configurationOptions.maxTitleLength;excess+=3;name=name.substring(0,name.length-excess)+'...';title=SAPO.Maps.Utils.stringReplace(configurationOptions.title,{target:target,name:name});}}
anchor.href=SAPO.Maps.Utils.stringReplace(anchor.href,{target:target,title:encodeURIComponent(title)});if(configurationOptions.icon!==undefined){var img=SAPO.Maps.Utils.createNewElement('img',{src:configurationOptions.icon});anchor.appendChild(img);}
else{anchor.appendChild(document.createTextNode(configurationOptions.text));}
return anchor;},getFacebookLikeButton:function(href){var iframe=document.createElement('iframe');iframe.src="http://www.facebook.com/plugins/like.php?";iframe.src+="href="+escape(href);iframe.src+="&layout=button_count";iframe.src+="&show_faces=false";iframe.src+="&width=90";iframe.src+="&action=gosto";iframe.src+="&font=arial";iframe.src+="&colorscheme=light";iframe.src+="&height=20";iframe.scrolling="no";iframe.frameBorder="0";iframe.marginheight="0";iframe.marginwidth="0";iframe.style.width="90px";iframe.style.height="20px";iframe.style.border="0px";iframe.allowTransparency="true";return iframe;}};
SapoMapsApp.State={map:null,mapTypes:{m:null,s:null,h:null,t:null},initialize:function(map){this.map=map;var baselayers=map.getBaseLayers();this.mapTypes={m:baselayers.NORMAL_MAP,s:baselayers.SATELLITE_MAP,h:baselayers.HYBRID_MAP,t:baselayers.TERRAIN_MAP,tr:baselayers.TERRITORY_MAP};},updateMapState:function(state,queryStr){var lonlat=false,lat,lon,z;if(!queryStr.ll&&queryStr.M){this.loadInCompatibilityMode(state,queryStr);return;}
if(queryStr.ll){var ll=queryStr.ll.split(',');try{lat=Number(ll[0]);lon=Number(ll[1]);lonlat=new OpenLayers.LonLat(lon,lat);state.center=lonlat;}catch(e2){}}
z=false;if(queryStr.z){try{z=Number(queryStr.z);state.zoomLevel=z;}catch(e3){}}
if(queryStr.t){state.layer=queryStr.t;}},load:function(queryStr){var lonlat=null;if(queryStr.ll){var ll=queryStr.ll.split(',');try{lat=Number(ll[0]);lon=Number(ll[1]);lonlat=new OpenLayers.LonLat(lon,lat);}catch(e2){}}
z=false;if(queryStr.z){try{z=Number(queryStr.z);}catch(e3){}}
if(queryStr.mks){SapoMapsApp.WhereAmI.setState(queryStr.mks);}
if(queryStr.q){try{selectPanel('search');}catch(e8){}
SapoMapsApp.Search.setState(queryStr.q);if(lonlat!==null){SapoMapsApp.Search.centerOnComplete(lonlat,z);}}
if(queryStr.qs){try{selectPanel('search');}catch(e9){}
if(lonlat!==null){SapoMapsApp.Search.centerOnComplete(lonlat,z);}
SapoMapsApp.Search.getResults(unescape(queryStr.qs),true);}
if(queryStr.it){try{selectPanel('itinerary');}catch(e10){}
SapoMapsApp.Itineraries.setState(queryStr.it);if(lonlat!==null){SapoMapsApp.Itineraries.centerOnComplete(lonlat,z);}}
var setPOIsState=function(){SapoMapsApp.Search.search.unRegisterEvent('completed',this,setPOIsState);if(queryStr.poi){var arr=queryStr.poi.split(',');var layer=arr[0];switch(layer){case"pharm":SapoMapsApp.PharmsAtService.setStateAfterLoad(queryStr.poi);break;case"virtual":SapoMapsApp.VirtualVisits.setStateAfterLoad(queryStr.poi);break;case"panoramas":SapoMapsApp.Panoramas.setStateAfterLoad(queryStr.poi);break;case"traffic":SapoMapsApp.Traffic.setStateAfterLoad(queryStr.poi);break;case"saber":SapoMapsApp.Saber.setStateAfterLoad(queryStr.poi);break;case"weather":SapoMapsApp.Weather.setStateAfterLoad(queryStr.poi);break;case"photos":SapoMapsApp.Photos.setStateAfterLoad(queryStr.poi);break;case"videos":SapoMapsApp.Videos.setStateAfterLoad(queryStr.poi);break;case"news":SapoMapsApp.News.setStateAfterLoad(queryStr.poi);break;case"fuel":SapoMapsApp.Fuel.setStateAfterLoad(queryStr.poi);break;case"christmas":try{christmasSetStateAfterLoad(queryStr.poi);}
catch(z){}
break;default:SapoMapsApp.POIS.setStateAfterLoad(queryStr.poi);}}};SapoMapsApp.Search.search.registerEvent('completed',this,setPOIsState);setPOIsState();if(queryStr.l){try{var layers=queryStr.l.split(',');try{checkOptionsWhenLoadsState(layers);}catch(exception){}
var sublayers=false;for(var i=0;i<layers.length;++i){if(layers[i].indexOf('services')!=-1){sublayers=layers[i].split('-');for(var j=1;j<sublayers.length;++j){switch(sublayers[j]){case'traffic':SapoMapsApp.Traffic.activate();break;case'virtual':SapoMapsApp.VirtualVisits.activate();break;case'panoramas':SapoMapsApp.Panoramas.activate();break;case'saber':SapoMapsApp.Saber.activate();break;case'weather':SapoMapsApp.Weather.activate();break;case'photos':SapoMapsApp.Photos.activate();break;case'videos':SapoMapsApp.Videos.activate();break;case'news':SapoMapsApp.News.activate();break;case'fuel':SapoMapsApp.Fuel.activate();break;case'christmas':try{toggleChristmasLayer();}
catch(x){}
break;}}}else{var l=layers[i].split('-');if(l.length==1){SapoMapsApp.POIS.activateLayer(layers[i],null,true);}else{for(var k=1;k<l.length;++k){if(l[0]==='health'&&l[k]==='pharmaciesAtService'){SapoMapsApp.PharmsAtService.activate();}
else{SapoMapsApp.POIS.activateLayer(l[0],l[k],true);}}}}}
SapoMapsApp.POIS.refresh();}catch(e5){debug(e5);}}
if(queryStr.territory){try{SapoMapsApp.Territory.setState(queryStr.territory);}catch(e6){alert(e6);}}
if(queryStr.stats){try{SapoMapsApp.Stats.setState(queryStr.stats);}catch(e7){alert(e7);}}},save:function(isFromWidgetGenerator){var center=isFromWidgetGenerator===true?SAPO.Maps.Utils.getMapCenterConsideringBorders(this.map):this.map.getMapCenter();var baselayer=this.map.baseLayer;var maptype=false;for(var e in this.mapTypes){if(baselayer==this.mapTypes[e]){maptype=e;if(this.map.sapoSelectedBaseLayer){maptype='h';}
break;}}
var url=OpenLayers.Util.removeTail(location.href)+'?ll='+SAPO.Maps.Utils.round(center.lat,6)+','+SAPO.Maps.Utils.round(center.lon,6)+'&z='+this.map.getZoom()+'&t='+maptype;var mks=SapoMapsApp.WhereAmI.getState();if(mks.length>0){url+='&mks='+mks;}
var q=SapoMapsApp.Search.getState();if(q.length>0){url+='&q='+q;}
var it=SapoMapsApp.Itineraries.getState();if(it.length>0){url+='&it='+it;}
var layers=SapoMapsApp.POIS.getActiveLayers();if(SapoMapsApp.Traffic.isActive()||SapoMapsApp.VirtualVisits.isActive()||SapoMapsApp.Panoramas.isActive()||SapoMapsApp.Saber.isActive()||SapoMapsApp.Weather.isActive()||SapoMapsApp.Photos.isActive()||SapoMapsApp.Videos.isActive()||SapoMapsApp.News.isActive()||SapoMapsApp.Fuel.isActive()||isChristmasLayerActive){if(layers.length){layers+=',';}
layers+='services';if(SapoMapsApp.Traffic.isActive()){layers+='-traffic';}
if(SapoMapsApp.VirtualVisits.isActive()){layers+='-virtual';}
if(SapoMapsApp.Panoramas.isActive()){layers+='-panoramas';}
if(SapoMapsApp.Saber.isActive()){layers+='-saber';}
if(SapoMapsApp.Weather.isActive()){layers+='-weather';}
if(SapoMapsApp.Photos.isActive()){layers+='-photos';}
if(SapoMapsApp.Videos.isActive()){layers+='-videos';}
if(SapoMapsApp.News.isActive()){layers+='-news';}
if(SapoMapsApp.Fuel.isActive()){layers+='-fuel';}
if(isChristmasLayerActive){layers+='-christmas';}}
if(SapoMapsApp.PharmsAtService.isActive()){if(layers.length){layers+=',';}
layers+='health-pharmaciesAtService';}
if(layers.length>0){url+='&l='+layers;}
var poi=SapoMapsApp.POIS.getState();if(!poi){poi="";}
poi=poi.length>0?poi:SapoMapsApp.Traffic.getState();poi=poi.length>0?poi:SapoMapsApp.PharmsAtService.getState();poi=poi.length>0?poi:SapoMapsApp.VirtualVisits.getState();poi=poi.length>0?poi:SapoMapsApp.Panoramas.getState();poi=poi.length>0?poi:SapoMapsApp.Saber.getState();poi=poi.length>0?poi:SapoMapsApp.Weather.getState();poi=poi.length>0?poi:SapoMapsApp.Photos.getState();poi=poi.length>0?poi:SapoMapsApp.Videos.getState();poi=poi.length>0?poi:SapoMapsApp.News.getState();poi=poi.length>0?poi:SapoMapsApp.Fuel.getState();poi=poi.length>0?poi:(openedChristmasLayerPOI?"christmas,"+openedChristmasLayerPOI.poi.POIId:"");if(poi.length>0){url+="&poi="+poi;}
var windowOpened=false;if(!isFromWidgetGenerator){var acoresWindow=SapoMapsApp.Territory.wmanager.getAcoresWindow();var madeiraWindow=SapoMapsApp.Territory.wmanager.getMadeiraWindow();windowOpened=acoresWindow&&!acoresWindow.windowControl.isHidden();windowOpened=windowOpened?windowOpened:madeiraWindow&&!madeiraWindow.windowControl.isHidden();}
if(baselayer===this.map.getBaseLayers().TERRITORY_MAP||windowOpened){var territory=SapoMapsApp.Territory.getState();if(territory.length>0){url+="&territory="+territory;}}
var stats=SapoMapsApp.Stats.getState();if(stats){url+="&stats="+stats;}
return url;},loadInCompatibilityMode:function(state,queryStr){var old_link=false;if(queryStr.o!==null){switch(queryStr.o){case'0':state.layer='m';break;case'1':state.layer='s';break;case'2':state.layer='h';break;}}
var lonlat,z;if(queryStr.M){var m=queryStr.M.split(',');try{var lat=Number(m[0]);var lon=Number(m[1]);z=m.length>2?Number(m[2]):null;lonlat=new OpenLayers.LonLat(lon,lat);state.center=lonlat;state.zoomLevel=z;}catch(e1){}
try{var layersState='';if(queryStr.M.indexOf('-restauracao-')!==-1){if(layersState.length>0){layersState+=',';}
layersState+='restaurants';SapoMapsApp.POIS.activateLayer('restaurants');}
if(queryStr.M.indexOf('-compras-')!==-1){if(layersState.length>0){layersState+=',';}
layersState+='shopping';SapoMapsApp.POIS.activateLayer('shopping');}
if(queryStr.M.indexOf('-desporto-')!==-1){if(layersState.length>0){layersState+=',';}
layersState+='sports';SapoMapsApp.POIS.activateLayer('sports');}
if(queryStr.M.indexOf('-passeios-')!==-1){if(layersState.length>0){layersState+=',';}
layersState+='tourism';SapoMapsApp.POIS.activateLayer('tourism');}
if(queryStr.M.indexOf('-seguranca-')!==-1){if(layersState.length>0){layersState+=',';}
layersState+='security';SapoMapsApp.POIS.activateLayer('security');}
if(queryStr.M.indexOf('-turismo-')!==-1&&queryStr.M.indexOf('-passeios-')===-1){if(layersState.length>0){layersState+=',';}
layersState+='tourism';SapoMapsApp.POIS.activateLayer('tourism');}
if(queryStr.M.indexOf('-hoteis-')!==-1){if(layersState.length>0){layersState+=',';}
layersState+='hotels';SapoMapsApp.POIS.activateLayer('hotels');}
if(queryStr.M.indexOf('-cultura-')!==-1){if(layersState.length>0){layersState+=',';}
layersState+='culture';SapoMapsApp.POIS.activateLayer('culture');}
if(queryStr.M.indexOf('-ensino-')!==-1){if(layersState.length>0){layersState+=',';}
layersState+='education';SapoMapsApp.POIS.activateLayer('education');}
if(queryStr.M.indexOf('-saude-')!==-1){if(layersState.length>0){layersState+=',';}
layersState+='health';SapoMapsApp.POIS.activateLayer('health');}
if(queryStr.M.indexOf('-utilidades-')!==-1){if(layersState.length>0){layersState+=',';}
layersState+='utilities';SapoMapsApp.POIS.activateLayer('utilities');}
if(queryStr.M.indexOf('-farmacias-')!==-1){if(queryStr.M.indexOf('-saude-')===-1){if(layersState.length>0){layersState+=',';}
layersState+='health-farmsAtService';}
SapoMapsApp.PharmsAtService.activate();}
if(queryStr.M.indexOf('-transito-')!==-1){if(layersState.length>0){layersState+=',';}
layersState+='services-traffic';SapoMapsApp.Traffic.activate();}
if(queryStr.M.indexOf('-virtual-')!==-1){if(layersState.indexOf('services')===-1){layersState+='services';}
layersState+='-virtualVisits';SapoMapsApp.VirtualVisits.activate();}
if(layersState.length>0){checkOptionsWhenLoadsState(layersState.split(','));}}catch(e2){}
try{var beginMks=window.location.href.indexOf('M=');var endMks=window.location.href.indexOf('&',beginMks);if(endMks===-1){endMks=window.location.href.length;}
var markers=window.location.href.substring(beginMks,endMks).split(';');if(markers.length>1){var marker=false;var mks="";for(var i=1;i<markers.length;++i){if(mks.length>0){mks+='@';}
marker=markers[i].split(',');mks+=marker[1]+',';mks+=marker[0]+',';mks+=marker[3]+',';mks+=unescape(unescape(unescape(unescape(this.removeSpecialCharacters_compatibilityMode(marker[2])))));}
if(mks){SapoMapsApp.WhereAmI.setState(mks);}}}catch(e3){}}
if(queryStr.t){selectPanel('search');SapoMapsApp.Search.setState(queryStr.t);SapoMapsApp.Search.centerOnComplete(lonlat,z);}
if(queryStr.P){try{selectPanel('itinerary');var startIt=window.location.href.indexOf('P=');var endIt=window.location.href.indexOf('&',startIt);if(endIt===-1){endIt=window.location.href.length;}
var it=window.location.href.substring(startIt,endIt);var arr=it.split(';');var mode='fastest';switch(queryStr){case'curto':mode='shortest';break;case'a pé':mode='walk';break;case'rapido':mode='fastest';break;}
var startLoc=arr[1].split(',')[2];var endLoc=arr[2].split(',')[2];SapoMapsApp.Itineraries.setState(decodeURIComponent(decodeURIComponent(startLoc))+","+decodeURIComponent(decodeURIComponent(endLoc))+","+mode);SapoMapsApp.Itineraries.centerOnComplete(lonlat,z);}catch(e4){}}
if(queryStr.ts){selectPanel('search');if(queryStr.area!="visible"){SapoMapsApp.Search.centerOnComplete(lonlat,z);}
var bbox=queryStr.area==="visible";SapoMapsApp.Search.getResults(unescape(queryStr.ts),true,bbox);}},removeSpecialCharacters_compatibilityMode:function(str){var lastStr=false;var curr_str=str;while(curr_str!=lastStr){lastStr=curr_str;curr_str=curr_str.replace('+',' ');}
return curr_str;}};
SapoMapsApp.Cookie={map:null,selectedColor:null,cookieName:'SAPO-Mapas',saveLocation:false,saveCategories:true,initialize:function(map){this.map=map;},save:function(){var cookieValue='';var minimap=this.map.getControlsByClass('SAPO.Maps.Control.MiniMap2')[0];cookieValue=minimap.isOpened()?'minimap=1':'minimap=0';var mousePos=this.map.getControlsByClass('SAPO.Maps.Control.MousePosition2')[0];cookieValue+=mousePos.isOpened()?'&mousePos=1':'&mousePos=0';if(this.saveLocation){var lonlat=this.map.getMapCenter();cookieValue+='&ll='+lonlat.lon+','+lonlat.lat;var zoom=this.map.getZoom();cookieValue+='&z='+zoom;cookieValue+="&saveLocation=true";}
var baseLayer=this.map.baseLayer;var mapLayers=this.map.getBaseLayers();var viewType=false;switch(baseLayer){case mapLayers.NORMAL_MAP:viewType='m';break;case mapLayers.SATELLITE_MAP:if(this.map.sapoSelectedBaseLayer){viewType='h';}
else{viewType='s';}
break;case mapLayers.HYBRID_MAP:viewType='h';break;case mapLayers.TERRAIN_MAP:viewType='t';break;}
cookieValue+='&t='+viewType;if(this.saveCategories){var layers=SapoMapsApp.POIS.getActiveLayers();if(SapoMapsApp.Traffic.isActive()||SapoMapsApp.VirtualVisits.isActive()||SapoMapsApp.Panoramas.isActive()||SapoMapsApp.Saber.isActive()||SapoMapsApp.Weather.isActive()||SapoMapsApp.Photos.isActive()||SapoMapsApp.Videos.isActive()||SapoMapsApp.News.isActive()){if(layers.length){layers+=',';}
layers+='services';if(SapoMapsApp.Traffic.isActive()){layers+='-traffic';}
if(SapoMapsApp.VirtualVisits.isActive()){layers+='-virtual';}
if(SapoMapsApp.Panoramas.isActive()){layers+='-panoramas';}
if(SapoMapsApp.Saber.isActive()){layers+='-saber';}
if(SapoMapsApp.Weather.isActive()){layers+='-weather';}
if(SapoMapsApp.Photos.isActive()){layers+='-photos';}
if(SapoMapsApp.Videos.isActive()){layers+='-videos';}
if(SapoMapsApp.News.isActive()){layers+='-news';}}
if(SapoMapsApp.PharmsAtService.isActive()){if(layers.length){layers+=',';}
layers+='health-pharmaciesAtService';}
if(layers){cookieValue+='&l='+layers;}
cookieValue+='&saveCategories=true';}
if(this.selectedColor){cookieValue+='&skin='+this.selectedColor;}
SAPO.Utility.Cookie.set(this.cookieName,cookieValue);},saveTheme:function(theme){this.selectedColor=theme;var cookie=SAPO.Utility.Cookie.get()[this.cookieName];var state=this.loadCookieIntoAnObject(cookie);if(!state){return;}
state.skin=theme;var cookieValue=this.fromObject2String(state);SAPO.Utility.Cookie.set(this.cookieName,cookieValue);},saveSettings:function(){this.saveLocation=document.getElementById("save_location_checkbox").checked;this.saveCategories=document.getElementById("save_categories_checkbox").checked;},updateMapState:function(state){var cookie=SAPO.Utility.Cookie.get()[this.cookieName];if(!cookie){return false;}
var params=this.loadCookieIntoAnObject(cookie);if(params.ll){var ll=params.ll.split(',');try{lon=Number(ll[0]);lat=Number(ll[1]);var lonlat=new OpenLayers.LonLat(lon,lat);state.center=lonlat;}catch(e2){}}
if(state.z){try{var z=Number(params.z);state.zoomLevel=z;}catch(e3){}}
if(params.t){state.layer=params.t;}
if(params.minimap){state.miniMapOpen=Number(params.minimap);}
if(params.mousePos){state.mousePositionOpen=Number(params.mousePos);}},load:function(){var cookie=SAPO.Utility.Cookie.get()[this.cookieName];if(!cookie){return false;}
var state=this.loadCookieIntoAnObject(cookie);if(state.l){try{var layers=state.l.split(',');try{checkOptionsWhenLoadsState(layers);}catch(excp){}
var sublayers=false;for(var i=0;i<layers.length;++i){if(layers[i].indexOf('services')!=-1){sublayers=layers[i].split('-');for(var j=1;j<sublayers.length;++j){switch(sublayers[j]){case'traffic':SapoMapsApp.Traffic.activate();break;case'virtual':SapoMapsApp.VirtualVisits.activate();break;case'panoramas':SapoMapsApp.Panoramas.activate();break;case'saber':SapoMapsApp.Saber.activate();break;case'weather':SapoMapsApp.Weather.activate();break;case'photos':SapoMapsApp.Photos.activate();break;case'videos':SapoMapsApp.Videos.activate();break;case'news':SapoMapsApp.News.activate();break;}}}else{var l=layers[i].split('-');if(l.length==1){SapoMapsApp.POIS.activateLayer(layers[i],null,true);}else{for(var k=1;k<l.length;++k){if(l[0]==='health'&&l[k]==='pharmaciesAtService'){SapoMapsApp.PharmsAtService.activate();}
else{SapoMapsApp.POIS.activateLayer(l[0],l[k],true);}}}}}
SapoMapsApp.POIS.refresh();}catch(e5){debug(e5);}}
if(!state.saveCategories){this.deactivateSaveCategories();}
else{this.activateSaveCategories();}
if(state.saveLocation){this.activateSaveLocation();}
else{this.deactivateSaveLocation();}
if(state.skin){this.selectedColor=state.skin;selectCurrentHTMLTheme(this.selectedColor);}
return true;},loadCookieIntoAnObject:function(cookieValue){if(!cookieValue){return;}
var arr=cookieValue.split('&');var ret={};var entry=false;for(var i=0;i<arr.length;++i){entry=arr[i].split('=');ret[entry[0]]=entry[1];}
return ret;},fromObject2String:function(obj){var str='';for(var e in obj){if(obj[e]){if(str.length>0){str+='&';}
str+=e+'='+obj[e];}}
return str;},getSettings:function(){this.saveLocation=document.getElementById("save_location_checkbox").checked;this.saveCategories=document.getElementById("save_categories_checkbox").checked;},activateSaveLocation:function(){document.getElementById("save_location_checkbox").checked=true;this.saveLocation=true;},deactivateSaveLocation:function(){document.getElementById("save_location_checkbox").checked=false;this.saveLocation=false;},activateSaveCategories:function(){document.getElementById("save_categories_checkbox").checked=true;this.saveCategories=true;},deactivateSaveCategories:function(){document.getElementById("save_categories_checkbox").checked=false;this.saveCategories=false;applyDefaults();}};
SapoMapsApp.CMap={width:425,height:350,showPanel:true,getCode:function(width,height,extraParams){if(width&&height){this.setSize(width,height);}
if(!extraParams){extraParams="";}
this.showPanel=this.isPanelOpened();var iframe="<iframe frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" ";iframe+="width=\""+this.getWidthForIframe()+"\" height=\""+this.getHeightForIframe()+"\"";iframe+="src=\""+this.getURLForIframe()+extraParams+"\"></iframe>";return iframe;},isPanelOpened:function(){var url=this.getURLForIframe();if(url.contains("q=")||url.contains("it=")){return true;}
return false;},getWidthForIframe:function(){return this.width+(this.showPanel===true?325:0);},getHeightForIframe:function(){return this.height;},getURLForIframe:function(){var url="http://"+location.host+location.pathname+"cmap/cmap.html?sz="+this.width+","+this.height+"&";var stateURL=SapoMapsApp.State.save(true);var relevantStateURL=stateURL.split("?")[1];url+=relevantStateURL;url=url.replace(/cmap\/cmap.htmlcmap\/cmap.html/,"cmap/cmap.html");return url;},setSize:function(width,height){this.width=width;this.height=height;}};
SAPO.Maps.ReverseGeocoder=OpenLayers.Class({syndication:null,initialize:function(){this.syndication=new SAPO.Communication.Syndication();},reverseGeocode:function(lonlat,onCompleteCallback,onErrorCallback){if(!lonlat||!onCompleteCallback){return;}
var url="http://services.sapo.pt/Maps/GetRoute/JSON?mode=rapido&pts="+lonlat.lon+","+lonlat.lat+","+lonlat.lon+","+lonlat.lat;var reqID=this.syndication.push(url,{timeout:4,onComplete:this.onComplete.bind(this),onTimeout:this.onTimeout.bind(this),optOnComplete:{onComplete:onCompleteCallback,onError:onErrorCallback}});this.syndication.run(reqID);},onComplete:function(obj,args){if(!obj.segs){try{args.onError();}
catch(e1){}}
try{args.onComplete(obj.segs[0].st);}
catch(e2){}},onTimeout:function(){if(this.onErrorCallback){try{this.onErrorCallback();}
catch(e1){}}
this.onCompleteCallback=this.onErrorCallback=null;},CLASS_NAME:'ReverseGeocoder'});
SapoMapsApp.Territory={map:null,wmanager:null,mappings:{area:{c:'Country',n1:'NUTS1',n2:'NUTS2',n3:'NUTS3',d:'District',m:'Municipality',p:'Parish'}},initialize:function(map,windowManager){this.map=map;this.wmanager=windowManager;},getState:function(){var state={};var layerStyle=SAPO.Maps.Utils.getDifferences(this.map.getBaseLayers().TERRITORY_MAP.getDefaultParameters(),this.map.getBaseLayers().TERRITORY_MAP.getLayerStyle());var shape=layerStyle.shape;for(var e in this.mappings.area){if(this.mappings.area[e]==shape){state.a=e;break;}}
if('showLabels'in layerStyle){state.n=layerStyle.showLabels?1:0;}
if('showLabelsInCentroid'in layerStyle){state.nc=layerStyle.showLabelsInCentroid?1:0;}
if(layerStyle.showIcons){state.si=encodeURIComponent(layerStyle.iconUrl);}
if('color'in layerStyle){state.ac=encodeURIComponent(layerStyle.color);}
if('outlineColor'in layerStyle){state.so=encodeURIComponent(layerStyle.outlineColor);}
state.whf=this.wmanager.isHeaderAndFooterVisible()?1:0;state.wo=this.wmanager.getWindowsOpacity();if(this.wmanager.getWindowsColor()!==null){var color=this.wmanager.getWindowsColor();state.wc=color.split('#')[1];}
var acoresWindow=this.wmanager.getAcoresWindow();if(acoresWindow!==null&&!acoresWindow.windowControl.isHidden()){state.av=1;state.ap=acoresWindow.percentages.width.toFixed(3)+","+
acoresWindow.percentages.height.toFixed(3)+","+
acoresWindow.percentages.top.toFixed(3)+","+
acoresWindow.percentages.left.toFixed(3);}
var madeiraWindow=this.wmanager.getMadeiraWindow();if(madeiraWindow!==null&&!madeiraWindow.windowControl.isHidden()){state.mv=1;state.mp=madeiraWindow.percentages.width.toFixed(3)+","+
madeiraWindow.percentages.height.toFixed(3)+","+
madeiraWindow.percentages.top.toFixed(3)+","+
madeiraWindow.percentages.left.toFixed(3);}
return SAPO.Utility.Serialize.get(state);},setState:function(str){var state=eval('('+str+')');var style={};if(state.a){style.shape=this.mappings.area[state.a];}
if(state.n){style.showLabels=state.n===0?false:true;}
if(state.nc){style.showLabelsInCentroid=state.nc===0?false:true;}
if(state.si){style.showIcons=true;style.iconUrl=decodeURIComponent(state.si);}
if(state.ac){style.color=decodeURIComponent(state.ac);}
if(state.so){style.outlineColor=decodeURIComponent(state.so);}
this.map.getBaseLayers().TERRITORY_MAP.setLayerStyle(style);if(Number(state.av)==1){var acoresPerc=null;if(state.ap){var ap_arr=state.ap.split(',');acoresPerc={width:Number(ap_arr[0]),height:Number(ap_arr[1]),top:Number(ap_arr[2]),left:Number(ap_arr[3])};}
this.wmanager.createAcoresWindow(acoresPerc,true);}
if(Number(state.mv)==1){var madeiraPerc=null;if(state.ap){var mp_arr=state.mp.split(',');madeiraPerc={width:Number(mp_arr[0]),height:Number(mp_arr[1]),top:Number(mp_arr[2]),left:Number(mp_arr[3])};}
this.wmanager.createMadeiraWindow(madeiraPerc,true);}
if(Number(state.whf)===0){this.wmanager.toggleHeaderAndFooter(false);}
if(!isNaN(Number(state.wo))){this.wmanager.setWindowsOpacity(Number(state.wo));}
if(state.wc){this.wmanager.setWindowsColor("#"+state.wc);}}};
SapoMapsApp.Stats={map:null,modal:null,modalBackground:null,searchBox:null,searchResultsWraper:null,modalWidth:800,modalHeight:350,selectedModalTab:"themes",modalContentNamePrefix:"modal_content_",modalTabNamePrefix:"modal_tab_",resizeCallback:null,searchTerm:null,pageNumber:1,recordsPerPage:7,numberOfPagesShown:5,statisticExplorer:null,statisticsSearch:null,showingStatistic:false,themes:null,subThemes:null,themesDropDown:null,subThemesDropDown:null,indicatorsDropDown:null,waitDiv:null,addIndicatorToCompare:false,optionsPanel:null,windowManager:null,printPage:false,legendHolder:null,initialize:function(map,panel,windowManager,printPage,legendHolder){this.map=map;this.optionsPanel=panel;this.windowManager=windowManager;this.printPage=printPage;this.legendHolder=legendHolder;if(!printPage){this.statisticsSearch=new SAPO.Maps.StatisticsSearch();this.subThemes={};this.modal=document.getElementById("modal_content");this.modalBackground=document.getElementById("modal_background");this.searchBox=document.getElementById("stats_textBox");this.searchResultsWraper=document.getElementById("stats_search_results");this.themesDropDown=document.getElementById("theme_list");this.subThemesDropDown=document.getElementById("sub_theme_list");this.indicatorsDropDown=document.getElementById("indicator_list");this.resizeCallback=this.positionModalBox.bindObj(this);this.attachEvents();OpenLayers.Event.observe(window,'resize',this.resizePanel);}},closeOpenedPopup:function(){if(this.statisticExplorer){this.statisticExplorer.closePopup();}},getState:function(){if(!this.statisticExplorer||this.statisticExplorer.getNrIndicators()===0){return"";}
var state={lo:this.statisticExplorer.isLabelsControlOpened()?1:0};var indicators=this.statisticExplorer.getIndicators();var key=false;for(var i=0,len=indicators.length;i<len;++i){key='i'+(i+1);state[key]=this.getIndicatorState(indicators[i]);if(indicators[i].getIsSelectedTab()){state.si=i+1;}}
if(this.statisticExplorer.isPopupOpened()){var ll=this.statisticExplorer.getPopupLonLat();state.ll=ll.lat+","+ll.lon;state.t=this.statisticExplorer.getPopupIndicatorSelected().getCurrentPopupTab();}
return encodeURIComponent(SAPO.Utility.Serialize.get(state));},getIndicatorState:function(indicator){var dimensions=indicator.getSelectedDimensions();var selected=[],d=false;for(var i=0,len=dimensions.length;i<len;++i){d={t:dimensions[i].type,id:dimensions[i].id,o:dimensions[i].order};if(dimensions[i].territoryView){d.tv=dimensions[i].territoryView;}
selected.push(d);}
var state={id:indicator.getIndicatorId(),r:indicator.getIndicatorRepresentationType(),d:selected};if(state.r==SAPO.Maps.Indicator.representationTypes.territory){state.o=indicator.getLayerOpacity();state.ci=indicator.getLayerColors().startColor;state.cf=indicator.getLayerColors().endColor;state.nc=indicator.getNrClasses();}else{var chartSize=indicator.getChartSize();state.cw=chartSize.width;state.ch=chartSize.height;var chartAxis=indicator.getSelectedAxisDimension();var idsArr=[];for(var j=0;j<chartAxis.ids.length;++j){idsArr.push(chartAxis.ids[j].Id);}
state.ca={t:chartAxis.type,o:chartAxis.order,ids:idsArr};}
return state;},setState:function(state){state=decodeURIComponent(state);state=eval('('+state+')');if(!this.statisticExplorer){this.createStatisticExplorer();}
if(!this.printPage){selectPanel('statistics');this.resizePanel();}
this.showingStatistic=true;var id1=this.setIndicatorState(state.i1,state.t);var id2=false;if(state.i2){id2=this.setIndicatorState(state.i2,state.t);}
var nrIndicators=id2?2:1;var count=0;function openPopup(){++count;if(count!=nrIndicators){return;}
var arr=state.ll.split(',');var ll=new OpenLayers.LonLat(Number(arr[1]),Number(arr[0]));var selectedIndicatorId=Number(state.si)==1?id1:id2;var selectedIndicator=this.statisticExplorer.getIndicator(selectedIndicatorId);this.statisticExplorer.openPopup(ll,selectedIndicator);this.statisticExplorer.getIndicator(id1).events.unregister('indicatorDetailsComplete',this,openPopup);if(id2){this.statisticExplorer.getIndicator(id2).events.unregister('indicatorDetailsComplete',this,openPopup);}}
if(state.ll){this.statisticExplorer.getIndicator(id1).events.register('indicatorDetailsComplete',this,openPopup);if(id2){this.statisticExplorer.getIndicator(id2).events.register('indicatorDetailsComplete',this,openPopup);}}
if(!this.printPage){this.statisticExplorer.toggleLabelsControl(Number(state.lo));}},setIndicatorState:function(indicatorState,tab){var indicator=indicatorState;var arr=[],helperObj=false;for(var j=0;j<indicator.d.length;++j){helperObj={type:indicator.d[j].t,id:indicator.d[j].id,order:indicator.d[j].o};if(indicator.d[j].tv){helperObj.territoryView=indicator.d[j].tv;}
arr.push(helperObj);}
indicator.d=arr;var options={currentRepresentationType:Number(indicator.r),selectedDimensions:indicator.d};if(tab){options.currentPopupTab=tab;}
if(Number(indicator.r)==SAPO.Maps.Indicator.representationTypes.territory){options.layerOpacity=Number(indicator.o);options.color={startColor:decodeURIComponent(indicator.ci),endColor:decodeURIComponent(indicator.cf)};options.nrClasses=indicator.nc;}else{options.chartWidth=indicator.cw;options.chartHeight=indicator.ch;var idsArray=[];for(var i=0;i<indicator.ca.ids.length;++i){idsArray.push({Id:indicator.ca.ids[i]});}
options.selectedAxisDimension={type:indicator.ca.t,order:indicator.ca.o,ids:idsArray};}
return this.statisticExplorer.addIndicator(SAPO.Maps.Statistics.Config.currentProvider.endpoint,indicator.id,options);},unloadStatistics:function(){this.showingStatistic=false;if(!this.statisticExplorer){return;}
this.statisticExplorer.removeAllIndicators();},createStatisticExplorer:function(){this.statisticExplorer=new SAPO.Maps.Statistics(this.map,this.optionsPanel,this.windowManager,{showChangeIndicartorLinkCallback:{scope:this,callback:this.openModalBox},legendDiv:this.legendHolder,showConfigTerritoryDiv:true,showTemporalDimensionOnPieCharts:false});this.statisticExplorer.events.register("selectIndicator",this,this.addNewIndicator);this.statisticExplorer.events.register("changeIndicator",this,this.openModalBox);if(!this.printPage){this.statisticExplorer.events.register("configureTerritory",this,openTerritoryPanel);maptype.getTerritoryPanel().setStatisticsObj(this.statisticExplorer);}
this.statisticExplorer.events.register("panelHidden",this,this.closeStatsPanel);},isStatisticActive:function(){return this.showingStatistic;},search:function(term){var searchValue=term?term:encodeURIComponent(this.searchBox.value);this.searchTerm=searchValue;this.pageNumber=1;this.getResults();},getResults:function(){this.clearSearchResults();if(!this.waitDiv){this.waitDiv=SAPO.Maps.Utils.createLoadingDiv(this.modalWidth,100);}
this.searchResultsWraper.appendChild(this.waitDiv);this.statisticsSearch.getStatisticsBySearch(SAPO.Maps.Statistics.Config.currentProvider.endpoint,this.searchTerm,this.pageNumber,this.recordsPerPage,{onComplete:this.searchResultsAvailable,onTimeout:this.timeout,scope:this});},getThemes:function(){if(this.themes!==null){return;}
this.statisticsSearch.getStatisticsThemes(SAPO.Maps.Statistics.Config.currentProvider.endpoint,{onComplete:this.getThemesResultsAvailable,onTimeout:function(){},scope:this});},getSubThemesFromTheme:function(themeCode){if(this.subThemes[themeCode]){this.displaySubThemes(this.subThemes[themeCode]);this.setSubThemeDropDownStatus(true);return;}
this.statisticsSearch.getSubThemes(SAPO.Maps.Statistics.Config.currentProvider.endpoint,themeCode,{onComplete:this.getSubThemesFromThemeResultsAvailable,onTimeout:function(){},scope:this,optOnComplete:themeCode});},getIndicatorsFromSubTheme:function(themeCode){this.statisticsSearch.getStatisticsByTheme(SAPO.Maps.Statistics.Config.currentProvider.endpoint,themeCode,{onComplete:this.getIndicatorsFromSubThemeResultsAvailable,onTimeout:function(){},scope:this,optOnComplete:themeCode});},statSelected:function(stat){this.showingStatistic=true;this.setModalBoxVisibility(false);if(!this.statisticExplorer){this.createStatisticExplorer();}
var indicator=this.statisticExplorer.getSelectedIndicator();if(this.addIndicatorToCompare||!indicator){this.statisticExplorer.addIndicator(SAPO.Maps.Statistics.Config.currentProvider.endpoint,stat.StatisticId,stat);this.addIndicatorToCompare=false;}else{indicator.changeIndicator(stat.StatisticId);}
selectPanel('statistics');this.resizePanel();document.getElementById('pub').style.display='none';},resizePanel:function(){var div_res=s$('stats_results');div_res.style.height=(s$('left_col').offsetHeight-div_res.offsetTop-33)+"px";},closeStatsPanel:function(){this.unloadStatistics();if(map.baseLayer===map.getBaseLayers().ADMINISTRATIVE_MAP){selectPanel('territory');}else{selectPanel();}},searchResultsAvailable:function(obj){var searchResults=obj;this.displaySearchResults(searchResults);},timeout:function(){this.searchResultsWraper.removeChild(this.waitDiv);var h2=document.createElement('h2');h2.innerHTML="Não foi possivel apresentar os resultados. Tente novamente";this.searchResultsWraper.appendChild(h2);},displaySearchResults:function(results){this.searchResultsWraper.removeChild(this.waitDiv);if(results.TotalResults===0){var h2=document.createElement('h2');var errorMsg="Não foram encontrados resultados na pesquisa por: "+decodeURIComponent(this.searchTerm);h2.appendChild(document.createTextNode(errorMsg));this.searchResultsWraper.appendChild(h2);return;}
var _this=this;var h1_header=document.createElement("h1");var ol_list=document.createElement("ol");var nrResults=results.TotalResults>1?results.TotalResults+" Resultados encontrados":results.TotalResults+" Resultado encontrado";h1_header.appendChild(document.createTextNode(nrResults));var hits=results.Hits;var li_item,a_indicatorName;for(var i=0;i<hits.length;++i){li_item=document.createElement("li");a_indicatorName=document.createElement("a");a_indicatorName.href="#";a_indicatorName.innerHTML=hits[i].StatisticName;a_indicatorName.stat=hits[i];a_indicatorName.onclick=function(){_this.statSelected(this.stat);return false;};li_item.appendChild(a_indicatorName);ol_list.appendChild(li_item);}
this.searchResultsWraper.appendChild(h1_header);this.searchResultsWraper.appendChild(ol_list);this.drawPages(results.TotalResults);},drawPages:function(nrResults){if(nrResults<=this.recordsPerPage){return;}
var div_pagination=document.createElement("div");div_pagination.className="smapi_global_pagination";var numPages=Math.ceil(nrResults/this.recordsPerPage);var startPage=this.pageNumber-Math.floor(this.numberOfPagesShown/2);var endPage=this.pageNumber+Math.floor(this.numberOfPagesShown/2);if(endPage>numPages){endPage=numPages;}
if(startPage<1){startPage=1;}
if((endPage-startPage+1)<this.numberOfPagesShown&&numPages>=this.numberOfPagesShown){if(startPage<=Math.floor(this.numberOfPagesShown/2)){endPage+=this.numberOfPagesShown-endPage;}else if(endPage>=numPages-Math.floor(this.numberOfPagesShown/2)){startPage-=this.numberOfPagesShown-(endPage-startPage+1);}}
var pageNumber=false;if(this.pageNumber!==1){var span_prev=document.createElement("span");span_prev.className="prev";span_prev.onclick=function(){this.goToPage(this.pageNumber-1);}.bindObj(this);div_pagination.appendChild(span_prev);}
var pages=document.createElement('span');var page=false;var _this=this;for(var i=startPage;i<=endPage;++i){page=document.createElement('a');page.innerHTML=i;page.page=i;page.onclick=function(){_this.goToPage(this.page);return false;};if(i===this.pageNumber){page.className='current';}
pages.appendChild(page);}
div_pagination.appendChild(pages);if(this.pageNumber!==numPages){var span_next=document.createElement("span");span_next.className="next";span_next.onclick=function(){this.goToPage(this.pageNumber+1);}.bindObj(this);div_pagination.appendChild(span_next);}
this.searchResultsWraper.appendChild(div_pagination);},goToPage:function(page){this.pageNumber=page;this.getResults();},clearSearchResults:function(){this.searchResultsWraper.innerHTML="";},getThemesResultsAvailable:function(obj){var themes=obj;this.themes=themes;this.displayThemes(themes);},displayThemes:function(themes){var option;for(var i=0;i<themes.length;++i){option=document.createElement("option");option.value=themes[i].Code;option.innerHTML=themes[i].Description;this.themesDropDown.appendChild(option);}},getSubThemesFromThemeResultsAvailable:function(obj,themeCode){var subThemes=obj;this.setSubThemeDropDownStatus(true);this.subThemes[themeCode]=subThemes;this.displaySubThemes(subThemes);},displaySubThemes:function(subThemes){SAPO.Maps.Utils.removeChildNodes(this.subThemesDropDown);var option=document.createElement('option');option.value='select';option.innerHTML='Seleccione o sub-tema dos indicadores a consultar';this.subThemesDropDown.appendChild(option);for(var i=0;i<subThemes.length;++i){option=document.createElement("option");option.subThemeCode=subThemes[i].Code;option.innerHTML=subThemes[i].Description;this.subThemesDropDown.appendChild(option);}},getIndicatorsFromSubThemeResultsAvailable:function(obj){var indicators=obj;this.setIndicatorDropDownStatus(true);this.displayIndicators(indicators);},displayIndicators:function(indicators){SAPO.Maps.Utils.removeChildNodes(this.indicatorsDropDown);var option=document.createElement('option');option.value='select';option.innerHTML='Seleccione o indicador a consultar';this.indicatorsDropDown.appendChild(option);for(var i=0;i<indicators.length;++i){option=document.createElement("option");option.statObj=indicators[i];option.innerHTML=(indicators[i].StatisticName.length>120)?indicators[i].StatisticName.substr(0,120)+"...":indicators[i].StatisticName;option.title=indicators[i].StatisticName;this.indicatorsDropDown.appendChild(option);}},themeSelected:function(evt){var selectedIdx=this.themesDropDown.selectedIndex;this.setIndicatorDropDownStatus(false);if(selectedIdx===0){this.setSubThemeDropDownStatus(false);return;}
var themeCode=this.themesDropDown.options[selectedIdx].value;this.getSubThemesFromTheme(themeCode);},subThemeSelected:function(evt){var selectedIdx=this.subThemesDropDown.selectedIndex;if(selectedIdx===0){this.setIndicatorDropDownStatus(false);return;}
var subThemeCode=this.subThemesDropDown.options[selectedIdx].subThemeCode;this.getIndicatorsFromSubTheme(subThemeCode);},indicatorSelected:function(evt){var selectedIdx=this.indicatorsDropDown.selectedIndex;if(selectedIdx===0){return;}
var statObj=this.indicatorsDropDown.options[selectedIdx].statObj;this.statSelected(statObj);},setSubThemeDropDownStatus:function(enable){if(enable){this.subThemesDropDown.disabled=false;}
else{this.subThemesDropDown.disabled=true;}
this.subThemesDropDown.selectedIndex=0;},setIndicatorDropDownStatus:function(enable){if(enable){this.indicatorsDropDown.disabled=false;}
else{this.indicatorsDropDown.disabled=true;}
this.indicatorsDropDown.selectedIndex=0;},attachEvents:function(){this.modalBackground.onclick=function(){this.closeModalBox();}.bindObj(this);var isEscapeKey=function(evt){if(evt.keyCode==Event.KEY_ESC){this.closeModalBox();}}.bindObj(this);if(OpenLayers.Util.getBrowserName()==='msie'){Event.observe(document.body,"keyup",isEscapeKey);}
else{Event.observe(window,"keyup",isEscapeKey);}
OpenLayers.Event.observe(this.themesDropDown,"change",this.themeSelected.bindObj(this));OpenLayers.Event.observe(this.subThemesDropDown,"change",this.subThemeSelected.bindObj(this));OpenLayers.Event.observe(s$('stats_closebtn'),'click',this.closeStatsPanel.bindObj(this));OpenLayers.Event.observe(s$('select_theme'),'click',this.indicatorSelected.bindObj(this));},addNewIndicator:function(evt){this.addIndicatorToCompare=true;this.openModalBox();},openModalBox:function(){this.positionModalBox();if(!this.showingStatistic){this.setPubVisibility(false);}
this.setModalBoxVisibility(true);OpenLayers.Event.observe(window,"resize",this.resizeCallback);this.getThemes();},closeModalBox:function(){this.setModalBoxVisibility(false);if(!this.showingStatistic){this.setPubVisibility(true);}
OpenLayers.Event.stopObserving(window,"resize",this.resizeCallback);},setModalBoxVisibility:function(show){if(show){this.modal.style.display="block";this.modalBackground.style.display="block";if(this.selectedModalTab==='search'){s$('stats_textBox').focus();}}
else{this.modal.style.display="none";this.modalBackground.style.display="none";}
if(SAPO.Maps.Utils.checkIE6()){var elements=document.getElementsByTagName('select');var elementsToAvoid=s$('themes').getElementsByTagName('select');for(var i=0;i<elements.length;++i){if(!SAPO.Maps.Utils.hasItem(elementsToAvoid,elements[i])){elements[i].style.visibility=show?'hidden':'visible';}}}},positionModalBox:function(){this.modal.style.left=((document.body.clientWidth/2)-(this.modalWidth/2)).toString()+"px";this.modal.style.top=((document.body.clientHeight/2)-(this.modalHeight/2)).toString()+"px";this.setPubVisibility(false);},selectModalTab:function(tabName){if(this.selectedModalTab){document.getElementById(this.modalContentNamePrefix+this.selectedModalTab).style.display="none";document.getElementById(this.modalTabNamePrefix+this.selectedModalTab).className="";}
document.getElementById(this.modalContentNamePrefix+tabName).style.display="block";document.getElementById(this.modalTabNamePrefix+tabName).className="current";if(tabName==='search'){s$('stats_textBox').focus();}
this.selectedModalTab=tabName;},setPubVisibility:function(show){if(show){document.getElementById("pub_mrec").style.display="block";}
else{document.getElementById("pub_mrec").style.display="none";}}};
SapoMapsApp.Suggest={map:null,url:"http://services.sapo.pt/Maps/SuggestJSON?",requester:null,maxResults:10,field:null,callback:null,scope:null,selectedIdx:-1,html:null,valueBeforeDisplay:null,reqId:null,initialize:function(fieldId,options){this.field=document.getElementById(fieldId);this.field.autocomplete="off";if(options&&options.clickSuggestionCallback&&options.scope){this.callback=options.clickSuggestionCallback;this.scope=options.scope;}
if(options&&options.map){this.map=options.map;}
this.requester=SAPO.Maps.Request.prototype.getRequester();this.attachEvents();},getFieldValue:function(){if(this.field){return this.field.value;}
return null;},display:function(suggestions){var obj=this.field;var left=0,top=0;do{left+=obj.offsetLeft;top+=obj.offsetTop;}while((obj=obj.offsetParent));this.html=this.buildHTML(suggestions);this.html.style.position="absolute";this.html.style.left=(left-5)+"px";this.html.style.top=(top+this.field.offsetHeight+2)+"px";this.html.style.zIndex="9999";this.valueBeforeDisplay=this.getFieldValue();this.reqId=null;document.body.appendChild(this.html);},close:function(){if(this.html){document.body.removeChild(this.html);this.html=null;this.selectedIdx=-1;}},moveUp:function(){if(!this.html){return;}
var elementToSelect=null,elementToUnSelect=null;if(this.selectedIdx===-1){this.selectedIdx=this.html.childNodes.length-1;elementToSelect=this.html.childNodes[this.selectedIdx];elementToSelect.className="suggestion_selected";this.selectSuggestion();return;}
if(this.selectedIdx===0){elementToUnSelect=this.html.childNodes[this.selectedIdx];elementToUnSelect.className="suggestion";this.selectedIdx=-1;this.selectSuggestion();return;}
elementToUnSelect=this.html.childNodes[this.selectedIdx];elementToUnSelect.className="suggestion";elementToSelect=this.html.childNodes[--this.selectedIdx];elementToSelect.className="suggestion_selected";this.selectSuggestion();},moveDown:function(){if(!this.html){return;}
var elementToSelect=null,elementToUnSelect=null;if(this.selectedIdx===-1){this.selectedIdx=0;elementToSelect=this.html.childNodes[this.selectedIdx];elementToSelect.className="suggestion_selected";this.selectSuggestion();return;}
if(this.selectedIdx===this.html.childNodes.length-1){elementToUnSelect=this.html.childNodes[this.selectedIdx];elementToUnSelect.className="suggestion";this.selectedIdx=-1;this.selectSuggestion();return;}
elementToUnSelect=this.html.childNodes[this.selectedIdx];elementToUnSelect.className="suggestion";elementToSelect=this.html.childNodes[++this.selectedIdx];elementToSelect.className="suggestion_selected";this.selectSuggestion();},selectSuggestion:function(close){try{this.field.value=this.html.childNodes[this.selectedIdx].childNodes[0].sug;}catch(e){}
if(close){this.close();}},buildHTML:function(suggestions){var mainDiv=document.createElement("div");mainDiv.className="suggestions main";var suggestionDiv=null;var suggestionTerm=null;var suggestionHits=null;for(var i=0;i<suggestions.length;++i){suggestionDiv=document.createElement("div");suggestionTerm=document.createElement("span");suggestionHits=document.createElement("span");suggestionDiv.className="suggestion";suggestionHits.className="hits";suggestionTerm.innerHTML=suggestions[i].value.length>34?suggestions[i].value.substr(0,34)+"...":suggestions[i].value;suggestionHits.innerHTML=suggestions[i].count+" Resultados";suggestionDiv.idx=suggestionTerm.idx=suggestionHits.idx=i;suggestionDiv.sug=suggestionTerm.sug=suggestionHits.sug=suggestions[i].value;suggestionDiv.onmouseover=this.mouseOverSuggestion.bindObj(this);Event.observe(suggestionDiv,"mousedown",this.clickSuggestion.bindObj(this),true);suggestionDiv.appendChild(suggestionTerm);mainDiv.appendChild(suggestionDiv);}
return mainDiv;},processSuggestions:function(obj){this.close();var suggestions=null;try{suggestions=obj.Response.FacetFields.Field.Item;if(!suggestions.length){suggestions=[suggestions];}}
catch(e){return;}
this.display(suggestions);},attachEvents:function(){Event.observe(this.field,"keyup",this.onKeyUp.bindObj(this));Event.observe(this.field,"keydown",this.onKeyDown.bindObj(this),true);Event.observe(this.field,"focus",this.onFocus.bindObj(this));if(OpenLayers.Util.getBrowserName()==='msie'){Event.observe(document.body,"click",this.onWindowClick.bindObj(this));}
else{Event.observe(window,"mousedown",this.onWindowClick.bindObj(this));}
if(this.map){this.map.events.register("click",this,this.onWindowClick);}},mouseOverSuggestion:function(e){if(!e){e=window.event;}
var element=e.target?e.target:e.srcElement;if(this.selectedIdx!==-1){var elementToUnSelect=this.html.childNodes[this.selectedIdx];elementToUnSelect.className="suggestion";}
this.selectedIdx=element.idx;var elementToSelect=this.html.childNodes[this.selectedIdx];elementToSelect.className="suggestion_selected";},clickSuggestion:function(e){if(!e){e=window.event;}
var element=e.target?e.target:e.srcElement;if(this.selectedIdx!==-1){var elementToUnSelect=this.html.childNodes[this.selectedIdx];elementToUnSelect.className="suggestion";}
this.selectedIdx=element.idx;var elementToSelect=this.html.childNodes[this.selectedIdx];elementToSelect.className="suggestion_selected";this.selectSuggestion(true);if(this.callback&&this.scope){this.callback.apply(this,[]);}},onKeyUp:function(e){if(this.reqId!==null&&this.reqId!==undefined){this.requester.cancel(this.reqId);}
var keycode=e.keyCode;if(keycode===Event.KEY_ESC||keycode===Event.KEY_TAB||keycode===Event.KEY_RETURN){this.close();return;}
if(keycode===Event.KEY_DOWN||keycode===Event.KEY_UP||keycode===Event.KEY_LEFT||keycode===Event.KEY_RIGHT){Event.stop(e);return;}
var text=this.getFieldValue();if(text.length===0){this.close();Event.stop(e);return;}
text=this.removeAccents(text).replace(/ /g,"\\ ")+"*";var params=["text="+text,"maxResults="+this.maxResults];var url=this.url+params.join("&");this.reqId=this.requester.request(url,{timeout:4,onComplete:this.processSuggestions.bindObj(this)});Event.stop(e);},onKeyDown:function(e){switch(e.keyCode){case Event.KEY_ESC:this.field.value=this.valueBeforeDisplay;this.close();Event.stop(e);break;case Event.KEY_DOWN:this.moveDown();Event.stop(e);break;case Event.KEY_UP:this.moveUp();Event.stop(e);break;case Event.KEY_RETURN:case Event.KEY_TAB:this.selectSuggestion(true);break;}},onFocus:function(e){},onWindowClick:function(e){this.close();},removeAccents:function(text){text=text.replace(new RegExp("[ÀÁÂÃÄÅàáâãäå]",'g'),"a");text=text.replace(new RegExp("æ",'g'),"ae");text=text.replace(new RegExp("[Çç]",'g'),"c");text=text.replace(new RegExp("[Ð]",'g'),"d");text=text.replace(new RegExp("[ÈÉÊËèéêëð]",'g'),"e");text=text.replace(new RegExp("[ÌÍÎÏìíîï]",'g'),"i");text=text.replace(new RegExp("[Ññ]",'g'),"n");text=text.replace(new RegExp("[ÒÓÔÕÕÖØòóôõöø]",'g'),"o");text=text.replace(new RegExp("œ",'g'),"oe");text=text.replace(new RegExp("[Šš]",'g'),"s");text=text.replace(new RegExp("[ÙÚÛÜùúûü]",'g'),"u");text=text.replace(new RegExp("[ŸÝýÿ]",'g'),"y");text=text.replace(new RegExp("[Žž]",'g'),"z");text=text.replace(new RegExp("[\\s]",'g'),"\\%20");text=text.toLowerCase();return text;}};
SapoMapsApp.Fuel={active:false,map:null,fuelLayerObject:null,selectedFuel:null,popup:null,recoverState:true,stateToRecover:null,filtersChangedListener:null,cql_filter:null,divLike:null,iframeLike:null,brands:['','GALP','REPSOL','BP','CEPSA','JUMBO'],types:['','gasoline_95','gasoline_98','diesel','gpl_auto'],initialize:function(map){this.map=map;},activate:function(){if(this.active){return;}
this.fuelLayerObject=new OpenLayers.Layer.WMS('Fuel',['http://map1.mapas.sapo.pt/server/wms','http://map2.mapas.sapo.pt/server/wms','http://map3.mapas.sapo.pt/server/wms','http://map4.mapas.sapo.pt/server/wms','http://map5.mapas.sapo.pt/server/wms','http://map6.mapas.sapo.pt/server/wms','http://map7.mapas.sapo.pt/server/wms','http://map8.mapas.sapo.pt/server/wms'],{height:'256',width:'256',layers:'gis:fuel',styles:'',srs:'EPSG:90013',format:'image/png',tiled:'true',transparent:true,tilesOrigin:map.maxExtent.left+','+map.maxExtent.bottom},{buffer:0,displayOutsideMaxExtent:true});this.fuelLayerObject.params.cql_filter=this.cql_filter;this.map.addLayer(this.fuelLayerObject);SapoMapsApp.GeoserverLayerManager.addLayer({layer:this.fuelLayerObject,callback:this.mapClicked,context:this});this.registerEvents();this.active=true;if(this.recoverState&&this.stateToRecover){this.setState(this.stateToRecover);this.recoverState=false;}
try{SapoMapsApp.Analytics.track("Layers","Fuel","ActivarLayer");}
catch(e){}},deactivate:function(){if(!this.active){return;}
this.closeOpenedPopup();SapoMapsApp.GeoserverLayerManager.removeLayer(this.fuelLayerObject);this.map.removeLayer(this.fuelLayerObject);this.fuelLayerObject=null;this.unregisterEvents();this.active=false;},isActive:function(){return this.active;},getState:function(){if(!this.isActive()){return"";}
var brandIndex,typeIndex;if(document.getElementById('fuel_filter_brand')){var brandSelect=document.getElementById('fuel_filter_brand');var typeSelect=document.getElementById('fuel_filter_type');brandIndex=brandSelect.selectedIndex;typeIndex=typeSelect.selectedIndex;}
else{var stateParams=this.stateToRecover.split(',');brandIndex=Number(stateParams[1]);typeIndex=Number(stateParams[2]);}
var state='fuel,'+brandIndex+','+typeIndex;if(this.selectedFuel){state+=','+this.selectedFuel.poiid;}
return state;},setStateAfterLoad:function(poi){this.stateToRecover=poi;},setState:function(){var stateParams=this.stateToRecover.split(',');var brandIndex=Number(stateParams[1]);var typeIndex=Number(stateParams[2]);var poiid=null;if(stateParams.length>3){poiid=stateParams[3];}
if(!document.getElementById('fuel_filter_brand')){var cql_filter='';if(brandIndex>0){cql_filter='brand like \''+this.brands[brandIndex]+'\'';if(typeIndex>0){cql_filter+=' AND ';}}
if(typeIndex>0){cql_filter+=this.types[typeIndex]+' <> \'\'';}
this.fuelLayerObject.params.cql_filter=cql_filter===''?null:cql_filter;this.map.removeLayer(this.fuelLayerObject);this.map.addLayer(this.fuelLayerObject);}
else{var brandSelect=document.getElementById('fuel_filter_brand');var typeSelect=document.getElementById('fuel_filter_type');brandSelect.selectedIndex=brandIndex;typeSelect.selectedIndex=typeIndex;this.filtersChanged();}
if(poiid!==null){var params={REQUEST:"GetFeature",OUTPUTFORMAT:'json',TYPENAME:'fuel',LAYERS:'gis:fuel',SRS:'EPSG:900913',CQL_FILTER:'poiid=\''+poiid+'\''};var success=function(data){var parsedData=eval('('+data.responseText+')');var poi=parsedData.features[0].properties;this.displayResult(poi);};OpenLayers.loadURL("/streamers/server/wfs",params,this,success,this.error);}},registerEvents:function(){if(document.getElementById('fuel_filter_brand')){this.filtersChangedListener=this.filtersChanged.bindObj(this);OpenLayers.Event.observe('fuel_filter_brand','change',this.filtersChangedListener);OpenLayers.Event.observe('fuel_filter_type','change',this.filtersChangedListener);}},unregisterEvents:function(){OpenLayers.Event.stopObservingElement('fuel_filter_brand');OpenLayers.Event.stopObservingElement('fuel_filter_type');},mapClicked:function(e){var params={REQUEST:"GetFeatureInfo",EXCEPTIONS:"application/vnd.ogc.se_xml",BBOX:map.getExtent().toBBOX(),X:e.xy.x,Y:e.xy.y,INFO_FORMAT:'text/html',QUERY_LAYERS:'gis:fuel',FEATURE_COUNT:50,Layers:'gis:fuel',Styles:'',Srs:'EPSG:900913',WIDTH:map.size.w,HEIGHT:map.size.h,format:'text/html',cql_filter:this.cql_filter};OpenLayers.loadURL("/streamers/server/wms",params,this,this.success,this.error);OpenLayers.Event.stop(e);},success:function(response){if(response.responseText!==""){var poi=eval('('+response.responseText.replace(/\n/g,'').replace(/\r/g,'')+')');poi=poi[0];this.displayResult(poi);try{SapoMapsApp.Analytics.track("Layers","Fuel","AbrirPin");}
catch(e){}}
else{SapoMapsApp.GeoserverLayerManager.nextLayer();}},error:function(response){},displayResult:function(poi){var popupId=poi.poiid;var popupLonLat=new OpenLayers.LonLat(Number(poi.longitude),Number(poi.latitude));var popupAnchor=popupLonLat.transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));var popupContent=this.getHtmlForFuelPopup(poi);this.popup=new SAPO.Maps.Popup.SapoPopup(popupId,popupAnchor,null,popupContent,true,this.closeOpenedPopup.bindObj(this),null,{top:138,left:57+308,right:10,bottom:60},true);this.getHtmlForPopupExtraOptions(poi,popupContent,this.popup);this.selectedFuel=poi;this.map.addPopup(this.popup,false);this.buildSocialHtml(poi,popupContent);this.popup.contentUpdated();this.divLike.appendChild(this.iframeLike);},closeOpenedPopup:function(){if(this.popup){this.map.removePopup(this.popup);this.popup=null;this.selectedFuel=null;if(this.divLike){this.divLike.innerHTML='';}
this.iframeLike=null;this.divLike=null;}},filtersChanged:function(){var brandSelect=document.getElementById('fuel_filter_brand');var typeSelect=document.getElementById('fuel_filter_type');var brandValue=brandSelect.options[brandSelect.selectedIndex].value;var typeValue=typeSelect.options[typeSelect.selectedIndex].value;var cql_filter='';if(brandValue!==''){cql_filter='brand LIKE \''+brandValue+'\'';}
if(typeValue!==''){if(cql_filter!==''){cql_filter+=' AND ';}
cql_filter+=typeValue+'<> \'\'';}
if(cql_filter===''){cql_filter=null;}
this.fuelLayerObject.params.cql_filter=cql_filter;this.cql_filter=cql_filter;this.map.removeLayer(this.fuelLayerObject);this.map.addLayer(this.fuelLayerObject);},getHtmlForFuelPopup:function(myFuel){var name=myFuel.poi;var brand=myFuel.brand;var type="&Aacute;reas de Servico";var street=myFuel.address;var parish=myFuel.parish;var zipcode=myFuel.zipcode.toString();zipcode=zipcode.substr(0,4)+'-'+zipcode.substr(4,3);var phone=myFuel.phone;var fax=myFuel.fax;var mail=myFuel.email;var poiid=myFuel.poiid;var fonte_url='http://www.precoscombustiveis.dgge.pt/';var fonte_title=myFuel.source;var lastmodified=myFuel.lastmodified.substr(0,10);var price_schumbo95=myFuel.gasoline_95;var price_schumbo98=myFuel.gasoline_98;var price_gasoleo=myFuel.diesel;var price_gasoleoplus="";var price_gplauto=myFuel.gpl_auto;var html="<div class=\"content_smapi\"><div class=\"search_pop_header_smapi\">";html+="<h1>"+name+"</h1>";html+="<h2>"+brand+"</h2>";html+="</div>";html+="<div class=\"search_pop_content_smapi\">";html+="<div class=\"fuel_text\">";if(street){html+="<span class=\"address_pop_content_smapi\">"+street+"</span>";}
if(parish){html+="<span class=\"address_pop_content_smapi\">"+parish+"</span>";}
if(zipcode){html+="<span class=\"address_pop_content_smapi zipcode_address_pop_content_smapi\">"+zipcode+"</span>";}
if(phone){html+="<span class=\"phone_pop_content_smapi\">"+phone+"</span>";}
if(fax){html+="<span class=\"fax_pop_content_smapi\">"+fax+"</span>";}
if(mail){html+="<span class=\"mail_pop_content_smapi\"><a href=\"mailto:"+mail+"\">"+mail+"</a></span>";}
html+="</div>";html+="<div class=\"fuel_info\"><span class=\"address_pop_content_smapi\"><b>Preço de combustíveis</b></span>";html+="<span class=\"address_pop_content_smapi\">";html+="<div id=\"fuel\"><ul>";if(price_schumbo95){html+="<li class=\"fuel_sprite-schumbo95_16x16\">Gasolina 95 - &euro; "+price_schumbo95+"</li>";}
if(price_schumbo98){html+="<li class=\"fuel_sprite-schumbo98_16x16\">Gasolina 98 - &euro; "+price_schumbo98+"</li>";}
if(price_gasoleo){html+="<li class=\"fuel_sprite-gasoleo_16x16\">Gasóleo - &euro; "+price_gasoleo+"</li>";}
if(price_gasoleoplus){html+="<li class=\"fuel_sprite-gasoleoplus_16x16\">Gasóleo+ - &euro; "+price_gasoleoplus+"</li>";}
if(price_gplauto){html+="<li class=\"fuel_sprite-gplauto_16x16\">GPL Auto - &euro; "+price_gplauto+"</li>";}
html+="</ul>";html+="<p>Actualizado em: "+lastmodified+"</p>";html+="</div>";html+="</div>";html+="<p class=\"smapi_popup_content_datasource\"><a target=\"_blank\" href=\"http://mapas.sapo.pt/POIDetails.aspx?poiid="+poiid+"\" class=\"more_info_btn\">Mais informações</a>Fonte: <a href=\""+fonte_url+"\" target=\"_blank\">DGEG</a></p>";html+="</div>";var div_holder=document.createElement('div');div_holder.className='smapi_popup_content';div_holder.innerHTML=html;return div_holder;},buildSocialHtml:function(poi,content){var header=content.childNodes[0].childNodes[0];content=content.childNodes[0].childNodes[1];var divShare=SAPO.Maps.Utils.createNewElement('div',{className:'share'});for(var i=0;i<content.childNodes.length;++i){if(content.childNodes[i].className==='smapi_popup_content_datasource'){var divClear=SAPO.Maps.Utils.createNewElement('div',{className:'clear'});content.childNodes[i].parentNode.insertBefore(divClear,content.childNodes[i]);content.childNodes[i+1].parentNode.insertBefore(divShare,content.childNodes[i+1]);break;}}
poi.Name=poi.poi;var url=SapoMapsApp.Social.POIDetailsLink+poi.poiid;getPunyUrl(url,function(obj){SapoMapsApp.Social.appendShareIcons(obj.punyURL.ascii,url,poi,null,divShare);},function(obj){SapoMapsApp.Social.appendShareIcons(url,url,poi,null,divShare);});var divLike=SAPO.Maps.Utils.createNewElement('div',{className:'like'});header.appendChild(divLike);this.divLike=divLike;this.iframeLike=SapoMapsApp.Social.getFacebookLikeButton(url);},getHtmlForPopupExtraOptions:function(poi,content,popup){poi.Latitude=poi.latitude;poi.Longitude=poi.longitude;SAPO.Maps.PoiInfoRenderer.getExtraOptionsHTML(poi,content,{popup:popup},SapoMapsApp.Search.search,[{name:'Itinerário',func:function(){SapoMapsApp.POIS.itineraryOptionClicked.apply(SapoMapsApp.Itineraries,[poi]);},context:this}]);}};
var isChristmasLayerActive=false;var christmasLayerMarkers=null;var openedChristmasLayerPOI=null;var toOpenChristmasPOI=null;var chirstmasBannerURL="images/destaques/natal_btn_off.png";function toggleChristmasLayer(){if(isChristmasLayerActive){disableChristmasLayer();chirstmasBannerURL="images/destaques/natal_btn_off.png";document.getElementById("pub_editorial_img").src=chirstmasBannerURL;isChristmasLayerActive=false;}
else{christmasLayerMarkers=new SAPO.Maps.Markers();map.addMarkers(christmasLayerMarkers);enableChristmasLayer();chirstmasBannerURL="images/destaques/natal_btn_on.png";document.getElementById("pub_editorial_img").src=chirstmasBannerURL;isChristmasLayerActive=true;}
return false;}
function disableChristmasLayer(){map.removeMarkers(christmasLayerMarkers);christmasLayerMarkers=null;}
function enableChristmasLayer(){var requester=SAPO.Maps.Request.prototype.getRequester();requester.request("http://services.sapo.pt/GIS/GetPOIByCategoryIdAndTextJSON?categoryId=259&recordsPerPage=100",{timeout:4,onComplete:processChristmas});}
function processChristmas(obj){var pois;try{pois=obj.GetPOIByCategoryIdAndTextResponse.GetPOIByCategoryIdAndTextResult.POI;if(!pois.length){pois=[pois];}}
catch(e){pois=[];}
var marker,poi;for(var i=0;i<pois.length;++i){poi=pois[i];marker=new SAPO.Maps.Marker(new OpenLayers.LonLat(poi.Longitude,poi.Latitude),{popupAnchor:new OpenLayers.Pixel(0,-8)},{markerImage:"images/destaques/natal_icon.png",markerAnchor:new OpenLayers.Pixel(-8,-8),size:new OpenLayers.Size(16,16)});marker.poi=poi;marker.html=getHTMLForChristmasPOI(poi);marker.registerEvent("click",this,function(m){SapoMapsApp.closeInfoWindows();m.openPopup(m.html,{borders:SapoMapsApp.borders});openedChristmasLayerPOI=m;});marker.registerEvent("mouseover",this,function(){map.div.style.cursor="pointer";});marker.registerEvent("mouseout",this,function(){map.div.style.cursor="";});christmasLayerMarkers.addMarker(marker);}
if(toOpenChristmasPOI){openChristmasPOI(toOpenChristmasPOI);toOpenChristmasPOI=null;}}
function getHTMLForChristmasPOI(poi){var div_wrapper=document.createElement("div");var h1_title=document.createElement("h1");var p_description=document.createElement("p");var img_image=document.createElement("img");div_wrapper.style.width="450px";img_image.style.cssFloat="left";img_image.style.styleFloat="left";h1_title.style.paddingBottom="10px";h1_title.style.fontSize="16px";img_image.style.paddingRight="10px";img_image.style.paddingBottom="10px";h1_title.innerHTML=poi.Name;p_description.innerHTML=poi.Description;img_image.width=150;img_image.height=100;try{img_image.src=poi.DetailXml.Details.Pictures.Picture.value;}
catch(e){}
div_wrapper.appendChild(h1_title);if(img_image.src!==''){div_wrapper.appendChild(img_image);}
div_wrapper.appendChild(p_description);return div_wrapper;}
function closeOpenedChristmasLayerPopup(){if(openedChristmasLayerPOI){openedChristmasLayerPOI.closePopup();openedChristmasLayerPOI=null;}}
function christmasSetStateAfterLoad(poiID){toOpenChristmasPOI=poiID.split(",")[1];}
function openChristmasPOI(poiID){var markers=christmasLayerMarkers.getMarkers();var marker=null;for(var i=0;i<markers.length;++i){if(markers[i].poi.POIId===poiID){marker=markers[i];break;}}
if(marker){SapoMapsApp.closeInfoWindows();marker.openPopup(marker.html,{borders:SapoMapsApp.borders});openedChristmasLayerPOI=marker;}}
SapoMapsApp.TransportDirections=OpenLayers.Class({panel:null,map:null,reverseGeocoder:null,language:null,route:null,events:null,syndicationObj:null,status:SAPO.Maps.Request.Status.STOP,request:null,currentStepIdx:0,popup:null,stepMarkers:null,imagesURL:{start:"http://js.sapo.pt/Assets/Maps/Images/bandeira_verde.gif",end:"http://js.sapo.pt/Assets/Maps/Images/bandeira_vermelha.gif",left:"http://js.sapo.pt/Assets/Maps/Images/esquerda.gif",right:"http://js.sapo.pt/Assets/Maps/Images/direita.gif",front:"http://js.sapo.pt/Assets/Maps/Images/frente.gif"},initialize:function(map,panel,options){this.events={};this.syndicationObj=new SAPO.Communication.Syndication();this.reverseGeocoder=new SAPO.Maps.ReverseGeocoder();this.map=map;if(panel){this.panel=typeof(panel)=='string'?document.getElementById(panel):panel;}
options=OpenLayers.Util.extend({language:'pt'},options);this.language=options.language?options.language:"pt";},getDirections:function(start,end,options){if(this.status==SAPO.Maps.Request.Status.REQUESTING){throw'SapoMapsApp.TransportDirections: cannot query the server while the last request is waiting';}
if(!options){options={};}
options=OpenLayers.Util.extend({routeMode:'Shortest',isDepartureTime:true},options);if(!options.dateAndTime){var date=new Date();var year=date.getFullYear().toString();var month=(date.getMonth()+1)<10?("0"+(date.getMonth()+1).toString()):(date.getMonth()+1).toString();var day=date.getDate()<10?("0"+date.getDate().toString()):date.getDate().toString();var hours=date.getHours()<10?("0"+date.getHours().toString()):date.getHours().toString();var minutes=date.getMinutes()<10?("0"+date.getMinutes().toString()):date.getMinutes().toString();var seconds=date.getSeconds()<10?("0"+date.getSeconds().toString()):date.getSeconds().toString();options.dateAndTime=year+"-"+month+"-"+day+"T"+hours+":"+minutes+":"+seconds;}
var requestURL="http://services.sapo.pt/Transport/GetRouteJSON?begin.long="+start.lon
+"&begin.lat="+start.lat
+"&end.long="+end.lon
+"&end.lat="+end.lat
+"&dateAndTime="+options.dateAndTime
+"&isDepartureTime="+options.isDepartureTime.toString()
+"&routeMode="+options.routeMode
+"&language=Portuguese";if(options.travelModes){requestURL+="&travelModes="+options.travelModes.toString();}
this.route=null;this.request={cancel:false};var reqID=this.syndicationObj.push(requestURL,{onComplete:this.onComplete.bindObj(this),onTimeout:this.onError.bindObj(this),optOnComplete:{status:this.request,description:options.description}});this.status=SAPO.Maps.Request.Status.REQUESTING;this.syndicationObj.run(reqID);try{this.notifyListeners('loading',[]);}catch(e){}
if(this.panel){SAPO.Maps.Utils.displayWaitIcon(this.panel);}
return true;},onComplete:function(obj,args){if(this.status!=SAPO.Maps.Request.Status.REQUESTING||args.status.cancel){return;}
try{if(this.panel){SAPO.Maps.Utils.removeWaitIcon(this.panel);}
var route=obj.GetRouteResponse.GetRouteResult;var routeSections;try{routeSections=route.RouteSections.RouteSection;}
catch(e6){if(!routeSections&&this.panel){var elem=document.createElement('div');elem.className='search_results_smapi';SAPO.Maps.Utils.displayMessageHTML(elem,"Não temos informação disponível para o itinerário entre os pontos indicados","","",SAPO.Maps.Utils.MessageType.WARNING);this.panel.appendChild(elem);}
this.notifyListeners('noroute',[this]);}
var steps=[];var coordinatesList,points,lonlat;for(var i=0;i<routeSections.length;++i){points=[];coordinatesList=routeSections[i].CoordinatesList.Coordinates.length?routeSections[i].CoordinatesList.Coordinates:[{Coordinate:routeSections[i].CoordinatesList.Coordinates.Coordinate}];for(var j=0;j<coordinatesList.length;++j){var coordinates=[];if(!coordinatesList[j].Coordinate.length){coordinatesList[j].Coordinate=[coordinatesList[j].Coordinate];}
for(var k=0;k<coordinatesList[j].Coordinate.length;++k){lonlat=new OpenLayers.LonLat(Number(coordinatesList[j].Coordinate[k].Longitude),Number(coordinatesList[j].Coordinate[k].Latitude));coordinates.push(lonlat);}
points.push(coordinates);}
steps.push(new SapoMapsApp.TransportDirections.Step({points:points,description:routeSections[i].Description,distance:Number(routeSections[i].Distance),duration:(Number(routeSections[i].TravelTime.split(":")[0])*3600)+(Number(routeSections[i].TravelTime.split(":")[1])*60)+Number(routeSections[i].TravelTime.split(":")[2]),price:Number(routeSections[i].Price),co2:Number(routeSections[i].CO2),waitingTime:routeSections[i].WaitingTime!==null?(Number(routeSections[i].WaitingTime.split(":")[0])*3600)+(Number(routeSections[i].WaitingTime.split(":")[1])*60)+Number(routeSections[i].WaitingTime.split(":")[2]):0,operator:SapoMapsApp.TransportDirections.Operator.getOperatorById(Number(routeSections[i].Operator.Id)),travelMode:SapoMapsApp.TransportDirections.TravelMode.getTravelModeByName(routeSections[i].TravelMode),beginDateTime:routeSections[i].BeginDateTime,endDateTime:routeSections[i].EndDateTime}));}
this.route=new SapoMapsApp.TransportDirections.Route(steps);this.status=SAPO.Maps.Request.Status.OK;if(this.panel){this.buildHTML(this.panel);for(var a=0;a<this.route.getSteps().length;++a){this.showText(a);}}
if(this.map){var bounds=this.getBounds();var polylines=this.getPolylines();for(var l=0;l<polylines.length;++l){this.map.addOverlay(polylines[l]);}
this.addStepMarkers();var adjustedBounds=new OpenLayers.Bounds(bounds.left-0.02199,bounds.bottom-0.02199,bounds.right+0.02199,bounds.top+0.02199);this.map.setBounds(this.getBoundsConsideringBorders(adjustedBounds));}
try{this.notifyListeners('completed',[this]);}catch(e2){try{this.notifyListeners('error',[this]);}catch(e3){}}}
catch(e1){this.route=null;this.status=SAPO.Maps.Request.Status.ERROR;try{this.notifyListeners('error',[this]);}catch(e5){}}},onError:function(obj){if(this.status!=SAPO.Maps.Request.Status.REQUESTING){return;}
this.status=SAPO.Maps.Request.Status.ERROR;try{this.notifyListeners('timeout',[this]);if(this.panel){SAPO.Maps.Utils.removeWaitIcon(this.panel);var elem=document.createElement('div');elem.className='search_results_smapi';SAPO.Maps.Utils.displayMessageHTML(elem,"Não temos informação disponível para o itinerário entre os pontos indicados","","",SAPO.Maps.Utils.MessageType.WARNING);this.panel.appendChild(elem);}}
catch(e){}},getStatus:function(){return this.status;},getBounds:function(){if(this.status!=SAPO.Maps.Request.Status.OK){return null;}
return this.route.getBounds();},getBoundsConsideringBorders:function(bounds){if(!this.borders){return bounds;}
this.map.setBounds(bounds,false);var mapSize=this.map.getSize();var bottom_left=new OpenLayers.Pixel(this.borders.left,mapSize.h-this.borders.bottom);var top_right=new OpenLayers.Pixel(mapSize.w-this.borders.right,this.borders.top);var bounds_sw=this.map.getContainerPixelFromLonLat(new OpenLayers.LonLat(bounds.left,bounds.bottom));var bounds_ne=this.map.getContainerPixelFromLonLat(new OpenLayers.LonLat(bounds.right,bounds.top));var delta_x=0,delta_y=0;if(bounds_sw.x<bottom_left.x){bounds_sw.x-=bottom_left.x;}
if(bounds_ne.y<top_right.y){bounds_ne.y-=top_right.y;}
if(bounds_sw.y>bottom_left.y){bounds_sw.y+=bottom_left.y;}
if(bounds_ne.x>top_right.x){bounds_ne.x+=top_right.x;}
var bounds_sw_lonlat=this.map.getLonLatFromContainerPixel(bounds_sw);var bounds_ne_lonlat=this.map.getLonLatFromContainerPixel(bounds_ne);return new OpenLayers.Bounds(bounds_sw_lonlat.lon,bounds_sw_lonlat.lat,bounds_ne_lonlat.lon,bounds_ne_lonlat.lat);},getPolylines:function(){if(this.status!=SAPO.Maps.Request.Status.OK){return null;}
return this.route.getPolylines();},getDuration:function(){if(this.status!=SAPO.Maps.Request.Status.OK){return null;}
return this.route.getDuration();},getDistance:function(){if(this.status!=SAPO.Maps.Request.Status.OK){return null;}
return this.route.getDistance();},getRoute:function(){if(this.status!=SAPO.Maps.Request.Status.OK){return null;}
return this.route;},getStartLonLat:function(){if(this.status!=SAPO.Maps.Request.Status.OK){return null;}
return this.route.getSteps()[0].getStart();},getEndLonLat:function(){if(this.status!=SAPO.Maps.Request.Status.OK){return null;}
var steps=this.route.getSteps();return steps[steps.length-1].getEnd();},getDescription:function(){if(this.status!=SAPO.Maps.Request.Status.OK){return null;}
return this.route.getDescription(this.language);},getSummaryHTML:function(){if(this.status!=SAPO.Maps.Request.Status.OK){return null;}
var divNode=document.createElement("div");this.buildHTML(divNode);return divNode;},addStepMarkers:function(){if(!this.stepMarkers){this.stepMarkers=new SAPO.Maps.Markers("TransportDirectionsStepMarkers");this.map.addMarkers(this.stepMarkers);}
var steps=this.route.getSteps();var marker=null;marker=new SAPO.Maps.Marker(steps[0].getStart().clone(),{},{markerImage:"http://imgs.sapo.pt/fotos_gis/site/iti2_markerA.png"});marker.idxStep=0;marker.registerEvent("click",this,function(marker){this.openPopup(marker.idxStep);});this.stepMarkers.addMarker(marker);for(var i=1;i<steps.length;++i){marker=new SAPO.Maps.Marker(steps[i].getStart().clone(),{popupAnchor:new OpenLayers.Pixel(-(steps[i].getOperator().images.icon.width),-(steps[i].getOperator().images.icon.height+50))},{markerImage:steps[i].getOperator().images.icon.url,size:new OpenLayers.Size(steps[i].getOperator().images.icon.width,steps[i].getOperator().images.icon.height),markerAnchor:new OpenLayers.Pixel(-(steps[i].getOperator().images.icon.width),-(steps[i].getOperator().images.icon.height))});marker.idxStep=i;marker.registerEvent("click",this,function(marker){this.openPopup(marker.idxStep);});marker.registerEvent("mouseover",this,function(){this.map.div.style.cursor="pointer";});marker.registerEvent("mouseout",this,function(){this.map.div.style.cursor="";});this.stepMarkers.addMarker(marker);}
marker=new SAPO.Maps.Marker(steps[steps.length-1].getEnd().clone(),{},{markerImage:"http://imgs.sapo.pt/fotos_gis/site/iti2_markerB.png"});this.stepMarkers.addMarker(marker);},navigateTo:function(idxStep,justSelect){try{var li=this.panel.childNodes[1].childNodes[this.currentStepIdx+1];if(li.hasMap&&li.hasText){li.className="iti_step_smapi_site iti_imageandtext_list_smapi_site";}
else{if(li.hasMap){li.className="iti_step_smapi_site iti_image_list_smapi_site";}
else{li.className="iti_step_smapi_site";}}
li=this.panel.childNodes[1].childNodes[idxStep+1];if(li.hasMap&&li.hasText){li.className="iti_step_smapi_site iti_imageandtext_list_smapi_site iti_selected_smapi_site";if(OpenLayers.Util.getBrowserName()==='msie'){li.className+=" iti_selected_smapi_site_ie";}}
else{if(li.hasMap){li.className="iti_step_smapi_site iti_image_list_smapi_site iti_selected_smapi_site";if(OpenLayers.Util.getBrowserName()==='msie'){li.className+=" iti_selected_smapi_site_ie";}}
else{li.className="iti_step_smapi_site iti_selected_smapi_site";if(OpenLayers.Util.getBrowserName()==='msie'){li.className+=" iti_selected_smapi_site_ie";}}}}
catch(e1){}
this.currentStepIdx=idxStep;if(justSelect){try{this.notifyListeners('stepSelected',[this,this.currentStepIdx]);}
catch(e2){}
return;}
if(!this.map){return;}
var step=this.route.steps[idxStep];var stepBounds=new OpenLayers.Bounds(step.points[0].lon,step.points[0].lat,step.points[0].lon,step.points[0].lat);for(var i=1;i<step.points.length;++i){stepBounds.extend(step.points[i]);}
stepBounds.transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));var stepZoom=this.map.getZoomForExtent(stepBounds);this.map.zoomTo(stepZoom);this.map.panTo(this.route.getSteps()[idxStep].getStart().clone().transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913")));try{this.notifyListeners('stepSelected',[this,this.currentStepIdx]);}
catch(e3){}},unselectStep:function(){try{var li=this.panel.childNodes[1].childNodes[this.currentStepIdx+1];if(li.hasMap&&li.hasText){li.className="iti_step_smapi_site iti_imageandtext_list_smapi_site";}
else{if(li.hasMap){li.className="iti_step_smapi_site iti_image_list_smapi_site";}
else{li.className="iti_step_smapi_site";}}}
catch(e1){return;}
try{this.notifyListeners('stepUnselected',[this,this.currentStepIdx]);}
catch(e2){}},openPopup:function(idxStep){if(!this.map){return;}
var _this=this;var step;try{step=this.route.getSteps()[idxStep];}
catch(e1){return;}
var first=idxStep===0?true:false;var last=idxStep==this.route.getSteps().length-1?true:false;if(this.popup){this.closePopup();}
var content=this.getHTMLForStepPopup(step);var popupAnchor=step.getStart().clone();var popupPixel=this.map.getContainerPixelFromLonLat(popupAnchor);popupPixel.y-=this.route.getSteps()[idxStep].getOperator().images.icon.height;if(idxStep!==0){popupPixel.x-=(this.route.getSteps()[idxStep].getOperator().images.icon.width)/2;}
popupAnchor=this.map.getLonLatFromContainerPixel(popupPixel);popupAnchor.transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));this.popup=new SAPO.Maps.Popup.SapoPopup(popupAnchor.toShortString(),popupAnchor,null,content,true,function(popup){SAPO.Maps.Directions.prototype.closePopup.apply(_this,[]);},null,SapoMapsApp.borders);this.map.addPopup(this.popup);this.navigateTo(idxStep,true);try{this.notifyListeners('popupOpened',[this,this.currentStepIdx]);}
catch(e2){}},closePopup:function(){if(!this.map){return;}
if(this.popup){this.map.removePopup(this.popup);this.popup=null;}
this.unselectStep();try{this.notifyListeners('popupClosed',[this,this.currentStepIdx]);}
catch(e){}},showMap:function(idxStep){var li_step=this.panel.childNodes[1].childNodes[idxStep+1];var divMapStep=li_step.childNodes[0];if(!divMapStep){return;}
divMapStep.id=Math.random().toString();divMapStep.style.display="block";divMapStep.style.width="150px";divMapStep.style.height="150px";if(!divMapStep.mapObject){divMapStep.mapObject=new SAPO.Maps.Map(divMapStep.id);for(var i=0;i<divMapStep.mapObject.controls.length;++i){if(divMapStep.mapObject.controls[i].CLASS_NAME==="SAPO.Maps.Control.Scale"){divMapStep.mapObject.removeControl(divMapStep.mapObject.controls[i]);break;}}
var polyline=this.getPolyline().clone();divMapStep.mapObject.addOverlay(polyline);divMapStep.mapObject.setMapCenter(this.route.getSteps()[idxStep].getStart(),17);}
li_step.hasMap=true;if(li_step.hasText){li_step.className="iti_step_smapi_site iti_imageandtext_list_smapi_site";li_step.childNodes[1].style.width=(li_step.clientWidth-160)+"px";}
else{li_step.className="iti_step_smapi_site iti_image_list_smapi_site";}},hideMap:function(idxStep){var li_step=this.panel.childNodes[1].childNodes[idxStep+1];var divMapStep=li_step.childNodes[0];if(!divMapStep){return;}
divMapStep.style.display="none";li_step.hasMap=false;if(li_step.hasText){li_step.className="iti_step_smapi_site";}},showText:function(idxStep){var li_step=this.panel.childNodes[1].childNodes[idxStep+1];if(!li_step){return;}
li_step.childNodes[1].style.display="block";li_step.childNodes[2].style.display="block";li_step.childNodes[3].style.display="block";li_step.hasText=true;if(li_step.hasMap){li_step.className="iti_step_smapi_site iti_imageandtext_list_smapi_site";}
else{li_step.className="iti_step_smapi_site";}},hideText:function(idxStep){var li_step=this.panel.childNodes[1].childNodes[idxStep+1];if(!li_step){return;}
li_step.childNodes[1].style.display="none";li_step.childNodes[2].style.display="none";li_step.childNodes[3].style.display="none";li_step.hasText=false;if(li_step.hasMap){li_step.className="iti_step_smapi_site iti_image_list_smapi_site";}
else{li_step.className="iti_step_smapi_site";}},getHTMLForStepPopup:function(step){var div_wraper=document.createElement("div");var div_image=document.createElement("div");var div_description=document.createElement("div");var img_operatorLogo=document.createElement("img");var p_hour=document.createElement("p");var p_waitingTime=document.createElement("p");var p_description=document.createElement("p");var p_price=document.createElement("p");var p_co2=document.createElement("p");div_wraper.className="iti_transports_popup";div_image.className="iti_transports_image";div_description.className="iti_transports_description";p_hour.className="iti_transports_description_hour";p_waitingTime.className="iti_transports_description_waitingTime";p_description.className="iti_transports_description_description";p_price.className="iti_transports_description_price";p_co2.className="iti_transports_description_co2";img_operatorLogo.src=step.getOperator().images.image_normal.url;var date=step.getBeginDateTime().split("T")[0];date=date.split("-");var hour=step.getBeginDateTime().split("T")[1];hour=hour.split(":");p_hour.innerHTML="<span>Data:</span> "+date[2]+"-"+date[1]+"-"+date[0]+"&nbsp;&nbsp;"+hour[0]+":"+hour[1];p_waitingTime.innerHTML="<span>Tempo de espera:</span> "+(step.getWaitingTime()>60?(Math.round(step.getWaitingTime()/60)).toString()+"min":step.getWaitingTime().toString()+"seg");p_description.innerHTML="<span>Descri&ccedil;&atilde;o:</span> "+step.getDescription();p_price.innerHTML="<span>Pre&ccedil;o:</span> "+step.getPrice().toFixed(2).replace(/\./,",")+" &euro;";p_co2.innerHTML="<span>CO2:</span> "+((Math.round(step.getCO2()*1000)<1000)?(Math.round(step.getCO2()*1000)+"gramas"):(Math.round(step.getCO2().toFixed(1))+"kg"));div_image.appendChild(img_operatorLogo);div_description.appendChild(p_hour);if(step.getWaitingTime()>0){div_description.appendChild(p_waitingTime);}
div_description.appendChild(p_description);if(step.getPrice()>0){div_description.appendChild(p_price);}
if(step.getCO2()>0){div_description.appendChild(p_co2);}
div_wraper.appendChild(div_image);div_wraper.appendChild(div_description);return div_wraper;},buildHTML:function(node){if(this.status!=SAPO.Maps.Request.Status.OK){return null;}
var _this=this;while(node.hasChildNodes()){node.removeChild(node.childNodes[0]);}
node.className="iti_results_smapi_site";node.style.position="relative";if(OpenLayers.Util.getBrowserName()==='msie'){node.className+=" iti_results_smapi_site_ie";}
var steps=this.route.getSteps();var div_header=document.createElement("div");div_header.className="iti_results_header_smapi_site";var div_estimated_time=document.createElement("div");div_estimated_time.className="iti_estimated_smapi_site";var p_distance=document.createElement("p");var p_estimated_time=document.createElement("p");var p_price=document.createElement("p");var p_co2=document.createElement("p");if(this.language==="pt"){p_distance.innerHTML="Dist&acirc;ncia: ";p_estimated_time.innerHTML="Tempo Estimado: ";p_price.innerHTML="Pre&ccedil;o: ";p_co2.innerHTML="CO2: ";}
if(this.language==="en"){p_distance.innerHTML="Distance: ";p_estimated_time.innerHTML="Estimated Time: ";p_price.innerHTML="Price: ";p_co2.innerHTML="CO2: ";}
var route_distance=this.route.getDistance();p_distance.innerHTML+="<span>"+(route_distance>1000?(route_distance/1000).toFixed(1).toString()+"km":route_distance.toString()+"m")+"</span";var route_duration=this.route.getDuration();if(route_duration<60){p_estimated_time.innerHTML+="<span>"+route_duration.toString()+"seg</span>";}
else{if(route_duration<3600){p_estimated_time.innerHTML+="<span>"+(route_duration/60).toFixed(0).toString()+"min</span>";}
else{var hours=Math.floor(route_duration/3600);var minutes=((route_duration%3600)/60).toFixed(0);p_estimated_time.innerHTML+="<span>"+hours+"h "+minutes+"min</span>";}}
p_price.innerHTML+="<span>"+this.route.getPrice().toFixed(2)+"&euro;</span>";p_co2.innerHTML+="<span>"+((this.route.getCO2()<0)?(Math.round(this.route.getCO2()*1000)+"gramas</span>"):(this.route.getCO2().toFixed(1)+"kg</span>"));div_estimated_time.appendChild(p_distance);div_estimated_time.appendChild(p_estimated_time);div_estimated_time.appendChild(p_price);div_estimated_time.appendChild(p_co2);div_header.appendChild(div_estimated_time);node.appendChild(div_header);var ul_list=document.createElement("ul");ul_list.className="iti_result_list_smapi_site";var li_start=document.createElement("li");li_start.className="iti_Points_smapi_site";var div_img_start=document.createElement("div");div_img_start.className="iti_start_image_smapi_site";var span_start=document.createElement("span");this.reverseGeocoder.reverseGeocode(steps[0].getStart(),function(streetName){span_start.innerHTML=streetName;});li_start.appendChild(div_img_start);li_start.appendChild(span_start);ul_list.appendChild(li_start);var li_step,div_step_map,div_step_text_img,div_step_text_description,div_step_text_length,a_step,span_step1,span_step2;for(var i=0;i<steps.length;++i){li_step=document.createElement("li");li_step.className="iti_step_smapi_site";div_step_map=document.createElement("div");div_step_map.className="iti_direction_preview_smapi_site";div_step_text_img=document.createElement("div");div_step_text_img.className="iti_direction_img_smapi_site";div_step_text_description=document.createElement("div");div_step_text_description.className="iti_direction_text_smapi_site";div_step_text_length=document.createElement("div");div_step_text_length.className="iti_meters_smapi_site";img_step=document.createElement("img");a_step=document.createElement("a");a_step.href="#";span_step=document.createElement("span");if(OpenLayers.Util.getBrowserName()==='msie'){div_step_text_description.className+=" iti_direction_text_smapi_site_ie";div_step_text_img.className+=" iti_direction_img_smapi_site_ie";div_step_text_length.className+=" iti_meters_smapi_site_ie";}
img_step.src=steps[i].getOperator().images.image_small.url;span_step.innerHTML=steps[i].getDescription();a_step.appendChild(span_step);div_step_text_length.innerHTML=steps[i].getDuration()>60?(Math.round(steps[i].getDuration()/60)).toString()+"min":steps[i].getDuration().toString()+"seg";div_step_text_description.appendChild(a_step);div_step_text_img.appendChild(img_step);li_step.appendChild(div_step_map);li_step.appendChild(div_step_text_img);li_step.appendChild(div_step_text_description);li_step.appendChild(div_step_text_length);ul_list.appendChild(li_step);li_step.idxStep=i;li_step.onclick=function(){_this.navigateTo(this.idxStep);_this.openPopup(this.idxStep);};}
var li_end=document.createElement("li");li_end.className="iti_Points_smapi_site";var div_img_end=document.createElement("div");div_img_end.className="iti_end_image_smapi_site";var span_end=document.createElement("span");this.reverseGeocoder.reverseGeocode(steps[steps.length-1].getEnd(),function(streetName){span_end.innerHTML=streetName;});li_end.appendChild(div_img_end);li_end.appendChild(span_end);ul_list.appendChild(li_end);node.appendChild(ul_list);return node;},buildErrorHTML:function(node){if(this.status!=SAPO.Maps.Request.Status.ERROR){return null;}
var _this=this;while(node.hasChildNodes()){node.removeChild(node.childNodes[0]);}
var div=document.createElement("div");var img=document.createElement("img");img.src="http://js.sapo.pt/Assets/Maps/Images/warning.gif";var span=document.createElement("span");span.innerHTML="N&atilde;o foi poss&iacute;vel encontrar um caminho entre os pontos indicados";div.appendChild(img);div.appendChild(span);node.appendChild(div);},clear:function(){if(this.status==SAPO.Maps.Request.Status.REQUESTING){throw'Directions: cannot clear the info until the request is pending';}
this.clearLine();this.clearStepMarkers();this.clearPanel();try{this.notifyListeners('clear',[this]);}catch(e){}},clearLine:function(){var polylines=this.getPolylines();if(polylines&&this.map){for(var i=0;i<polylines.length;++i){this.map.removeOverlay(polylines[i]);}
this.closePopup();}},clearStepMarkers:function(){if(this.stepMarkers&&this.map){this.map.removeMarkers(this.stepMarkers);this.stepMarkers=null;}},clearPanel:function(){if(this.panel){while(this.panel.hasChildNodes()){this.panel.removeChild(this.panel.childNodes[0]);}
var classes=this.panel.className.split(' ');this.panel.className="";if(classes.length===0){return;}
for(var i=0;i<classes.length;++i){if(classes[i]==="iti_results_smapi_site"||classes[i]==="iti_results_smapi_site_ie"){continue;}
this.panel.className+=classes[i];}}},cancel:function(){if(this.status!=SAPO.Maps.Request.Status.REQUESTING){return;}
this.status=SAPO.Maps.Request.Status.CANCELED;this.request.cancel=true;try{this.notifyListeners('canceled',[this]);}catch(e){}},registerEvent:function(eventType,context,func){if(!this.events[eventType]){this.events[eventType]=[];}
var obj={func:func,context:context};this.events[eventType].push(obj);},unRegisterEvent:function(eventType,context,func){var evts=this.events[eventType]?this.events[eventType]:[];for(var i=0;i<evts.length;++i){if(context==evts[i].context&&func==evts[i].func){evts.splice(i,1);return true;}}
return false;},notifyListeners:function(eventType,args){var evts=this.events[eventType]?this.events[eventType]:[];args=args?args:[];var func,context;for(var i=0;i<evts.length;++i){func=evts[i].func;context=evts[i].context;func.apply(context,args);}},EVENT_TYPES:['completed','error','clear','canceled',"noroute","loading","timeout","stepSelected","stepUnselected","popupOpened","popupClosed"],CLASS_NAME:"SapoMapsApp.TransportDirections"});
SapoMapsApp.TransportDirections.Operator={OPERATORS:{PEDESTRIAN:{id:0,name:"Pedestrian",shortName:"Pedestrian",images:{image_normal:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/normal/walk.gif"},image_small:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/small/walk.gif",width:14,height:20},icon:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/icon/walk.png",width:28,height:41}}},CARRIS:{id:1,name:"Carris",shortName:"Carris",images:{image_normal:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/normal/Carris.png"},image_small:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/small/Carris.png",width:25,height:17},icon:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/icon/Carris.png",width:38,height:36}}},METRO:{id:2,name:"Metro",shortName:"Metro",images:{image_normal:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/normal/Metro.png"},image_small:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/small/Metro.png",width:20,height:25},icon:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/icon/Metro.png",width:31,height:43}}},CP:{id:3,name:"CP",shortName:"CP",images:{image_normal:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/normal/CP.png"},image_small:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/small/CP.png",width:25,height:14},icon:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/icon/CP.png",width:39,height:34}}},TT:{id:4,name:"TransTejo",shortName:"TT",images:{image_normal:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/normal/TT.png"},image_small:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/small/TT.png",width:25,height:14},icon:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/icon/TT.png",width:36,height:43}}},TST:{id:11,name:"TST",shortName:"TST",images:{image_normal:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/normal/TST.png"},image_small:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/small/TST.png",width:30,height:16},icon:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/icon/TST.png",width:43,height:36}}},FERTAGUS:{id:13,name:"Fertagus",shortName:"Fertagus",images:{image_normal:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/normal/Fertagus.png"},image_small:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/small/Fertagus.png",width:25,height:25},icon:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/icon/Fertagus.png",width:35,height:41}}},SOFLUSA:{id:14,name:"Soflusa",shortName:"Soflusa",images:{image_normal:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/normal/soflusa.png"},image_small:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/small/soflusa.png",width:25,height:25},icon:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/icon/soflusa.png",width:33,height:43}}},SULFERTAGUS:{id:21,name:"SulFertagus",shortName:"SFertagus",images:{image_normal:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/normal/Fertagus.png"},image_small:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/small/Fertagus.png",width:25,height:25},icon:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/icon/Fertagus.png",width:35,height:41}}},VIMECA:{id:31,name:"Vimeca",shortName:"Vimeca",images:{image_normal:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/normal/vimeca.png"},image_small:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/small/vimeca.png",width:16,height:25},icon:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/icon/vimeca.png",width:32,height:50}}},TCBARREIRO:{id:41,name:"Transportes Colectivos do Barreiro",shortName:"TCBarreiro",images:{image_normal:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/normal/TCB.png"},image_small:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/small/TCB.png",width:16,height:25},icon:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/icon/TCB.png",width:41,height:40}}},SCOTTURB:{id:51,name:"Scotturb",shortName:"Scotturb",images:{image_normal:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/normal/scotturb.png"},image_small:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/small/scotturb.png",width:50,height:22},icon:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/icon/scotturb.png",width:48,height:36}}},RL:{id:61,name:"Rodoviária de Lisboa",shortName:"RL",images:{image_normal:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/normal/RL.png"},image_small:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/small/RL.png",width:25,height:25},icon:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/icon/RL.png",width:35,height:41}}},CARRISTUR:{id:71,name:"CarrisTur",shortName:"CarrisTur",images:{image_normal:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/normal/Carris.png"},image_small:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/small/Carris.png",width:25,height:17},icon:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/icon/Carris.png",width:38,height:36}}},RODINHAS:{id:81,name:"Rodinhas",shortName:"Rodinhas",images:{image_normal:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/normal/RL.png"},image_small:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/small/RL.png",width:25,height:25},icon:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/icon/RL.png",width:35,height:41}}},MTS:{id:12,name:"Metro Sul",shortName:"Metro Sul",images:{image_normal:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/normal/MTS.png"},image_small:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/small/MTS.png",width:38,height:25},icon:{url:"http://imgs.sapo.pt/fotos_gis/Transports/Logos/icon/MTS.png",width:35,height:41}}}},getOperatorById:function(id){for(var m in this.OPERATORS){var mode=this.OPERATORS[m];if(mode.id==id){return mode;}}
return SapoMapsApp.TransportDirections.Operator.OPERATORS.PEDESTRIAN;}};
SapoMapsApp.TransportDirections.TravelMode={MODES:{Car:{id:0,color:"#000000"},Pedestrian:{id:1,color:"#A400A4"},Bus:{id:2,color:"#006194"},Train:{id:3,color:"#78D000"},Metro:{id:4,color:"#f80000"},Tram:{id:5,color:"#78D000"},Boat:{id:6,color:"#f89830"},Plane:{id:7,color:"#CA3D5E"}},getTravelModeByName:function(name){return this.MODES[name];}};
SapoMapsApp.TransportDirections.Step=OpenLayers.Class({points:null,distance:0,duration:0,description:null,startLonLat:null,endLonLat:null,beginDateTime:null,endDateTime:null,price:null,co2:null,waitingTime:null,operator:null,travelMode:null,initialize:function(opts){this.description=opts.description;this.distance=opts.distance;this.duration=opts.duration;this.points=opts.points;this.price=opts.price;this.co2=opts.co2;this.waitingTime=opts.waitingTime;this.operator=opts.operator;this.travelMode=opts.travelMode;this.beginDateTime=opts.beginDateTime;this.endDateTime=opts.endDateTime;this.startLonLat=this.points[0][0];this.endLonLat=this.points[this.points.length-1][this.points[this.points.length-1].length-1];},getPoints:function(){return this.points;},getDescription:function(){return this.description;},getDistance:function(){return this.distance;},getDuration:function(){return this.duration;},getLocation:function(){return this.location;},getBeginDateTime:function(){return this.beginDateTime;},getEndDateTime:function(){return this.beginDateTime;},getPrice:function(){return this.price;},getCO2:function(){return this.co2;},getWaitingTime:function(){return this.waitingTime;},getOperator:function(){return this.operator;},getTravelMode:function(){return this.travelMode;},getDirection:function(){return this.direction;},getStart:function(){return this.startLonLat;},getEnd:function(){return this.endLonLat;},CLASS_NAME:"SapoMapsApp.TransportDirections.Step"});
SapoMapsApp.TransportDirections.Route=OpenLayers.Class({steps:null,distance:0,duration:0,beginDateTime:null,endDateTime:null,price:null,co2:null,stopovers:null,polylines:null,initialize:function(steps){this.steps=steps;},getSteps:function(){return this.steps;},getDistance:function(){if(this.distance!==0){return this.distance;}
for(var i=0;i<this.steps.length;++i){this.distance+=this.steps[i].getDistance();}
return this.distance;},getDuration:function(){if(this.duration!==0){return this.duration;}
for(var i=0;i<this.steps.length;++i){this.duration+=this.steps[i].getDuration();}
return this.duration;},getDescription:function(language){var description=[];if(!language){language="pt";}
for(var i=0;i<this.steps.length;++i){description.push(this.steps[i].getDescription(language));}
return description;},getBeginDateTime:function(){return this.beginDateTime;},getEndDateTime:function(){return this.endDateTime;},getPrice:function(){if(this.price){return this.price;}
for(var i=0;i<this.steps.length;++i){this.price+=this.steps[i].getPrice();}
return this.price;},getCO2:function(){if(this.co2){return this.co2;}
for(var i=0;i<this.steps.length;++i){this.co2+=this.steps[i].getCO2();}
return this.co2;},getStopovers:function(){return this.stopovers;},getBounds:function(){if(!this.polylines){this.getPolylines();}
var bounds=this.polylines[0].getBounds();for(var i=1;i<this.polylines.length;++i){bounds.extend(this.polylines[i].getBounds());}
return bounds;},getPolylines:function(){if(this.polylines){return this.polylines;}
this.polylines=[];var points=[];for(var i=0;i<this.steps.length;++i){for(var j=0;j<this.steps[i].points.length;++j){this.polylines.push(new SAPO.Maps.Polyline(this.steps[i].points[j],{strokeColor:this.steps[i].getTravelMode().color,strokeOpacity:0.8,strokeWidth:5}));}}
return this.polylines;},CLASS_NAME:"SapoMapsApp.TransportDirections.Route"});
SapoMapsApp.TransportItineraries=OpenLayers.Class({status:null,map:null,panel:null,directions:null,search:null,listeners:null,request:null,from:null,to:null,startSelected:false,endSelected:false,language:null,mode:null,borders:null,numberOfPagesShown:5,allowPaging:true,indexToSelect:null,indexToShowDetails:null,div:null,initialize:function(map,panel,options){this.language='pt';this.mode='fastest';this.options=options;OpenLayers.Util.extend(this,options);this.status=SAPO.Maps.Request.Status.STOP;this.map=map;if(panel){this.panel=typeof(panel)=='string'?document.getElementById(panel):panel;}
this.search=new SAPO.Maps.Search(this.map,this.panel,{borders:this.borders,openDetailsWhenClick:false,numberOfPagesShown:this.numberOfPagesShown});this.directions=new SapoMapsApp.TransportDirections(map,panel,options);this.listeners={};this.directions.registerEvent('completed',this,this.completedDirections);this.directions.registerEvent('timeout',this,this.timeout);this.directions.registerEvent('noroute',this,this.itineraryNotFound);this.directions.registerEvent('popupOpened',this,this.directionsStepSelected);this.directions.registerEvent('popupClosed',this,this.directionsStepUnselected);this.search.registerEvent('completed',this,this.completedSearch);this.search.registerEvent('selectedOnMap',this,this.resultSelectedOnMap);this.search.registerEvent('selectedOnPanel',this,this.resultSelectedOnPanel);this.search.registerEvent('unselected',this,this.unselectSearchResult);this.search.registerEvent('timeout',this,this.timeout);this.search.registerEvent('pageChanged',this,this.pageChanged);},getItinerary:function(from,to,options){if(!from||!to){throw'Itineraries: Invalid arguments';}
if(this.status==SAPO.Maps.Request.Status.REQUESTING){throw'Itineraries: Cannot query the server while the last request is waiting';}
this.options=options;this.prepareRequest();OpenLayers.Util.extend(this,options);this.status=SAPO.Maps.Request.Status.REQUESTING;this.from=from;this.to=to;this.requestPOIS(true);},getStatus:function(){return this.status;},getStartingPOIS:function(){if(!this.startSelected&&this.status===SAPO.Maps.Request.Status.REQUESTING){return this.search.getPOIS();}
return this.startSelected;},getEndingPOIS:function(){if(!this.endSelected&&this.status===SAPO.Maps.Request.Status.REQUESTING){return this.search.getPOIS();}
return this.endSelected;},goToPage:function(page){if(this.search.getStatus()===SAPO.Maps.Request.Status.REQUESTING||this.search.getStatus()===SAPO.Maps.Request.Status.OK){return;}
this.search.goToPage(page);},selectStartPOI:function(idx,page){if(this.startSelected){return;}
if(page&&page!==this.search.getCurrentPage()){this.indexToSelect=idx;this.goToPage(page);}else{var pois=this.search.getPOIS();if(idx>=pois.length){return;}
this.startSelected=pois[idx];try{this.notifyListeners('startSelected',[pois[idx],idx,page]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}
this.requestPOIS(false);}},selectEndPOI:function(idx,page){if(this.endSelected){return;}
if(page&&page!==this.search.getCurrentPage()){this.indexToSelect=idx;this.goToPage(page);}else{var pois=this.search.getPOIS();if(idx>=pois.length){return;}
this.endSelected=pois[idx];try{this.notifyListeners('endSelected',[pois[idx],idx,page]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}
this.requestDirections();}},clear:function(silent){if(this.panel&&this.div){this.panel.removeChild(this.div);this.div=null;}
this.search.clear();this.directions.clear();if(!silent){try{this.notifyListeners('clean',[this]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}}},cancel:function(){this.search.cancel();this.directions.cancel();this.status=SAPO.Maps.Request.Status.CANCELED;try{this.notifyListeners('canceled',[this]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}},getDirections:function(){if(this.status==SAPO.Maps.Request.Status.OK){return this.directions;}
return null;},getSearch:function(){return this.search;},selectResult:function(idx,page){if(this.status!==SAPO.Maps.Request.Status.OK&&this.status!==SAPO.Maps.Request.Status.REQUESTING){return;}
if(!this.startSelected||!this.endSelected){if(page&&page!==this.search.getCurrentPage()){this.indexToShowDetails=idx;this.goToPage(page);}else{this.search.openDetails(idx);}
try{this.notifyListeners('resultSelect',[idx,this.search.getCurrentPage()]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}}else{if(this.status===SAPO.Maps.Request.Status.OK){this.directions.openPopup(idx);}}},unselectResult:function(idx){if(this.status!==SAPO.Maps.Request.Status.OK&&this.status!==SAPO.Maps.Request.Status.REQUESTING){return;}
if(this.status===SAPO.Maps.Request.Status.OK){this.directions.closePopup(idx);}else{this.search.unselectResult(idx);try{this.notifyListeners('resultUnselect',[idx]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}}},getResultSelected:function(){if(this.status===SAPO.Maps.Request.Status.OK){return this.directions.currentStepIdx;}
return this.search.getSelectedIndex();},requestPOIS:function(isStart){this.clear(isStart);var query=isStart?this.from:this.to;var isCoords=SAPO.Maps.Utils.checkQuery(query);if(isCoords){var pois=[isCoords];this.completedSearch(this.search,pois);}else{this.search.search(query,{allowPaging:this.allowPaging,displaySingleResult:false});}},requestDirections:function(){this.clear(false);var start=new OpenLayers.LonLat(this.startSelected.Longitude,this.startSelected.Latitude);var end=new OpenLayers.LonLat(this.endSelected.Longitude,this.endSelected.Latitude);if(!this.options){try{this.options=this.getOptions();}
catch(e){}}
this.directions.getDirections(start,end,this.options);},prepareRequest:function(){this.clear(true);this.from=null;this.to=null;this.startSelected=false;this.endSelected=false;},getOptions:function(){var options={};var tm_all=document.getElementById("transportes_todos");var tm_train=document.getElementById("transportes_comboios");var tm_boat=document.getElementById("transportes_barco");var tm_metro=document.getElementById("transportes_metro");var tm_bus=document.getElementById("transportes_autocarro");if(!tm_all.checked){options.travelModes=[];if(tm_train.checked){options.travelModes.push("Train");}
if(tm_boat.checked){options.travelModes.push("Boat");}
if(tm_metro.checked){options.travelModes.push("Metro");}
if(tm_bus.checked){options.travelModes.push("Bus");}}
var rm_stopOvers=document.getElementById("transportes_transbordo");var rm_fastest=document.getElementById("transportes_rapido");var rm_walk=document.getElementById("transportes_pedonal");if(rm_stopOvers.checked){options.routeMode="LessStopOvers";}
if(rm_fastest.checked){options.routeMode="Fastest";}
if(rm_walk.checked){options.routeMode="LessPedestrian";}
var dateTime="";var date=document.getElementById("transporlis_data").value.split("/");dateTime+=date[2]+"-"+date[1]+"-"+date[0]+"T";var hour=document.getElementById("transporlis_horas").selectedIndex;dateTime+=hour<10?("0"+hour.toString()):hour.toString();dateTime+=":";var minutes=document.getElementById("transporlis_minutos").selectedIndex;dateTime+=minutes<10?("0"+minutes.toString()):minutes.toString();dateTime+=":00";options.dateAndTime=dateTime;return options;},completedSearch:function(s,pois){var isStart=!this.startSelected;if(pois.length===0){this.status=SAPO.Maps.Request.ERROR;try{this.notifyListeners('noresults',isStart);}
catch(e){try{this.notifyListeners('error',[this,e]);}catch(e1){}}
return;}
if(pois.length>1&&this.panel){var msg=isStart?'Seleccione o ponto de partida':'Seleccione o ponto de chegada';var elem=document.createElement('h1');elem.className='itineraries_results_smapi_h1';elem.innerHTML=msg;this.panel.insertBefore(elem,this.panel.firstChild);this.div=elem;}
var eventType=isStart?'startingPOIS':'endingPOIS';try{this.notifyListeners(eventType,[this,pois]);}
catch(e2){try{this.notifyListeners('error',[this,e2]);}catch(e3){}}
if(pois.length==1){this.resultSelectedOnPanel(this.search,pois[0],0,this.search.getCurrentPage());}},resultSelectedOnMap:function(s,poi,idx,page){s.openDetails(idx);try{this.notifyListeners('resultSelect',[idx,page]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}},resultSelectedOnPanel:function(s,poi,idx,page){var isStart=!this.startSelected;var eventType='';if(isStart){eventType='startSelected';this.startSelected=poi;this.requestPOIS(false);}else{eventType='endSelected';this.endSelected=poi;this.requestDirections();}
try{this.notifyListeners(eventType,[poi,idx,page]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}},unselectSearchResult:function(s,poi,idx,page){try{this.notifyListeners('resultUnselect',[idx,page]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}},pageChanged:function(s,page){if(this.indexToSelect!==null){if(!this.startSelected){this.selectStartPOI(this.indexToSelect);}
else{this.selectEndPOI(this.indexToSelect);}
this.indexToSelect=null;}
if(this.indexToShowDetails!==null){this.selectResult(this.indexToShowDetails);this.indexToShowDetails=null;}
try{this.notifyListeners('pageChanged',[page]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}},completedDirections:function(){this.status=SAPO.Maps.Request.Status.OK;try{this.notifyListeners('complete',[this.directions]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}},timeout:function(){this.status=SAPO.Maps.Request.Status.ERROR;try{this.notifyListeners('timeout',[this]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}},itineraryNotFound:function(){this.status=SAPO.Maps.Request.Status.ERROR;try{this.notifyListeners('itinerarynotfound',[this]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}},directionsStepSelected:function(directions,StepIdx){this.selectedResult=StepIdx;try{this.notifyListeners('resultSelect',[StepIdx]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}},directionsStepUnselected:function(directions,StepIdx){this.selectedResult=null;try{this.notifyListeners('resultUnselect',[StepIdx]);}
catch(e5){try{this.notifyListeners('error',[this,e5]);}catch(e6){}}},registerEvent:function(eventType,context,func){if(!this.listeners[eventType]){this.listeners[eventType]=[];}
var obj={func:func,context:context};this.listeners[eventType].push(obj);},unRegisterEvent:function(eventType,context,func){var evts=this.listeners[eventType]?this.listeners[eventType]:[];for(var i=0;i<evts.length;++i){if(context==evts[i].context&&func==evts[i].func){evts.splice(i,1);return true;}}
return false;},notifyListeners:function(eventType,args){var evts=this.listeners[eventType]?this.listeners[eventType]:[];args=args?args:[];var func,context;for(var i=0;i<evts.length;++i){func=evts[i].func;context=evts[i].context;func.apply(context,args);}},EVENT_TYPES:['startingPOIS','endingPOIS','complete','error','timeout','startSelected','endSelected','clean','canceled','noresults','itinerarynotfound','resultSelect','resultUnselect','pageChanged'],CLASS_NAME:'SapoMapsApp.TransportItineraries'});
