
function Geometry(srs){this.srs=srs||"EPSG:4326";this.getSrs=getSrs;this.setSrs=setSrs;function getSrs(){return this.srs;}function setSrs(newSrs){this.srs=newSrs;}}Geometry.POINT=0;Geometry.LINE_STRING=1;Geometry.LINEAR_RING=2;function Point2D_Double(x,y){this.x=x||0;this.y=y||0;this.getX=getX;this.setX=setX;this.getY=getY;this.setY=setY;this.setLocation=setLocation;function getX(){return this.x;}function setX(newX){this.x=newX;}function getY(){return this.y;}function setY(newY){this.y=newY;}function setLocation(newX,newY){this.setX(newX);this.setY(newY);}}Point2D_Double.prototype=new Geometry;function Rectangle2D_Double(x,y,width,height){this.x=x||0;this.y=y||0;this.width=width||0;this.height=height||0;this.getX=getX;this.setX=setX;this.getY=getY;this.setY=setY;this.getWidth=getWidth;this.setWidth=setWidth;this.getHeight=getHeight;this.setHeight=setHeight;this.setRect=setRect;this.isEmpty=isEmpty;this.contains=contains;function getX(){return this.x;}function setX(newX){this.x=newX;}function getY(){return this.y;}function setY(newY){this.y=newY;}function getWidth(){return this.width;}function setWidth(newWidth){this.width=newWidth;}function getHeight(){return this.height;}function setHeight(newHeight){this.height=newHeight;}function setRect(newX,newY,newWidth,newHeight){this.setX(newX);this.setY(newY);this.setWidth(newWidth);this.setHeight(newHeight);}function isEmpty(){return(this.width<=0.0)||(this.height<=0.0);}function contains(x,y){x0=this.getX();y0=this.getY();return(x>=x0&&y>=y0&&x<x0+this.getWidth()&&y<y0+this.getHeight());}}Rectangle2D_Double.prototype=new Geometry;function Point(x,y){this.icsl17=Point2D_Double;this.icsl17(x,y);this._bounds=null;this.getBounds=getBounds;this.getClass=getClass;function getBounds(){if((this._bounds==null)||(this._bounds.x!=this.x)||(this._bounds.y!=this.y)){this._bounds=new Rectangle2D_Double(x,y,0,0);}return this._bounds;}function getClass(){return Geometry.POINT;}}Point.prototype=new Point2D_Double;function Curve(){}Curve.prototype=new Geometry;function Surface(){}Surface.prototype=new Geometry;function LineString(xpoints,ypoints,npoints){this.npoints=npoints||0;this.xpoints=xpoints||new Array(0);this.ypoints=ypoints||new Array(0);this._bounds=null;this.getLength=getLength;this.getStartPoint=getStartPoint;this.getEndPoint=getEndPoint;this.addPoint=addPoint;this.getBounds=getBounds;this.setBounds=setBounds;this.move=move;this._calculateBounds=_calculateBounds;this.getClass=getClass;function getLength(tramo){if(tramo){if((tramo>=0)&&(tramo<=this.npoints-2)){return Math.sqrt((this.xpoints[tramo+1]-this.xpoints[tramo])*(this.xpoints[tramo+1]-this.xpoints[tramo])+(this.ypoints[tramo+1]-this.ypoints[tramo])*(this.ypoints[tramo+1]-this.ypoints[tramo]));}else{return 0.0;}}else{length=0.0;for(i=0;i<=this.npoints-2;i++){length+=this.getLength(i);}return length;}}function getStartPoint(){return new Point(this.xpoints[0],this.ypoints[0]);}function getEndPoint(){return new Point(this.xpoints[this.npoints-1],this.ypoints[this.npoints-1]);}function addPoint(x,y){this.xpoints[this.npoints]=x;this.ypoints[this.npoints]=y;this.npoints++;if(this._bounds!=null){if(x<this._bounds.x){this._bounds.width=this._bounds.width+(this._bounds.x-x);this._bounds.x=x;}else{this._bounds.width=Math.max(this._bounds.width,x-this._bounds.x);}if(y<this._bounds.y){this._bounds.height=this._bounds.height+(this._bounds.y-y);this._bounds.y=y;}else{this._bounds.height=Math.max(this._bounds.height,y-this._bounds.y);}}}function getBounds(){if(this._bounds==null){this._bounds=_calculateBounds(this.xpoints,this.ypoints,this.npoints);}return this._bounds;}function setBounds(x,y,w,h){this._bounds=new Rectangle2D_Double(x,y,w,h);}function move(incx,incy){for(i=0;i<this.npoints;i++){this.xpoints[i]+=incx;this.ypoints[i]+=incy;}this._bounds=_calculateBounds(this.xpoints,this.ypoints,this.npoints);}function _calculateBounds(xpoints,ypoints,npoints){boundsMinX=Number.MAX_VALUE;boundsMinY=Number.MAX_VALUE;boundsMaxX=-Number.MAX_VALUE;boundsMaxY=-Number.MAX_VALUE;if(npoints>0){boundsMinX=xpoints[0];boundsMinY=ypoints[0];boundsMaxX=xpoints[0];boundsMaxY=ypoints[0];}for(i=1;i<npoints;i++){x=xpoints[i];boundsMinX=Math.min(boundsMinX,x);boundsMaxX=Math.max(boundsMaxX,x);y=ypoints[i];boundsMinY=Math.min(boundsMinY,y);boundsMaxY=Math.max(boundsMaxY,y);}this._bounds=new Rectangle2D_Double(boundsMinX,boundsMinY,boundsMaxX-boundsMinX,boundsMaxY-boundsMinY);return this._bounds;}function getClass(){return Geometry.LINE_STRING;}}LineString.prototype=new Curve;function Line(x1,y1,x2,y2){this.npoints=2;this.xpoints=new Array(2);this.xpoints[0]=x1;this.xpoints[1]=x2;this.ypoints=new Array(2);this.ypoints[0]=y1;this.ypoints[1]=y2;this.addPoint=addPoint;function addPoint(){}}Line.prototype=new LineString;function LinearRing(xpoints,ypoints,npoints){this.icsl17=LineString;this.icsl17(xpoints,ypoints,npoints);this.contains=contains;this.isClockWise=isClockWise;this.getClass=getClass;function contains(x,y){if(this.getBounds().contains(x,y)){hits=0;ySave=0;var i=0;while((i<this.npoints)&&(this.ypoints[i]==y)){i++;}for(var n=0;n<this.npoints;n++){j=(i+1)%this.npoints;dx=this.xpoints[j]-this.xpoints[i];dy=this.ypoints[j]-this.ypoints[i];if(dy!=0){rx=x-this.xpoints[i];ry=y-this.ypoints[i];if((this.ypoints[j]==y)&&(this.xpoints[j]>=x)){ySave=this.ypoints[i];}if((this.ypoints[i]==y)&&(this.xpoints[i]>=x)){if((ySave>y)!=(ypoints[j]>y)){hits--;}}s=ry/dy;if((s>=0.0)&&(s<=1.0)&&((s*dx)>=rx)){hits++;}}i=j;}return(hits%2)!=0;}return false;}function isClockWise(){N=this.npoints;i=0;j=0;area=0;for(i=0;i<N;i++){j=(i+1)%N;area+=this.xpoints[i]*this.ypoints[j];area-=this.ypoints[i]*this.xpoints[j];}return(area<0);}function getClass(){return Geometry.LINEAR_RING;}}LinearRing.prototype=new LineString;function Polygon(exteriorRing,interiorRings){this.exteriorRing=exteriorRing;this.interiorRings=interiorRings||new Array(0);this.numInteriorRings=this.interiorRings.length||0;this.contains=contains;this.getExteriorRing=getExteriorRing;this.getInteriorRings=getInteriorRings;this.getNumInteriorRings=getNumInteriorRings;this.getArea=getArea;this._getRingArea=_getRingArea;this.getPerimeter=getPerimeter;this.getBounds=getBounds;function getExteriorRing(){return this.exteriorRing;}function getNumInteriorRings(){return this.numInteriorRings;}function getInteriorRings(){return this.interiorRings;}function getArea(){extArea=_getRingArea(this.exteriorRing);for(var i=0;i<this.interiorRings.length;i++){extArea-=_getRingArea(this.interiorRings[i]);}return extArea;}function _getRingArea(ring){N=ring.npoints;i=0;j=0;area=0;for(i=0;i<N;i++){j=(i+1)%N;area+=ring.xpoints[i]*ring.ypoints[j];area-=ring.ypoints[i]*ring.xpoints[j];}area/=2;return(area<0?-1*area:area);}function getBounds(){return this.exteriorRing.getBounds();}function getPerimeter(){return this.exteriorRing.getLength();}}Polygon.prototype=new Surface;var jg_ihtm,jg_ie,jg_fast,jg_dom,jg_moz,jg_n4=(document.layers&&typeof document.classes!="undefined");function chkDHTM(x,i){x=document.body||null;jg_ie=x&&typeof x.insertAdjacentHTML!="undefined";jg_dom=(x&&!jg_ie&&typeof x.appendChild!="undefined"&&typeof document.createRange!="undefined"&&typeof(i=document.createRange()).setStartBefore!="undefined"&&typeof i.createContextualFragment!="undefined");jg_ihtm=!jg_ie&&!jg_dom&&x&&typeof x.innerHTML!="undefined";jg_fast=jg_ie&&document.all&&!window.opera;jg_moz=jg_dom&&typeof x.style.MozOpacity!="undefined";}function pntDoc(){this.wnd.document.write(jg_fast?this.htmRpc():this.htm);this.htm='';}function pntCnvDom(){var x=document.createRange();x.setStartBefore(this.cnv);x=x.createContextualFragment(jg_fast?this.htmRpc():this.htm);this.cnv.appendChild(x);this.htm='';}function pntCnvIe(){this.cnv.insertAdjacentHTML("BeforeEnd",jg_fast?this.htmRpc():this.htm);this.htm='';}function pntCnvIhtm(){this.cnv.innerHTML+=this.htm;this.htm='';}function pntCnv(){this.htm='';}function mkDiv(x,y,w,h){this.htm+='<div style="position:absolute;'+'left:'+x+'px;'+'top:'+y+'px;'+'width:'+w+'px;'+'height:'+h+'px;'+'clip:rect(0,'+w+'px,'+h+'px,0);'+'background-color:'+this.color+
(!jg_moz?';overflow:hidden':'')+';"><\/div>';}function mkDivIe(x,y,w,h){this.htm+='%%'+this.color+';'+x+';'+y+';'+w+';'+h+';';}function mkDivPrt(x,y,w,h){this.htm+='<div style="position:absolute;'+'border-left:'+w+'px solid '+this.color+';'+'left:'+x+'px;'+'top:'+y+'px;'+'width:0px;'+'height:'+h+'px;'+'clip:rect(0,'+w+'px,'+h+'px,0);'+'background-color:'+this.color+
(!jg_moz?';overflow:hidden':'')+';"><\/div>';}function mkLyr(x,y,w,h){this.htm+='<layer '+'left="'+x+'" '+'top="'+y+'" '+'width="'+w+'" '+'height="'+h+'" '+'bgcolor="'+this.color+'"><\/layer>\n';}var regex=/%%([^;]+);([^;]+);([^;]+);([^;]+);([^;]+);/g;function htmRpc(){return this.htm.replace(regex,'<div style="overflow:hidden;position:absolute;background-color:'+'$1;left:$2;top:$3;width:$4;height:$5"></div>\n');}function htmPrtRpc(){return this.htm.replace(regex,'<div style="overflow:hidden;position:absolute;background-color:'+'$1;left:$2;top:$3;width:$4;height:$5;border-left:$4px solid $1"></div>\n');}function mkLin(x1,y1,x2,y2){if(x1>x2){var _x2=x2;var _y2=y2;x2=x1;y2=y1;x1=_x2;y1=_y2;}var dx=x2-x1,dy=Math.abs(y2-y1),x=x1,y=y1,yIncr=(y1>y2)?-1:1;if(dx>=dy){var pr=dy<<1,pru=pr-(dx<<1),p=pr-dx,ox=x;while((dx--)>0){++x;if(p>0){this.mkDiv(ox,y,x-ox,1);y+=yIncr;p+=pru;ox=x;}else p+=pr;}this.mkDiv(ox,y,x2-ox+1,1);}else{var pr=dx<<1,pru=pr-(dy<<1),p=pr-dy,oy=y;if(y2<=y1){while((dy--)>0){if(p>0){this.mkDiv(x++,y,1,oy-y+1);y+=yIncr;p+=pru;oy=y;}else{y+=yIncr;p+=pr;}}this.mkDiv(x2,y2,1,oy-y2+1);}else{while((dy--)>0){y+=yIncr;if(p>0){this.mkDiv(x++,oy,1,y-oy);p+=pru;oy=y;}else p+=pr;}this.mkDiv(x2,oy,1,y2-oy+1);}}}function mkLin2D(x1,y1,x2,y2){if(x1>x2){var _x2=x2;var _y2=y2;x2=x1;y2=y1;x1=_x2;y1=_y2;}var dx=x2-x1,dy=Math.abs(y2-y1),x=x1,y=y1,yIncr=(y1>y2)?-1:1;var s=this.stroke;if(dx>=dy){if(dx>0&&s-3>0){var _s=(s*dx*Math.sqrt(1+dy*dy/(dx*dx))-dx-(s>>1)*dy)/dx;_s=(!(s-4)?Math.ceil(_s):Math.round(_s))+1;}else var _s=s;var ad=Math.ceil(s/2);var pr=dy<<1,pru=pr-(dx<<1),p=pr-dx,ox=x;while((dx--)>0){++x;if(p>0){this.mkDiv(ox,y,x-ox+ad,_s);y+=yIncr;p+=pru;ox=x;}else p+=pr;}this.mkDiv(ox,y,x2-ox+ad+1,_s);}else{if(s-3>0){var _s=(s*dy*Math.sqrt(1+dx*dx/(dy*dy))-(s>>1)*dx-dy)/dy;_s=(!(s-4)?Math.ceil(_s):Math.round(_s))+1;}else var _s=s;var ad=Math.round(s/2);var pr=dx<<1,pru=pr-(dy<<1),p=pr-dy,oy=y;if(y2<=y1){++ad;while((dy--)>0){if(p>0){this.mkDiv(x++,y,_s,oy-y+ad);y+=yIncr;p+=pru;oy=y;}else{y+=yIncr;p+=pr;}}this.mkDiv(x2,y2,_s,oy-y2+ad);}else{while((dy--)>0){y+=yIncr;if(p>0){this.mkDiv(x++,oy,_s,y-oy+ad);p+=pru;oy=y;}else p+=pr;}this.mkDiv(x2,oy,_s,y2-oy+ad+1);}}}function mkLinDott(x1,y1,x2,y2){if(x1>x2){var _x2=x2;var _y2=y2;x2=x1;y2=y1;x1=_x2;y1=_y2;}var dx=x2-x1,dy=Math.abs(y2-y1),x=x1,y=y1,yIncr=(y1>y2)?-1:1,drw=true;if(dx>=dy){var pr=dy<<1,pru=pr-(dx<<1),p=pr-dx;while((dx--)>0){if(drw)this.mkDiv(x,y,1,1);drw=!drw;if(p>0){y+=yIncr;p+=pru;}else p+=pr;++x;}if(drw)this.mkDiv(x,y,1,1);}else{var pr=dx<<1,pru=pr-(dy<<1),p=pr-dy;while((dy--)>0){if(drw)this.mkDiv(x,y,1,1);drw=!drw;y+=yIncr;if(p>0){++x;p+=pru;}else p+=pr;}if(drw)this.mkDiv(x,y,1,1);}}function mkOv(left,top,width,height){var a=width>>1,b=height>>1,wod=width&1,hod=(height&1)+1,cx=left+a,cy=top+b,x=0,y=b,ox=0,oy=b,aa=(a*a)<<1,bb=(b*b)<<1,st=(aa>>1)*(1-(b<<1))+bb,tt=(bb>>1)-aa*((b<<1)-1),w,h;while(y>0){if(st<0){st+=bb*((x<<1)+3);tt+=(bb<<1)*(++x);}else if(tt<0){st+=bb*((x<<1)+3)-(aa<<1)*(y-1);tt+=(bb<<1)*(++x)-aa*(((y--)<<1)-3);w=x-ox;h=oy-y;if(w&2&&h&2){this.mkOvQds(cx,cy,-x+2,ox+wod,-oy,oy-1+hod,1,1);this.mkOvQds(cx,cy,-x+1,x-1+wod,-y-1,y+hod,1,1);}else this.mkOvQds(cx,cy,-x+1,ox+wod,-oy,oy-h+hod,w,h);ox=x;oy=y;}else{tt-=aa*((y<<1)-3);st-=(aa<<1)*(--y);}}this.mkDiv(cx-a,cy-oy,a-ox+1,(oy<<1)+hod);this.mkDiv(cx+ox+wod,cy-oy,a-ox+1,(oy<<1)+hod);}function mkOv2D(left,top,width,height){var s=this.stroke;width+=s-1;height+=s-1;var a=width>>1,b=height>>1,wod=width&1,hod=(height&1)+1,cx=left+a,cy=top+b,x=0,y=b,aa=(a*a)<<1,bb=(b*b)<<1,st=(aa>>1)*(1-(b<<1))+bb,tt=(bb>>1)-aa*((b<<1)-1);if(s-4<0&&(!(s-2)||width-51>0&&height-51>0)){var ox=0,oy=b,w,h,pxl,pxr,pxt,pxb,pxw;while(y>0){if(st<0){st+=bb*((x<<1)+3);tt+=(bb<<1)*(++x);}else if(tt<0){st+=bb*((x<<1)+3)-(aa<<1)*(y-1);tt+=(bb<<1)*(++x)-aa*(((y--)<<1)-3);w=x-ox;h=oy-y;if(w-1){pxw=w+1+(s&1);h=s;}else if(h-1){pxw=s;h+=1+(s&1);}else pxw=h=s;this.mkOvQds(cx,cy,-x+1,ox-pxw+w+wod,-oy,-h+oy+hod,pxw,h);ox=x;oy=y;}else{tt-=aa*((y<<1)-3);st-=(aa<<1)*(--y);}}this.mkDiv(cx-a,cy-oy,s,(oy<<1)+hod);this.mkDiv(cx+a+wod-s+1,cy-oy,s,(oy<<1)+hod);}else{var _a=(width-((s-1)<<1))>>1,_b=(height-((s-1)<<1))>>1,_x=0,_y=_b,_aa=(_a*_a)<<1,_bb=(_b*_b)<<1,_st=(_aa>>1)*(1-(_b<<1))+_bb,_tt=(_bb>>1)-_aa*((_b<<1)-1),pxl=new Array(),pxt=new Array(),_pxb=new Array();pxl[0]=0;pxt[0]=b;_pxb[0]=_b-1;while(y>0){if(st<0){st+=bb*((x<<1)+3);tt+=(bb<<1)*(++x);pxl[pxl.length]=x;pxt[pxt.length]=y;}else if(tt<0){st+=bb*((x<<1)+3)-(aa<<1)*(y-1);tt+=(bb<<1)*(++x)-aa*(((y--)<<1)-3);pxl[pxl.length]=x;pxt[pxt.length]=y;}else{tt-=aa*((y<<1)-3);st-=(aa<<1)*(--y);}if(_y>0){if(_st<0){_st+=_bb*((_x<<1)+3);_tt+=(_bb<<1)*(++_x);_pxb[_pxb.length]=_y-1;}else if(_tt<0){_st+=_bb*((_x<<1)+3)-(_aa<<1)*(_y-1);_tt+=(_bb<<1)*(++_x)-_aa*(((_y--)<<1)-3);_pxb[_pxb.length]=_y-1;}else{_tt-=_aa*((_y<<1)-3);_st-=(_aa<<1)*(--_y);_pxb[_pxb.length-1]--;}}}var ox=0,oy=b,_oy=_pxb[0],l=pxl.length,w,h;for(var i=0;i<l;i++){if(typeof _pxb[i]!="undefined"){if(_pxb[i]<_oy||pxt[i]<oy){x=pxl[i];this.mkOvQds(cx,cy,-x+1,ox+wod,-oy,_oy+hod,x-ox,oy-_oy);ox=x;oy=pxt[i];_oy=_pxb[i];}}else{x=pxl[i];this.mkDiv(cx-x+1,cy-oy,1,(oy<<1)+hod);this.mkDiv(cx+ox+wod,cy-oy,1,(oy<<1)+hod);ox=x;oy=pxt[i];}}this.mkDiv(cx-a,cy-oy,1,(oy<<1)+hod);this.mkDiv(cx+ox+wod,cy-oy,1,(oy<<1)+hod);}}function mkOvDott(left,top,width,height){var a=width>>1,b=height>>1,wod=width&1,hod=height&1,cx=left+a,cy=top+b,x=0,y=b,aa2=(a*a)<<1,aa4=aa2<<1,bb=(b*b)<<1,st=(aa2>>1)*(1-(b<<1))+bb,tt=(bb>>1)-aa2*((b<<1)-1),drw=true;while(y>0){if(st<0){st+=bb*((x<<1)+3);tt+=(bb<<1)*(++x);}else if(tt<0){st+=bb*((x<<1)+3)-aa4*(y-1);tt+=(bb<<1)*(++x)-aa2*(((y--)<<1)-3);}else{tt-=aa2*((y<<1)-3);st-=aa4*(--y);}if(drw)this.mkOvQds(cx,cy,-x,x+wod,-y,y+hod,1,1);drw=!drw;}}function mkRect(x,y,w,h){var s=this.stroke;this.mkDiv(x,y,w,s);this.mkDiv(x+w,y,s,h);this.mkDiv(x,y+h,w+s,s);this.mkDiv(x,y+s,s,h-s);}function mkRectDott(x,y,w,h){this.drawLine(x,y,x+w,y);this.drawLine(x+w,y,x+w,y+h);this.drawLine(x,y+h,x+w,y+h);this.drawLine(x,y,x,y+h);}function jsgFont(){this.PLAIN='font-weight:normal;';this.BOLD='font-weight:bold;';this.ITALIC='font-style:italic;';this.ITALIC_BOLD=this.ITALIC+this.BOLD;this.BOLD_ITALIC=this.ITALIC_BOLD;}var Font=new jsgFont();function jsgStroke(){this.DOTTED=-1;}var Stroke=new jsgStroke();function jsGraphics(id,wnd){this.setColor=new Function('arg','this.color = arg.toLowerCase();');this.setStroke=function(x){this.stroke=x;if(!(x+1)){this.drawLine=mkLinDott;this.mkOv=mkOvDott;this.drawRect=mkRectDott;}else if(x-1>0){this.drawLine=mkLin2D;this.mkOv=mkOv2D;this.drawRect=mkRect;}else{this.drawLine=mkLin;this.mkOv=mkOv;this.drawRect=mkRect;}};this.setPrintable=function(arg){this.printable=arg;if(jg_fast){this.mkDiv=mkDivIe;this.htmRpc=arg?htmPrtRpc:htmRpc;}else this.mkDiv=jg_n4?mkLyr:arg?mkDivPrt:mkDiv;};this.setFont=function(fam,sz,sty){this.ftFam=fam;this.ftSz=sz;this.ftSty=sty||Font.PLAIN;};this.drawPolyline=this.drawPolyLine=function(x,y,s){for(var i=0;i<x.length-1;i++)this.drawLine(x[i],y[i],x[i+1],y[i+1]);};this.fillRect=function(x,y,w,h){this.mkDiv(x,y,w,h);};this.drawPolygon=function(x,y){this.drawPolyline(x,y);this.drawLine(x[x.length-1],y[x.length-1],x[0],y[0]);};this.drawEllipse=this.drawOval=function(x,y,w,h){this.mkOv(x,y,w,h);};this.fillEllipse=this.fillOval=function(left,top,w,h){var a=(w-=1)>>1,b=(h-=1)>>1,wod=(w&1)+1,hod=(h&1)+1,cx=left+a,cy=top+b,x=0,y=b,ox=0,oy=b,aa2=(a*a)<<1,aa4=aa2<<1,bb=(b*b)<<1,st=(aa2>>1)*(1-(b<<1))+bb,tt=(bb>>1)-aa2*((b<<1)-1),pxl,dw,dh;if(w+1)while(y>0){if(st<0){st+=bb*((x<<1)+3);tt+=(bb<<1)*(++x);}else if(tt<0){st+=bb*((x<<1)+3)-aa4*(y-1);pxl=cx-x;dw=(x<<1)+wod;tt+=(bb<<1)*(++x)-aa2*(((y--)<<1)-3);dh=oy-y;this.mkDiv(pxl,cy-oy,dw,dh);this.mkDiv(pxl,cy+y+hod,dw,dh);ox=x;oy=y;}else{tt-=aa2*((y<<1)-3);st-=aa4*(--y);}}this.mkDiv(cx-a,cy-oy,w+1,(oy<<1)+hod);};this.fillPolygon=function(array_x,array_y){var i;var y;var miny,maxy;var x1,y1;var x2,y2;var ind1,ind2;var ints;var n=array_x.length;if(!n)return;miny=array_y[0];maxy=array_y[0];for(i=1;i<n;i++){if(array_y[i]<miny)miny=array_y[i];if(array_y[i]>maxy)maxy=array_y[i];}for(y=miny;y<=maxy;y++){var polyInts=new Array();ints=0;for(i=0;i<n;i++){if(!i){ind1=n-1;ind2=0;}else{ind1=i-1;ind2=i;}y1=array_y[ind1];y2=array_y[ind2];if(y1<y2){x1=array_x[ind1];x2=array_x[ind2];}else if(y1>y2){y2=array_y[ind1];y1=array_y[ind2];x2=array_x[ind1];x1=array_x[ind2];}else continue;if((y>=y1)&&(y<y2))polyInts[ints++]=Math.round((y-y1)*(x2-x1)/(y2-y1)+x1);else if((y==maxy)&&(y>y1)&&(y<=y2))polyInts[ints++]=Math.round((y-y1)*(x2-x1)/(y2-y1)+x1);}polyInts.sort(integer_compare);for(i=0;i<ints;i+=2)this.mkDiv(polyInts[i],y,polyInts[i+1]-polyInts[i]+1,1);}};this.drawString=function(txt,x,y){this.htm+='<div style="position:absolute;white-space:nowrap;'+'left:'+x+'px;'+'top:'+y+'px;'+'font-family:'+this.ftFam+';'+'font-size:'+this.ftSz+';'+'color:'+this.color+';'+this.ftSty+'">'+txt+'<\/div>';};this.drawStringRect=function(txt,x,y,width,halign){this.htm+='<div style="position:absolute;overflow:hidden;'+'left:'+x+'px;'+'top:'+y+'px;'+'width:'+width+'px;'+'text-align:'+halign+';'+'font-family:'+this.ftFam+';'+'font-size:'+this.ftSz+';'+'color:'+this.color+';'+this.ftSty+'">'+txt+'<\/div>';};this.drawImage=function(imgSrc,x,y,w,h,a){this.htm+='<div style="position:absolute;'+'left:'+x+'px;'+'top:'+y+'px;'+'width:'+w+';'+'height:'+h+';">'+'<img src="'+imgSrc+'" width="'+w+'" height="'+h+'"'+(a?(' '+a):'')+'>'+'<\/div>';};this.clear=function(){this.htm="";if(this.cnv)this.cnv.innerHTML=this.defhtm;};this.mkOvQds=function(cx,cy,xl,xr,yt,yb,w,h){this.mkDiv(xr+cx,yt+cy,w,h);this.mkDiv(xr+cx,yb+cy,w,h);this.mkDiv(xl+cx,yb+cy,w,h);this.mkDiv(xl+cx,yt+cy,w,h);};this.setStroke(1);this.setFont('verdana,geneva,helvetica,sans-serif',String.fromCharCode(0x31,0x32,0x70,0x78),Font.PLAIN);this.color='#000000';this.htm='';this.wnd=wnd||window;if(!(jg_ie||jg_dom||jg_ihtm))chkDHTM();if(typeof id!='string'||!id)this.paint=pntDoc;else{this.cnv=document.all?(this.wnd.document.all[id]||null):document.getElementById?(this.wnd.document.getElementById(id)||null):null;this.defhtm=(this.cnv&&this.cnv.innerHTML)?this.cnv.innerHTML:'';this.paint=jg_dom?pntCnvDom:jg_ie?pntCnvIe:jg_ihtm?pntCnvIhtm:pntCnv;}this.setPrintable(false);}function integer_compare(x,y){return(x<y)?-1:((x>y)*1);}var widthh;var heightt;var leftt;var topp;var customEnv="";var customInitialMap=false;var customQuery=false;var distanceString="";var customMapService=false;var nomCustomMapService="";var debugOn=false;var customMinx;var customMaxx;var customMiny;var customMaxy;var customTool=false;var customToolEditar=false;var customToolType="";var customToolEditarType="";var _theInitialActiveLayer;var _theInitialQuery;var distanceList=new Array;var findWin,tocWin,legendWin,resultsWin,detailedQueryWin,detailedResultsWin,queryResultsWin,toolBarWin;var distanceMeasureWin,areaMeasureWin,editarWin,historicoWin,printOptionsWin,overviewWin,bufferCircleWin;function checkInitialParams(){cmdString=document.location.toString();var bboxString=getInitialParam(cmdString,"BOX=");if(bboxString!=""){var xyBox=bboxString.split(":");if(xyBox.length==4){customMinx=parseFloat(xyBox[0]);customMiny=parseFloat(xyBox[1]);customMaxx=parseFloat(xyBox[2]);customMaxy=parseFloat(xyBox[3]);customEnv='<ENVELOPE minx="'+parseFloat(xyBox[0])+'" miny="'+parseFloat(xyBox[1])+'" maxx="'+parseFloat(xyBox[2])+'" maxy="'+parseFloat(xyBox[3])+'" />';customInitialMap=true;}}debugString=getInitialParam(cmdString,"DEBUG=").toUpperCase();if((debugString=="TRUE")||(debugString=="TRUE#")){debugOn=true;}debugString=getInitialParam(cmdString,"debug=").toUpperCase();if((debugString=="TRUE")||(debugString=="TRUE#")){debugOn=true;}_theInitialActiveLayer=getInitialParam(cmdString,"ACTIVELAYER=");_theInitialQueryUnsafe=getInitialParam(cmdString,"QUERY=");_theInitialQueryService=getInitialParam(cmdString,"QUERYSERVICE=");var newQueryURL=defaultQueryUrl;if((_theInitialActiveLayer!="")&&(_theInitialQuery!="")){customInitialMap=true;customQuery=true;if(_theInitialQueryService!=""){newQueryURL=server+"/servlet/com.esri.esrimap.Esrimap?ServiceName="+_theInitialQueryService+"&Form=False&ClientVersion=4.0&CustomService=Query";}_theInitialQuery=getSafeParam(_theInitialQueryUnsafe);initialQueryString="initialQuery('"+_theInitialQuery+"', '"+_theInitialActiveLayer+"', '"+newQueryURL+"');";}nucleoString=getInitialParam(cmdString,"nucleo=");if(nucleoString!=""){customInitialMap=true;customQuery=true;initialQueryString="initialQuery('C_NUCLEO_I="+nucleoString+"', 'Localidad');";}customToolString=getInitialParam(cmdString,"CUSTOMTOOL=").toUpperCase();if((customToolString=="GEOREF1")||(debugString=="GEOREF1#")){customToolEditar=true;customToolEditarType="GEOREF1";}if((customToolString=="GEOREF2")||(debugString=="GEOREF2#")){customToolEditar=true;customToolEditarType="GEOREF2";}if((customToolString=="GRANJAS")||(debugString=="GRANJAS#")){customTool=true;customToolType="GRANJAS";}pos=cmdString.indexOf("DISTANCIAS=");if(pos!=-1){startpos=pos+11;endpos=cmdString.indexOf("&",startpos);if(endpos==-1){endpos=cmdString.indexOf("#",startpos);if(endpos==-1){endpos=cmdString.length;}}distanceString=cmdString.substring(startpos,endpos);distList=distanceString.split(",");for(var i=0;i<distList.length;i++){distanceList[i]=parseFloat(distList[i]);}}var _theMarkerX=getInitialParam(cmdString,"MARKERX=");var _theMarkerY=getInitialParam(cmdString,"MARKERY=");if((_theMarkerX!="")&&(_theMarkerY!="")){_theXUnsafe=normalizaCadena(_theMarkerX);_theYUnsafe=normalizaCadena(_theMarkerY);xCoordUsr=getSafeParam(_theXUnsafe);yCoordUsr=getSafeParam(_theYUnsafe);}var _theViaUnsafe=getInitialParam(cmdString,"NOMVIA=");var _theLocUnsafe=getInitialParam(cmdString,"LOCALIDAD_NOMVIA=");var _thePortalUnsafe=getInitialParam(cmdString,"NUMPORTAL=");if((_theViaUnsafe!="")&&(_theLocUnsafe!="")){customInitialMap=true;customQuery=true;_theViaUnsafe=normalizaCadena(_theViaUnsafe);_theLocUnsafe=normalizaCadena(_theLocUnsafe);var _theVia=getSafeParam(_theViaUnsafe);var _theLoc=getSafeParam(_theLocUnsafe);var _thePortal=getSafeParam(_thePortalUnsafe);initialQueryString="queryCallejero('"+_theVia+"', '"+_theLoc+"', '"+_thePortal+"', true);";}var _theToponimoUnsafe=getInitialParam(cmdString,"TOPONIMO=");var _theMuniToponimoUnsafe=getInitialParam(cmdString,"MUNI_TOPONIMO=");if(_theToponimoUnsafe!=""){customInitialMap=true;customQuery=true;_theToponimoUnsafe=normalizaCadena(_theToponimoUnsafe);_theMuniToponimoUnsafe=normalizaCadena(_theMuniToponimoUnsafe);var _theToponimo=getSafeParam(_theToponimoUnsafe);var _theMuniToponimo=getSafeParam(_theMuniToponimoUnsafe);initialQueryString="queryToponimo('"+_theToponimo+"','"+_theMuniToponimo+"');";}nomCustomMapService=getInitialParam(cmdString,"EXCLUSIVO=");if(nomCustomMapService!=""){customMapService=true;url=server+"/servlet/com.esri.esrimap.Esrimap?ServiceName="+nomCustomMapService+"&Form=False&ClientVersion=4.0";}}var initialVisibleLayers=new Array();var initialHiddenLayers=new Array();function getInitialVisibilityLayers(){cmdString=document.location.toString();pos=cmdString.indexOf("VISIBLELAYERS=");if(pos!=-1){startpos=pos+14;endpos=cmdString.indexOf("&",startpos);if(endpos==-1){endpos=cmdString.indexOf("#",startpos);if(endpos==-1){endpos=cmdString.length;}}var visibString=cmdString.substring(startpos,endpos);initialVisibleLayers=visibString.split(",");}pos=cmdString.indexOf("HIDDENLAYERS=");if(pos!=-1){startpos=pos+13;endpos=cmdString.indexOf("&",startpos);if(endpos==-1){endpos=cmdString.indexOf("#",startpos);if(endpos==-1){endpos=cmdString.length;}}var hiddenString=cmdString.substring(startpos,endpos);initialHiddenLayers=hiddenString.split(",");}}function getSafeParam(inParam){var aux=replacePlus(inParam);aux=unescape(aux);return makeXMLsafe(aux);}function getInitialParam(str,strToFind){pos=str.indexOf(strToFind);if(pos!=-1){startpos=pos+strToFind.length;endpos=str.indexOf("&",startpos);if(endpos==-1){endpos=str.length;}return str.substring(startpos,endpos);}else{return"";}}function startUp(){checkInitialParams();getServiceInfo();}function pintaElementosMapa(){widthh=document.body.clientWidth-(minLeft+(2*gap));heightt=document.body.clientHeight-(minTop+(2*gap))-30;leftt=minLeft+gap;topp=minTop+gap;document.write('<img id="theAcetateEscala" src="images/pixel.gif" style="position:absolute;top:'+(topp+38)+'px;left:'+(leftt)+'px;z-index:201;overflow:hidden;"/>');document.write('<img id="theAcetateMarca" src="images/pixel.gif" style="position:absolute;top:'+(topp)+'px;left:'+(leftt)+'px;z-index:201;overflow:hidden;"/>');var content='';content+="<div id=\""+DivId+"\" style=\"position:absolute;width:"+(widthh-(2*borderr))+"px;height:"+(heightt-(2*borderr))+"px;top:0px; left:0px;\" >";if(isIE6){content+='<img id="theNorthArrow" src="images/norte.gif" style="position:absolute;top:'+(heightt-100)+'px;left:'+(widthh-80)+'px;z-index:500;"/>';}else{content+='<img id="theNorthArrow" src="images/norte.png" style="position:absolute;top:'+(heightt-100)+'px;left:'+(widthh-80)+'px;z-index:500;"/>';}content+='<img id="theImage" src="images/pixel.gif" style="position:absolute;top:0px;left:0px;z-index:100;" class="transp65" />';for(ii=0;ii<wmsList["count"];ii++){content+='<img id="theImageWMS'+ii+'" src="images/pixel.gif" style="position:absolute;top:0px;left:0px;z-index:'+wmsList[ii]["zIdx"]+';" onload="loadedWMS(\''+ii+'\')" class="'+wmsList[ii]["clase"]+'" />';}content+='<'+'/div>';createMapContainer('mapContainer',content,topp,leftt,widthh,heightt,borderr,'mapclass');setMapDivProperties(topp,leftt,widthh,heightt,borderr,DivId);createZoomBoxDivs();createLayer("measureBoxDiv",mleft,mtop,mwidth,mheight,true,'',1200);createLayer("eventosMapa",mleft,mtop,mwidth,mheight,true,'',1250);document.getElementById('eventosMapa').style.backgroundImage="url(images/pixel.gif)";}function pintaLoading(){var loadingTop=topp+(heightt/2)-10;var loadingLeft=leftt+(widthh/2)-110;var loadingContent='<div id="loading" style="position:absolute;top:'+loadingTop+'px; left:'+loadingLeft+'px;visibility:visible;z-index:1000;" >';loadingContent+='<img id="theLoadingImage" src="images/loading.gif"/>';loadingContent+='<'+'/div>';document.writeln(loadingContent);}function pintaElementosZonaSuperior(){document.write('<table width="100%" height="'+(gap)+'px" cellpadding="0" cellspacing="0" style="position:absolute;top:'+(mtop)+'px;left:0px;table-layout:fixed;z-index:1500;">');document.write('<tr>');document.write('<td width="'+gap+'px"></td>');document.write('<td id="tablaSuperior1" align="left">');document.write('</td>');document.write('<td id="tablaSuperior2" align="right">');document.write('&nbsp;<input type="button" onclick="javascript:showFondoMudo();" id="bgMudoShowId" style="visibility:visible;" value="Desactivar Fondo"></input>');document.write('&nbsp;<input type="button" onclick="javascript:showFondoMapa();" id="bgMapaShowId" style="visibility:visible;" value="Arag&oacute;n Mapa"></input>');document.write('&nbsp;<input type="button" disabled onclick="javascript:showFondoFoto();" id="bgFotoShowId" style="visibility:visible;" value="Arag&oacute;n Foto"></input>');document.write('</td>');document.write('<td width="'+gap+'px"></td>');document.write('</tr>');document.write('</table>');}function pintaElementosZonaInferior(){document.write('<table id="tablaInferior" width="100%" height="30px" cellpadding="0" cellspacing="2" style="position:absolute;top:'+(document.body.clientHeight-30)+'px;left:0px;table-layout:fixed;z-index:1500;">');document.write('<tr>');document.write('<td width="'+(gap+340)+'px"></td>');document.write('<td class="textoInferior" id="textosInferior">');document.write('<label for="scaleTextBox">Escala aproximada 1:</label>');document.write('<input onmousedown="this.focus()" onclick="this.focus()" onkeypress="cboEscala_onkeypress(event)" onFocus="act(\'scaleTextBox\')" onBlur="deac(\'scaleTextBox\')" id="scaleTextBox" size="9" maxlength="12" class="textoInferior2" type="text" value="" style="z-index:13000">');document.write('<img valign="bottom" alt="Actualiza la escala" onmousedown="javascript:updateScale();" src="images/play.gif" border="0">');document.write('<label for="Lx"> X: </label>');document.write('<input type="text" disabled id="Lx" value="" size="11" class="textoInferior2"></input>');document.write('m&nbsp; &nbsp;');document.write('<label for="Ly"> Y: </label>');document.write('<input type="text" disabled id="Ly" value="" size="11" class="textoInferior2"></input>');document.write('m&nbsp; &nbsp;');document.write('<select id="cboSRSClient" class="textoInferior2">');document.write(' <option value="EPSG:23030" selected>UTM ED50 Huso 30</option>');document.write(' <option value="EPSG:23031">UTM ED50 Huso 31</option>');document.write('</select>');document.write('</td>');document.write("<td width='"+(gap)+"px'></td>");document.write('</tr>');document.write('</table>');}function reajustBbox(newW,newH){xDiffPx=(newW-(2*borderr))-mwidth;yDiffPx=(newH-(2*borderr))-mheight;xDiffCoord=maxx-minx;coordPerPx=xDiffCoord/mwidth;maxx=maxx+(xDiffPx*coordPerPx);miny=miny-(yDiffPx*coordPerPx);}function updateMapSize(newW,newH){reajustBbox(newW,newH);document.getElementById("mapArea").style.width=(newW-(2*borderr))+"px";document.getElementById("mapArea").style.height=(newH-(2*borderr))+"px";updateMapContainer('mapContainer',newW,newH);updateMapDivProperties(newW,newH);document.getElementById("eventosMapa").style.width=(newW-(2*borderr))+"px";document.getElementById("eventosMapa").style.height=(newH-(2*borderr))+"px";document.getElementById("measureBoxDiv").style.width=(newW-(2*borderr))+"px";document.getElementById("measureBoxDiv").style.height=(newH-(2*borderr))+"px";getMapWithCurrentExtent();}onresize=pagereloader;function pagereloader(){mbarleftpos=Math.round((document.body.clientWidth-550)/2)+22;newWidth=document.body.clientWidth-(minLeft+(2*gap));newHeight=document.body.clientHeight-(minTop+(2*gap))-30;document.getElementById('theNorthArrow').style.top=(newHeight-100)+"px";document.getElementById('theNorthArrow').style.left=(newWidth-80)+"px";document.getElementById('tablaInferior').style.top=(document.body.clientHeight-30)+"px";var newLoadingTop=topp+(newHeight/2)-10;var newLoadingLeft=leftt+(newWidth/2)-110;document.getElementById('loading').style.top=(newLoadingTop)+"px";document.getElementById('loading').style.left=(newLoadingLeft)+"px";updateMapSize(newWidth,newHeight);oldMaxxWindows=eval("findWin").maxx;oldMaxyWindows=eval("findWin").maxy;for(x in windowarr){wid=windowarr[x];eval(wid).setmaxx(document.body.clientWidth-gap);eval(wid).setmaxy(document.body.clientHeight-gap-30);}browserresize(oldMaxxWindows,oldMaxyWindows);}function RoundDecimal(num,d){var m=Math.pow(10,d);var num2=num*m;return(Math.round(num2)/m);}function degrees2radians(degrees){return(degrees*Math.PI/180);}function radians2degrees(radians){return(radians*180/Math.PI);}function isEnterKey(evt){if(!evt){return(evt.keyCode==13);}else if(!evt.keyCode){return(evt.which==13);}return(evt.keyCode==13);}function getMouse(e){getXY2(e);mouseStuff();return false;}function mouseStuff(){numDecimals=2;var coordActual=getMapXY(theX,theY);coordActualX=coordActual[0];coordActualY=coordActual[1];setNewCoords(coordActualX,coordActualY);if(isDistanceMeasuring){movement_distanceMeasure(coordActualX,coordActualY);}}function Recordset(attributesNamesList){this.attributesNamesList=attributesNamesList||new Array();this.geometryList=new Array();this.attributesList=new Array();this.nextPosition=0;this.getGeometryList=getGeometryList;this.getGeometry=getGeometry;this.getAttributesList=getAttributesList;this.getAttribute=getAttribute;this.getAttributeNamesList=getAttributeNamesList;this.setAttributeNamesList=setAttributeNamesList;this.addVectorialData=addVectorialData;this.removeVectorialData=removeVectorialData;this.clearVectorialData=clearVectorialData;this.getVectorialDataCount=getVectorialDataCount;function getAttributeNamesList(){return this.attributesNamesList;}function setAttributeNamesList(newAttributesNamesList){this.attributesNamesList=newAttributesNamesList;}function getGeometryList(){return this.geometryList;}function getGeometry(index){return this.geometryList[index];}function getAttributesList(index){return this.attributesList[index];}function getAttribute(index,nameAttribute){indexCol=-1;for(var i=0;i<this.getAttributeNamesList().length;i++){if(this.getAttributeNamesList()[i]==nameAttribute){indexCol=this.getAttributeNamesList()[i];}}if(indexCol!=-1){return this.attributesList[index][indexCol];}else{return null;}}function addVectorialData(newGeometry,newAttributesList){this.geometryList[this.nextPosition]=newGeometry;this.attributesList[this.nextPosition]=newAttributesList;this.nextPosition++;}function removeVectorialData(index){this.geometryList[index]=null;this.attributesList[index]=null;for(var i=index;i<this.nextPosition-1;i++){this.geometryList[i]=this.geometryList[i+1];this.attributesList[i]=this.attributesList[i+1];}this.nextPosition--;}function clearVectorialData(){this.nextPosition=0;}function getVectorialDataCount(){return this.nextPosition;}}function showLineSelectZone(){showZone("lineSelectZone");}function showPolySelectZone(){showZone("polySelectZone");}function hideLineSelectZone(){hideZone("lineSelectZone");}function hidePolySelectZone(){hideZone("polySelectZone");}function hideSelectZone(){hideLineSelectZone();hidePolySelectZone();}function hideGeorefZone(){hidePointGeorefZone();hideLineGeorefZone();hidePolyGeorefZone();hideGeomGeorefZone();}function showCoordsZone(){showZone("coordsZone");}function hideCoordsZone(){hideZone("coordsZone");}function showPointGeorefZone(){showZone("pointGeorefZone");showZone("georefPointDiv");showZone("georefPointGeomDiv");showZone("georefPointLabelDiv");}function hidePointGeorefZone(){hideZone("pointGeorefZone");hideZone("georefPointDiv");}function showLineGeorefZone(){showZone("lineGeorefZone");showZone("georefLineDiv");showZone("georefLineGeomDiv");showZone("georefLineLabelDiv");}function hideLineGeorefZone(){hideZone("lineGeorefZone");hideZone("georefLineDiv");}function showPolyGeorefZone(){showZone("polyGeorefZone");showZone("georefPolyDiv");showZone("georefPolyGeomDiv");showZone("georefPolyLabelDiv");}function hidePolyGeorefZone(){hideZone("polyGeorefZone");hideZone("georefPolyDiv");}function hideGeomGeorefZone(){hideZone("georefPolyGeomDiv");hideZone("georefPolyLabelDiv");hideZone("georefLineGeomDiv");hideZone("georefLineLabelDiv");hideZone("georefPointGeomDiv");hideZone("georefPointLabelDiv");}function showHistoricoZone(){showZone("historicoDiv");showZone("georefHistoricoGeomDiv");showZone("georefHistoricoLabelDiv");}function hideHistoricoZone(){hideZone("historicoDiv");hideZone("georefHistoricoGeomDiv");hideZone("georefHistoricoLabelDiv");}function toggleZone(id){obj=document.getElementById(id);if(obj.style.visibility=="visible"){hideZone(id);}else{showZone(id);}}function showZone(id){obj=document.getElementById(id);obj.style.visibility="visible";}function hideZone(id){obj=document.getElementById(id);obj.style.visibility="hidden";}function closeSelect(){hideSelectZone();resetToolBar();}function closeHistorico(){hideHistoricoZone();resetToolBar();}function closeGeorref(){hideGeorefZone();resetToolBar();}function closeMeasure(){hideSelectZone();resetToolBar();}function act(idObj){document.getElementById(idObj).style.border="#CC0000 solid 2px";}function deac(idObj){document.getElementById(idObj).style.border="";}function replacePlus(inText){var re=/\+/g;inText=inText.replace(re," ");return inText;}function makeXMLsafe(oldString){oldString=oldString.replace(/&/g,"&amp;");oldString=oldString.replace(/'/g,"&apos;");oldString=oldString.replace(/>/g,"&gt;");oldString=oldString.replace(/</g,"&lt;");oldString=oldString.replace(/"/g,"&quot;");oldString=normalizaCadenaURL(oldString);return oldString;}function makeXMLsafeAcentos(oldString){var aux=oldString;aux=aux.replace(/&nbsp;/g," ");aux=aux.replace(/&/g,"&amp;");aux=aux.replace(/<link href=".*page.css" rel="StyleSheet" type="text\/css">/g,"");aux=aux.replace(/&amp;ordm;/g,"&#186;");if(aux.indexOf("src='")!=-1){if(aux.indexOf("src='http://")==-1){aux=aux.replace(/src='/g,"src='"+urlApp);}}if(aux.indexOf("src=\"")!=-1){if(aux.indexOf("src=\"http://")==-1){aux=aux.replace(/src="/g,"src=\""+urlApp);}}aux=aux.replace(/&amp;ordm;/g,"&#186;");aux=aux.replace(/&amp;ordf;/g,"&#170;");aux=aux.replace(/&amp;quot;/g,"&#34;");aux=aux.replace(/&amp;aacute;/g,"&#225;");aux=aux.replace(/&amp;eacute;/g,"&#233;");aux=aux.replace(/&amp;iacute;/g,"&#237;");aux=aux.replace(/&amp;oacute;/g,"&#243;");aux=aux.replace(/&amp;uacute;/g,"&#250;");aux=aux.replace(/&amp;ntilde;/g,"&#241;");aux=aux.replace(/&amp;uuml;/g,"&#252;");aux=aux.replace(/&amp;Aacute;/g,"&#193;");aux=aux.replace(/&amp;Eacute;/g,"&#201;");aux=aux.replace(/&amp;Iacute;/g,"&#205;");aux=aux.replace(/&amp;Oacute;/g,"&#211;");aux=aux.replace(/&amp;Uacute;/g,"&#218;");aux=aux.replace(/&amp;Ntilde;/g,"&#209;");aux=aux.replace(/&amp;Uuml;/g,"&#220;");aux=aux.replace(/á/g,"&#225;");aux=aux.replace(/é/g,"&#233;");aux=aux.replace(/í/g,"&#237;");aux=aux.replace(/ó/g,"&#243;");aux=aux.replace(/ú/g,"&#250;");aux=aux.replace(/ñ/g,"&#241;");aux=aux.replace(/ü/g,"&#252;");aux=aux.replace(/Á/g,"&#193;");aux=aux.replace(/É/g,"&#201;");aux=aux.replace(/Í/g,"&#205;");aux=aux.replace(/Ó/g,"&#211;");aux=aux.replace(/Ú/g,"&#218;");aux=aux.replace(/Ñ/g,"&#209;");aux=aux.replace(/Ü/g,"&#220;");return aux;}function loadedWMS(idx){document.getElementById(wmsList[idx]["id"]).style.display="block";loadingWMSId="wmsLoading"+idx;if(document.getElementById(loadingWMSId)){document.getElementById(loadingWMSId).style.visibility="hidden";}}function setNewCoords(x,y){comboSRS=document.getElementById('cboSRSClient');theSRS=comboSRS.options[comboSRS.selectedIndex].value;theX=x;theY=y;if(theSRS!="EPSG:23030"){destino=coordTransform("EPSG:23030",theSRS,x,y);theX=destino[0];theY=destino[1];}theX=RoundDecimal(theX,numDecimals);theY=RoundDecimal(theY,numDecimals);document.getElementById("Lx").value=theX;document.getElementById("Ly").value=theY;}function cboEscala_onkeypress(evt){if(isEnterKey(evt)){updateScale();}}function setNewScale(newScale){document.getElementById('scaleTextBox').value=newScale;}function updateScale(){newValue=document.getElementById('scaleTextBox').value;if(!isNaN(newValue)){if(newValue>=500){doZoomScale(newValue);return false;}else if((newValue>0)&&(newValue<500)){window.alert("La escala debe ser mayor que 500");}else if(newValue<=0){window.alert("La escala debe ser un número positivo mayor que 500");}}else{window.alert("La escala debe ser un número positivo mayor que 500");}}var cuantasWheel=0;var xWheel=-1;var yWheel=-1;var tWheel=-1;function wheelRaton(e){if(tWheel!=-1){clearTimeout(tWheel);}var evt=window.event||e;var delta=evt.detail?evt.detail*(-120):evt.wheelDelta;xWheel=Math.round(mwidth/2);yWheel=Math.round(mheight/2);if(delta>0){cuantasWheel++;}else{cuantasWheel--;}tWheel=setTimeout("actualizaWheel()",400);}function actualizaWheel(){var cuantasWheelAux=cuantasWheel;cuantasWheel=0;if(cuantasWheelAux>0){fixedZoomIn(xWheel,yWheel,cuantasWheelAux);}else{fixedZoomOut(xWheel,yWheel,Math.abs(cuantasWheelAux));}}function ocultaLayerLoading(){hideLayer('loading');}function muestraLayerLoading(){showLayer('loading');setTimeout("ocultaLayerLoading()",30000);}var cuantasVeces=0;function activaBusqueda(){if(document.getElementById("muniBus")){actb(document.getElementById("muniBus"),customarrayMuni);}else{cuantasVeces++;if(cuantasVeces<10){setTimeout("activaBusqueda()",500);}else{}}}function setColorMarcas(newColor){jg.setColor(newColor);jgPoint.setColor(newColor);jgPointLabel.setColor(newColor);jgLine.setColor(newColor);jgLineLabel.setColor(newColor);jgPol.setColor(newColor);jgPolLabel.setColor(newColor);jgHistorico.setColor(newColor);jgHistoricoLabel.setColor(newColor);jgCircle.setColor(newColor);jgCircleGranjas.setColor(newColor);}function toggleZoneTexto(theId,theText){theTableId=theId+"Table";theLinkId=theId+"Link";theTable=document.getElementById(theTableId);theLink=document.getElementById(theLinkId);if(theTable.style.display=='none'){theTable.style.display='block';theLink.innerHTML='Ocultar '+theText;theLink.title='Ocultar '+theText;}else{theTable.style.display='none';theLink.innerHTML='Mostrar '+theText;theLink.title='Mostrar '+theText;}}function toggleZoneCarpeta(theId,theText){theTableId=theId+"Table";theLinkId=theId+"Link";theTable=document.getElementById(theTableId);theLink=document.getElementById(theLinkId);if(theTable.style.display=='none'){theTable.style.display='block';theTable.style.visibility='visible';theLink.innerHTML="<img src='imagesTOC/old_icon_opened.gif' border='0'></img>";theLink.title='Ocultar '+theText;}else{theTable.style.display='none';theTable.style.visibility='hidden';theLink.innerHTML="<img src='imagesTOC/old_icon_closed.gif' border='0'></img>";theLink.title='Mostrar '+theText;}}function Unit(unit){this.unit=unit;this.canConvert=canConvert;this.equals=equals;function canConvert(){return true;}function equals(aUnit){return(aUnit.unit==this.unit);}}function Unit_metre(){return new Unit('m');}function Unit_degree(){return new Unit('°');}function WGS84ConversionInfo(){this.dx=-1;this.dy=-1;this.dz=-1;this.ex=-1;this.ey=-1;this.ez=-1;this.ppm=-1;this.areaOfUse='';this.equals=equals;function equals(that){if((this.dx==that.dx)&&(this.dy==that.dy)&&(this.dz==that.dz)&&(this.ex==that.ex)&&(this.ey==that.ey)&&(this.ez==that.ez)&&(this.ppm==that.ppm)&&(this.areaOfUse==that.areaOfUse)){return true;}return false;}}function Info(name){this.name=name;this.getName=getName();this.ensureAngularUnit=ensureAngularUnit;this.ensureLinearUnit=ensureLinearUnit;function getName(){return this.name;}function ensureLinearUnit(unit){if(!new Unit_metre().canConvert(unit)){alert("Error: Unit::ensureLinearUnit");}}function ensureAngularUnit(unit){if(!new Unit_degree.canConvert(unit)){alert("Error: Unit::ensureAngularUnit");}}}function Ellipsoid(name,semiMajorAxis,semiMinorAxis,inverseFlattening,ivfDefinitive,unit){this.icsl304=Info;this.icsl304(name);this.unit=unit;this.semiMajorAxis=check("semiMajorAxis",semiMajorAxis);this.semiMinorAxis=check("semiMinorAxis",semiMinorAxis);this.inverseFlattening=check("inverseFlattening",inverseFlattening);this.ivfDefinitive=ivfDefinitive;this.check=check;this.equals=equals;this.ensureLinearUnit(unit);this.getSemiMinorAxis=getSemiMinorAxis;this.getSemiMajorAxis=getSemiMajorAxis;function getSemiMinorAxis(){return this.semiMinorAxis;}function getSemiMajorAxis(){return this.semiMajorAxis;}this.createEllipsoid=createEllipsoid;function check(name,value){if(value>0){return value;}alert("Error Ellipsoid::check: "+name);}function createEllipsoid(name,semiMajorAxis,semiMinorAxis,unit){if(semiMajorAxis==semiMinorAxis){return new Spheroid(name,semiMajorAxis,false,unit);}else{return new Ellipsoid(name,semiMajorAxis,semiMinorAxis,semiMajorAxis/(semiMajorAxis-semiMinorAxis),false,unit);}}function equals(anEllips){if(this.semiMajorAxis==anEllips.semiMajorAxis){if(this.semiMinorAxis==anEllips.semiMinorAxis){if(this.inverseFlattening==anEllips.inverseFlattening){return true;}}}return false;}}Ellipsoid.prototype=Info;function Ellipsoid_FlattenedSphere(name,semiMajorAxis,inverseFlattening,unit){if(!isFinite(inverseFlattening)){return new Spheroid(name,semiMajorAxis,true,unit);}else{return new Ellipsoid(name,semiMajorAxis,semiMajorAxis*(1-1/inverseFlattening),inverseFlattening,true,unit);}}function Spheroid(name,radius,ivfDefinitive,unit){this.icsl304=Ellipsoid;this.icsl304(name,this.check("radius",radius),radius,Infinity,ivfDefinitive,unit);}Spheroid.prototype=Ellipsoid;function Ellipsoid_WGS84(){return new Ellipsoid_FlattenedSphere("WGS84",6378137.0,298.257223563,new Unit_metre());}function DatumType(name,value,key){this.name=name;this.value=value;this.key=key;}function DatumType_classic(){return new DatumType("CLASSIC",1001,5);}function DatumType_geocentric(){return new DatumType("GEOCENTRIC",1002,15);}function Datum(name,datumType){this.icsl304=Info;this.icsl304(name);this.datumType=datumType;this.getDatumType=getDatumType;function getDatumType(){return this.datumType;}}Datum.prototype=Info;function HorizontalDatum(name,type,ellipsoid,parameters){this.icsl304=Datum;this.icsl304(name,type);this.ellipsoid=ellipsoid;this.parameters=parameters;this.equals=equals;this.getEllipsoid=getEllipsoid;this.equals=equals;function getEllipsoid(){return this.ellipsoid;}function equals(aHorizDatum){if(this.getEllipsoid().equals(aHorizDatum.getEllipsoid())){if(this.parameters.equals(aHorizDatum.parameters)){return true;}}return false;}}HorizontalDatum.prototype=Datum;function Projection(name,classification,semiMinor,semiMajor,falseNorthing,falseEasting,centralMeridian,centralLatitude,scaleFactor){this.icsl304=Info;this.icsl304(name);this.classification=classification||"";this.falseNorthing=falseNorthing;this.falseEasting=falseEasting;this.centralMeridian=centralMeridian;this.centralLatitude=centralLatitude;this.semiMinor=semiMinor;this.semiMajor=semiMajor;this.scaleFactor=scaleFactor;this.getFalseNorthing=getFalseNorthing;this.getFalseEasting=getFalseEasting;this.getCentralMeridian=getCentralMeridian;this.getCentralLatitude=getCentralLatitude;this.getSemiMinor=getSemiMinor;this.getSemiMajor=getSemiMajor;this.getScaleFactor=getScaleFactor;this.getClass=getClass;function getFalseNorthing(){return this.falseNorthing;}function getFalseEasting(){return this.falseEasting;}function getCentralMeridian(){return this.centralMeridian;}function getCentralLatitude(){return this.centralLatitude;}function getSemiMinor(){return this.semiMinor;}function getSemiMajor(){return this.semiMajor;}function getScaleFactor(){return this.scaleFactor;}function getClass(){return this.classification;}}Projection.prototype=Info;function Point2D_Double(x,y){this.x=x||0;this.y=y||0;this.getX=getX;this.getY=getY;this.setLocation=setLocation;function getX(){return this.x;}function getY(){return this.y;}function setLocation(newX,newY){this.x=newX;this.y=newY;}}function CoordinatePoint(dim){this.ord=new Array(dim);this.getOrd=getOrd;this.setLocation=setLocation;function getOrd(){return this.getOrd;}function setLocation(x,y){this.ord[0]=x;this.ord[1]=y;}}function MapProjection(projection){this.semiMajor=projection.getSemiMajor();this.semiMinor=projection.getSemiMinor();this.centralMeridian=degrees2radians(projection.getCentralMeridian());this.centralLatitude=degrees2radians(projection.getCentralLatitude());this.scaleFactor=projection.getScaleFactor();this.falseEasting=projection.getFalseEasting();this.falseNorthing=projection.getFalseNorthing();this.isSpherical=(this.semiMajor==this.semiMinor);this.es=1.0-(this.semiMinor*this.semiMinor)/(this.semiMajor*this.semiMajor);this.e=Math.sqrt(this.es);this.MAX_ERROR=1;this.EPS=1.0E-6;this.TOL=1E-10;this.transform=transform;this.inverseTransform=inverseTransform;this.transform2ptos=transform2ptos;this.inverseTransform2ptos=inverseTransform2ptos;function transform(src,srcOffset,dest,dstOffset,numPts){reverse=(src==dest&&srcOffset<dstOffset&&srcOffset+(numPts<<1)>dstOffset);if(reverse){srcOffset+=2*numPts;dstOffset+=2*numPts;}point=new Point2D_Double();firstException=null;while(--numPts>=0){point.x=src[srcOffset++];point.y=src[srcOffset++];this.transform2ptos(point,point);dest[dstOffset++]=point.x;dest[dstOffset++]=point.y;if(reverse){srcOffset-=4;dstOffset-=4;}}if(firstException!=null){throw firstException;}}function inverseTransform(src,srcOffset,dest,dstOffset,numPts){reverse=(src==dest&&srcOffset<dstOffset&&srcOffset+(numPts<<1)>dstOffset);if(reverse){srcOffset+=2*numPts;dstOffset+=2*numPts;}point=new Point2D_Double();firstException=null;while(--numPts>=0){point.x=src[srcOffset++];point.y=src[srcOffset++];this.inverseTransform2ptos(point,point);dest[dstOffset++]=point.x;dest[dstOffset++]=point.y;if(reverse){srcOffset-=4;dstOffset-=4;}}if(firstException!=null){throw firstException;}}function transform2ptos(ptSrc,ptDst){x=ptSrc.getX();y=ptSrc.getY();ptDst=this.transformUTM(degrees2radians(x),degrees2radians(y),ptDst);return ptDst;}function inverseTransform2ptos(ptSrc,ptDst){x0=ptSrc.getX();y0=ptDst.getY();ptDst=this.inverseTransformUTM(x0,y0,ptDst);x=radians2degrees(ptDst.getX());y=radians2degrees(ptDst.getY());ptDst.setLocation(x,y);return ptDst;}}function MapProjection_inverse(projection){this.icsl304=MapProjection;this.icsl304(projection);this.transform_inverse=transform_inverse;function transform_inverse(source,srcOffset,dest,dstOffset,length){this.inverseTransform(source,srcOffset,dest,dstOffset,length);}}MapProjection_inverse.prototype=MapProjection;function TransverseMercatorProjection(projection){this.icsl304=MapProjection_inverse;this.icsl304(projection);FC1=1.00000000000000000000000,FC2=0.50000000000000000000000,FC3=0.16666666666666666666666,FC4=0.08333333333333333333333,FC5=0.05000000000000000000000,FC6=0.03333333333333333333333,FC7=0.02380952380952380952380,FC8=0.01785714285714285714285;C00=1.0,C02=0.25,C04=0.046875,C06=0.01953125,C08=0.01068115234375,C22=0.75,C44=0.46875,C46=0.01302083333333333333,C48=0.00712076822916666666,C66=0.36458333333333333333,C68=0.00569661458333333333,C88=0.3076171875;EPS10=1e-10,EPS11=1e-11;this.ak0=this.semiMajor*this.scaleFactor;this.esp=(this.semiMajor*this.semiMajor)/(this.semiMinor*this.semiMinor)-1.0;this.en0=C00-this.es*(C02+this.es*(C04+this.es*(C06+this.es*C08)));this.en1=this.es*(C22-this.es*(C04+this.es*(C06+this.es*C08)));this.en2=(t=this.es*this.es)*(C44-this.es*(C46+this.es*C48));this.en3=(t*=this.es)*(C66-this.es*C68);this.en4=t*this.es*C88;this.getZone=getZone;this.mlfn=mlfn;this.transformUTM=transformUTM;this.inverseTransformUTM=inverseTransformUTM;function getZone(centralLongitudeZone1,zoneWidth){alert("TransverseMercatorProjection::getZone: comprobar que la funcionalidad es correcta");zoneCount=Math.abs(360/zoneWidth);t=centralLongitudeZone1-0.5*zoneWidth;t=radians2degrees(centralMeridian)-t;t=Math.floor(t/zoneWidth+this.EPS);t-=zoneCount*Math.floor(t/zoneCount);t_int=Math.floor(t);return(t_int)+1;}function mlfn(phi,sphi,cphi){cphi*=sphi;sphi*=sphi;return this.en0*phi-cphi*(this.en1+sphi*(this.en2+sphi*(this.en3+sphi*(this.en4))));}function transformUTM(x,y,ptDst){if(Math.abs(y)>(Math.PI/2-this.EPS)){alert("ERROR: TransverseMercatorProjection::transform ERROR_POLE_PROJECTION");}y-=this.centralLatitude;x-=this.centralMeridian;sinphi=Math.sin(y);cosphi=Math.cos(y);if(this.isSpherical){b=cosphi*Math.sin(x);if(Math.abs(Math.abs(b)-1.0)<=EPS10){alert("ERROR: TransverseMercatorProjection::transform ERROR_VALUE_TEND_TOWARD_INFINITY");}icsl295=cosphi*Math.cos(x)/Math.sqrt(1.0-b*b);x=0.5*this.ak0*Math.log((1.0+b)/(1.0-b));if((b=Math.abs(icsl295))>=1.0){if((b-1.0)>EPS10){alert("ERROR: TransverseMercatorProjection::transform ERROR_VALUE_TEND_TOWARD_INFINITY 2");}else{icsl295=0.0;}}else{icsl295=Math.acos(icsl295);}if(y<0){icsl295=-icsl295;}y=this.ak0*icsl295;}else{t=Math.abs(cosphi)>EPS10?sinphi/cosphi:0;t*=t;al=cosphi*x;als=al*al;al/=Math.sqrt(1.0-this.es*sinphi*sinphi);n=this.esp*cosphi*cosphi;y=this.ak0*(this.mlfn(y,sinphi,cosphi)+sinphi*al*x*FC2*(1.0+FC4*als*(5.0-t+n*(9.0+4.0*n)+FC6*als*(61.0+t*(t-58.0)+n*(270.0-330.0*t)+FC8*als*(1385.0+t*(t*(543.0-t)-3111.0))))));x=this.ak0*al*(FC1+FC3*als*(1.0-t+n+FC5*als*(5.0+t*(t-18.0)+n*(14.0-58.0*t)+FC7*als*(61.0+t*(t*(179.0-t)-479.0)))));}x+=this.falseEasting;y+=this.falseNorthing;if(ptDst!=null){ptDst.setLocation(x,y);return ptDst;}else{return new Point2D_Double(x,y);}}function inverseTransformUTM(x,y,ptDst){x-=this.falseEasting;y-=this.falseNorthing;if(this.isSpherical){t=Math.exp(x/this.ak0);d=0.5*(t-1/t);t=Math.cos(y/this.ak0);phi=Math.asin(Math.sqrt((1.0-t*t)/(1.0+d*d)));y=y<0.0?-phi:phi;x=(Math.abs(d)<=EPS10&&Math.abs(t)<=EPS10)?this.centralMeridian:Math.atan2(d,t)+this.centralMeridian;}else{y_ak0=y/this.ak0;k=1.0-this.es;phi=y_ak0;for(i=10;true;){if(--i<0){alert("ERROR: TransverseMercatorProjection::inverseTransform ERROR_NO_CONVERGENCE");}s=Math.sin(phi);t=1.0-this.es*(s*s);t=(this.mlfn(phi,s,Math.cos(phi))-y_ak0)/(k*t*Math.sqrt(t));phi-=t;if(Math.abs(t)<EPS11){break;}}if(Math.abs(phi)>=(Math.PI/2)){y=y<0.0?-(Math.PI/2):(Math.PI/2);x=this.centralMeridian;}else{sinphi=Math.sin(phi);cosphi=Math.cos(phi);t=Math.abs(cosphi)>EPS10?sinphi/cosphi:0.0;n=this.esp*cosphi*cosphi;con=1.0-this.es*sinphi*sinphi;d=x*Math.sqrt(con)/this.ak0;con*=t;t*=t;ds=d*d;y=phi-(con*ds/(1.0-this.es))*FC2*(1.0-ds*FC4*(5.0+t*(3.0-9.0*n)+n*(1.0-4*n)-ds*FC6*(61.0+t*(90.0-252.0*n+45.0*t)+46.0*n-ds*FC8*(1385.0+t*(3633.0+t*(4095.0+1574.0*t))))));x=d*(FC1-ds*FC3*(1.0+2.0*t+n-ds*FC5*(5.0+t*(28.0+24*t+8.0*n)+6.0*n-ds*FC7*(61.0+t*(662.0+t*(1320.0+720.0*t))))))/cosphi+this.centralMeridian;}}y+=this.centralLatitude;if(ptDst!=null){ptDst.setLocation(x,y);return ptDst;}else{return new Point2D_Double(x,y);}}}TransverseMercatorProjection.prototype=MapProjection_inverse;function MatrixTransform(numCol,numRow,elt){this.numCol=numCol||0;this.numRow=numRow||0;this.elt=elt||new Array();this.transformMatrix=transformMatrix;function transformMatrix(srcPts,srcOff,dstPts,dstOff,numPts){srcOffB=srcOff;dstOffB=dstOff;numPtsB=numPts;inputDimension=this.numCol-1;outputDimension=this.numRow-1;buffer=new Array();if(srcPts==dstPts){upperSrc=srcOffB+numPtsB*inputDimension;if(upperSrc>dstOffB){if(inputDimension>=outputDimension?dstOffB>srcOffB:dstOffB+numPtsB*outputDimension>upperSrc){srcPts=new Array();ii=0;for(kk=srcOffB;kk<=(srcPts.length+srcOffB);kk++){srcPts[ii]=dstPts[kk];ii++;}srcOffB=0;}}}while(--numPtsB>=0){mix=0;for(var j=0;j<this.numRow;j++){sum=this.elt[mix+inputDimension];for(var i=0;i<inputDimension;i++){sum+=srcPts[srcOffB+i]*this.elt[mix++];}buffer[j]=sum;mix++;}w=buffer[outputDimension];for(var j=0;j<outputDimension;j++){dstPts[dstOffB++]=buffer[j]/w;}srcOffB+=inputDimension;}}}function GeocentricTransform(ellipsoid){semiMajor=ellipsoid.getSemiMajorAxis();semiMinor=ellipsoid.getSemiMinorAxis();this.MAX_ERROR=0.01;this.COS_67P5=0.38268343236508977;this.AD_C=1.0026000;this.a=semiMajor;this.b=semiMinor;this.a2=(this.a*this.a);this.b2=(this.b*this.b);this.e2=(this.a2-this.b2)/this.a2;this.ep2=(this.a2-this.b2)/this.b2;this.hasHeight=false;this.getDimSource=getDimSource;this.transformGeocentric=transformGeocentric;this.transformGeocentric_inverse=transformGeocentric_inverse;function getDimSource(){return 2;}function transformGeocentric(srcPts,srcOff,dstPts,dstOff,numPts,hasHeight){numPtsB=numPts;step=0;dimSource=this.getDimSource();this.hasHeight|=(dimSource>=3);error=null;while(--numPtsB>=0){L=degrees2radians(srcPts[srcOff++]);P=degrees2radians(srcPts[srcOff++]);h=hasHeight?srcPts[srcOff++]:0;cosLat=Math.cos(P);sinLat=Math.sin(P);rn=this.a/Math.sqrt(1-this.e2*(sinLat*sinLat));dstPts[dstOff++]=(rn+h)*cosLat*Math.cos(L);dstPts[dstOff++]=(rn+h)*cosLat*Math.sin(L);dstPts[dstOff++]=(rn*(1-this.e2)+h)*sinLat;srcOff+=step;dstOff+=step;}}function transformGeocentric_inverse(srcPts,srcOff,dstPts,dstOff,numPts){numPtsB=numPts;step=0;dimSource=this.getDimSource();hasHeight=(dimSource>=3);computeHeight=hasHeight;while(--numPtsB>=0){x=srcPts[srcOff++];y=srcPts[srcOff++];z=srcPts[srcOff++];W2=x*x+y*y;W=Math.sqrt(W2);T0=z*this.AD_C;S0=Math.sqrt(T0*T0+W2);sin_B0=T0/S0;cos_B0=W/S0;sin3_B0=sin_B0*sin_B0*sin_B0;T1=z+this.b*this.ep2*sin3_B0;sum=W-this.a*this.e2*(cos_B0*cos_B0*cos_B0);S1=Math.sqrt(T1*T1+sum*sum);sin_p1=T1/S1;cos_p1=sum/S1;longitude=radians2degrees(Math.atan2(y,x));latitude=radians2degrees(Math.atan(sin_p1/cos_p1));dstPts[dstOff++]=longitude;dstPts[dstOff++]=latitude;if(computeHeight){rn=this.a/Math.sqrt(1-this.e2*(sin_p1*sin_p1));if(cos_p1>=this.COS_67P5)height=W/+cos_p1-rn;else if(cos_p1<=(-1*this.COS_67P5))height=W/-cos_p1-rn;else height=z/sin_p1+rn*(this.e2-1.0);if(this.hasHeight){dstPts[dstOff++]=height;}}srcOff+=step;dstOff+=step;}}}function startsWith(cadOrigen,cadStart){if(cadOrigen.length>=cadStart.length){var cad=cadOrigen.substring(0,cadStart.length);if(cad==cadStart){return true;}else{return false;}}else{return false;}}function getZona(srs){if(startsWith(srs,'EPSG:230')){var zona=parseInt(srs.substring(new String('EPSG:230').length,srs.length));return zona;}if(startsWith(srs,'EPSG:258')){var zona=parseInt(srs.substring(new String('EPSG:258').length,srs.length));return zona;}}zona30=30;centralMeridian30=-183.0+(zona30*6.0);zona31=31;centralMeridian31=-183.0+(zona31*6.0);centralLatitude=0;falseNorthing=0.0;falseEasting=500000;scaleFactor=0.9996;ed50Awgs84=new WGS84ConversionInfo();ed50Awgs84.dx=-84.0;ed50Awgs84.dy=-107.0;ed50Awgs84.dz=-120.0;horizDatum=new HorizontalDatum("European Datum 50",new DatumType_classic(),new Ellipsoid_FlattenedSphere("International 1924",6378388.0,297.0,new Unit_metre()),ed50Awgs84);ed50=horizDatum.getEllipsoid();horizDatum2=new HorizontalDatum("European Terrestrial Reference System",new DatumType_classic(),new Ellipsoid_FlattenedSphere("GRS 1980",6378137.0,298.257222,new Unit_metre()),new WGS84ConversionInfo());ellipsoidETRS89=horizDatum2.getEllipsoid();projectionZone30_etrs89=new Projection("ETRS89 / UTM Norte","Transverse_Mercator",ellipsoidETRS89.getSemiMinorAxis(),ellipsoidETRS89.getSemiMajorAxis(),falseNorthing,falseEasting,centralMeridian30,centralLatitude,scaleFactor);projectionZone31_etrs89=new Projection("ETRS89 / UTM Norte","Transverse_Mercator",ellipsoidETRS89.getSemiMinorAxis(),ellipsoidETRS89.getSemiMajorAxis(),falseNorthing,falseEasting,centralMeridian31,centralLatitude,scaleFactor);projectionZone30_ed50=new Projection("ED50 / UTM Norte","Transverse_Mercator",ed50.getSemiMinorAxis(),ed50.getSemiMajorAxis(),falseNorthing,falseEasting,centralMeridian30,centralLatitude,scaleFactor);projectionZone31_ed50=new Projection("ED50 / UTM Norte","Transverse_Mercator",ed50.getSemiMinorAxis(),ed50.getSemiMajorAxis(),falseNorthing,falseEasting,centralMeridian31,centralLatitude,scaleFactor);etrs89_TMProj30=new TransverseMercatorProjection(projectionZone30_etrs89);etrs89_TMProj31=new TransverseMercatorProjection(projectionZone31_etrs89);ed50_TMProj30=new TransverseMercatorProjection(projectionZone30_ed50);ed50_TMProj31=new TransverseMercatorProjection(projectionZone31_ed50);matrixTr_positive=[1.0,0.0,0.0,84.0,0.0,1.0,0.0,107.0,0.0,0.0,1.0,120.0,0.0,0.0,0.0,1.0];matrixTr_negative=[1.0,0.0,0.0,-84.0,0.0,1.0,0.0,-107.0,0.0,0.0,1.0,-120.0,0.0,0.0,0.0,1.0];mt_positive=new MatrixTransform(4,4,matrixTr_positive);mt_negative=new MatrixTransform(4,4,matrixTr_negative);gt_ed50=new GeocentricTransform(ed50);gt_etrs89=new GeocentricTransform(ellipsoidETRS89);gt_wgs84=new GeocentricTransform(new Ellipsoid_WGS84());function getUTM_ETRS89_zone(zona){switch(zona){case 28:{return etrs89_TMProj28;}break;case 29:{return etrs89_TMProj29;}break;case 30:{return etrs89_TMProj30;}break;case 31:{return etrs89_TMProj31;}break;case 32:{return etrs89_TMProj32;}break;case 33:{return etrs89_TMProj33;}break;case 34:{return etrs89_TMProj34;}break;case 35:{return etrs89_TMProj35;}break;case 36:{return etrs89_TMProj36;}break;case 37:{return etrs89_TMProj37;}break;case 38:{return etrs89_TMProj38;}break;default:{alert("Zona "+zona+" no disponible en UTM con ETRS89");return etrs89_TMProj30;}}}function getUTM_ED50_zone(zona){switch(zona){case 28:{return ed50_TMProj28;}break;case 29:{return ed50_TMProj29;}break;case 30:{return ed50_TMProj30;}break;case 31:{return ed50_TMProj31;}break;case 32:{return ed50_TMProj32;}break;case 33:{return ed50_TMProj33;}break;case 34:{return ed50_TMProj34;}break;case 35:{return ed50_TMProj35;}break;case 36:{return ed50_TMProj36;}break;case 37:{return ed50_TMProj37;}break;case 38:{return ed50_TMProj38;}break;default:{alert("Zona "+zona+" no disponible en UTM con ED50");return ed50_TMProj30;}}}function transform230XX_230XX(x,y,zonaOrig,zonaDest){srcPts=new Array();srcPts[0]=x;srcPts[1]=y;dstPtsInv2=[0.0,0.0];getUTM_ED50_zone(zonaOrig).transform_inverse(srcPts,0,dstPtsInv2,0,1);dstPts44=[0.0,0.0];getUTM_ED50_zone(zonaDest).transform(dstPtsInv2,0,dstPts44,0,1);return dstPts44;}function transform258XX_258XX(x,y,zonaOrig,zonaDest){srcPts=new Array();srcPts[0]=x;srcPts[1]=y;dstPtsInv2=[0.0,0.0];getUTM_ETRS89_zone(zonaOrig).transform_inverse(srcPts,0,dstPtsInv2,0,1);dstPts44=[0.0,0.0];getUTM_ETRS89_zone(zonaDest).transform(dstPtsInv2,0,dstPts44,0,1);return dstPts44;}function transform4326_258XX(x,y,zonaDest){srcPts=new Array();srcPts[0]=x;srcPts[1]=y;dstPts=[0.0,0.0,0.0];gt_wgs84.transformGeocentric(srcPts,0,dstPts,0,1,false);dstPts33=[0.0,0.0];gt_etrs89.transformGeocentric_inverse(dstPts,0,dstPts33,0,1,false);dstPtsInv2=[0.0,0.0];getUTM_ETRS89_zone(zonaDest).transform(dstPts33,0,dstPtsInv2,0,1);return dstPtsInv2;}function transform258XX_4326(x,y,zonaOrig){srcPts=new Array();srcPts[0]=x;srcPts[1]=y;dstPtsInv2=[0.0,0.0];getUTM_ETRS89_zone(zonaOrig).transform_inverse(srcPts,0,dstPtsInv2,0,1);dstPts=[0.0,0.0,0.0];gt_etrs89.transformGeocentric(dstPtsInv2,0,dstPts,0,1,false);dstPts33=[0.0,0.0];gt_wgs84.transformGeocentric_inverse(dstPts,0,dstPts33,0,1,false);return dstPts33;}function transform230XX_258XX(x,y,zonaOrig,zonaDest){srcPts=new Array();srcPts[0]=x;srcPts[1]=y;dstPtsInv2=[0.0,0.0];getUTM_ED50_zone(zonaOrig).transform_inverse(srcPts,0,dstPtsInv2,0,1);dstPts=[0.0,0.0,0.0];gt_ed50.transformGeocentric(dstPtsInv2,0,dstPts,0,1,false);srcPts22=[0.0,0.0,0.0];mt_negative.transformMatrix(dstPts,0,srcPts22,0,1);dstPts33=[0.0,0.0];gt_etrs89.transformGeocentric_inverse(srcPts22,0,dstPts33,0,1,false);dstPts44=[0.0,0.0];getUTM_ETRS89_zone(zonaDest).transform(dstPts33,0,dstPts44,0,1);return dstPts44;}function transform258XX_230XX(x,y,zonaOrig,zonaDest){srcPts=new Array();srcPts[0]=x;srcPts[1]=y;dstPtsInv2=[0.0,0.0];getUTM_ETRS89_zone(zonaOrig).transform_inverse(srcPts,0,dstPtsInv2,0,1);dstPts=[0.0,0.0,0.0];gt_etrs89.transformGeocentric(dstPtsInv2,0,dstPts,0,1,false);srcPts22=[0.0,0.0,0.0];mt_positive.transformMatrix(dstPts,0,srcPts22,0,1);dstPts33=[0.0,0.0];gt_ed50.transformGeocentric_inverse(srcPts22,0,dstPts33,0,1,false);dstPts44=[0.0,0.0];getUTM_ED50_zone(zonaDest).transform(dstPts33,0,dstPts44,0,1);return dstPts44;}function transform230XX_4326(x,y,zonaOrig){srcPts=new Array();srcPts[0]=x;srcPts[1]=y;dstPtsInv2=[0.0,0.0];getUTM_ED50_zone(zonaOrig).transform_inverse(srcPts,0,dstPtsInv2,0,1);dstPts=[0.0,0.0,0.0];gt_ed50.transformGeocentric(dstPtsInv2,0,dstPts,0,1,false);srcPts22=[0.0,0.0,0.0];mt_negative.transformMatrix(dstPts,0,srcPts22,0,1);dstPts33=[0.0,0.0];gt_wgs84.transformGeocentric_inverse(srcPts22,0,dstPts33,0,1,false);return dstPts33;}function transform4326_230XX(x,y,zonaDest){srcPts=new Array();srcPts[0]=x;srcPts[1]=y;dstPts=[0.0,0.0,0.0];gt_wgs84.transformGeocentric(srcPts,0,dstPts,0,1,false);srcPts22=[0.0,0.0,0.0];mt_positive.transformMatrix(dstPts,0,srcPts22,0,1);dstPtsInv=[0.0,0.0];gt_ed50.transformGeocentric_inverse(srcPts22,0,dstPtsInv,0,1,false);dstPtsInv2=[0.0,0.0];getUTM_ED50_zone(zonaDest).transform(dstPtsInv,0,dstPtsInv2,0,1);return dstPtsInv2;}function coordTransform(srsOrigen,srsDestino,coordX,coordY){destino=new CoordinatePoint(2);if(srsOrigen==srsDestino){destino.ord[0]=coordX;destino.ord[1]=coordY;return destino;}else{if(srsOrigen=="EPSG:4326"){if(startsWith(srsDestino,'EPSG:230')){return transform4326_230XX(coordX,coordY,getZona(srsDestino));}else if(startsWith(srsDestino,'EPSG:258')){return transform4326_258XX(coordX,coordY,getZona(srsDestino));}else{alert("El srs "+srsDestino+" no está disponible");}}else if(startsWith(srsOrigen,'EPSG:230')){if(srsDestino=="EPSG:4326"){return transform230XX_4326(coordX,coordY,getZona(srsOrigen));}else if(startsWith(srsDestino,'EPSG:230')){return transform230XX_230XX(coordX,coordY,getZona(srsOrigen),getZona(srsDestino));}else if(startsWith(srsDestino,'EPSG:258')){return transform230XX_258XX(coordX,coordY,getZona(srsOrigen),getZona(srsDestino));}else{alert("El srs "+srsDestino+" no está disponible");}}else if(startsWith(srsOrigen,'EPSG:258')){if(srsDestino=="EPSG:4326"){return transform258XX_4326(coordX,coordY,getZona(srsOrigen));}else if(startsWith(srsDestino,'EPSG:230')){return transform258XX_230XX(coordX,coordY,getZona(srsOrigen),getZona(srsDestino));}else if(startsWith(srsDestino,'EPSG:258')){return transform258XX_258XX(coordX,coordY,getZona(srsOrigen),getZona(srsDestino));}else{alert("El srs "+srsDestino+" no está disponible");}}else{alert("El srs "+srsOrigen+" no está disponible");}}}var LayerName=new Array();var LayerID=new Array();var LayerVisible=new Array();var LayerType=new Array();var LayerTypeById=new Array();var ActiveLayerIndex=0;var ActiveLayer;var layerCount;function getLayers(theReply){var theReplyUC=theReply.toUpperCase();var startpos=0;var endpos=0;var pos=-1;var lpos=1;var epos=1;var zpos=1;var zpos2=1;var tempString="";var visString="";var typeString="";var fieldString="";var testString="";var testString2="";var minString="";var maxString="";var dQuote='"';getInitialVisibilityLayers();layerCount=0;LayerName.length=1;LayerVisible.length=1;LayerID.length=1;LayerType.length=1;lpos=theReplyUC.indexOf("<LAYERINFO",zpos);while(lpos>-1){if(lpos!=-1){zpos=theReplyUC.indexOf("</LAYERINFO",lpos);if(zpos==-1){zpos=theReplyUC.indexOf("/>",lpos);}
if(zpos!=-1){pos=theReplyUC.indexOf("NAME=",lpos);if(pos!=-1){startpos=pos+6;endpos=theReply.indexOf(dQuote,startpos);tempString=theReply.substring(startpos,endpos);tempString=tempString.replace(/&apos;/g,"'");LayerName[layerCount]=tempString;startpos=theReplyUC.indexOf("VISIBLE=",lpos);if(startpos!=-1){startpos=startpos+9;endpos=startpos+4;visString=theReply.substring(startpos,endpos);}
startpos=theReplyUC.indexOf("ID=",lpos);if((startpos!=-1)&&(startpos<zpos)){startpos=startpos+4;endpos=theReply.indexOf(dQuote,startpos);tempString=theReply.substring(startpos,endpos);tempString=tempString.replace(/&apos;/g,"'");LayerID[layerCount]=tempString;}else{LayerID[layerCount]=LayerName[layerCount];}
if(visString=="true"){LayerVisible[layerCount]=1;}else{LayerVisible[layerCount]=0;}
if(isIncluded(initialVisibleLayers,LayerID[layerCount],initialVisibleLayers.length)){LayerVisible[layerCount]=1;}
if(isIncluded(initialHiddenLayers,LayerID[layerCount],initialHiddenLayers.length)){LayerVisible[layerCount]=0;}
acetatepos=theReplyUC.indexOf("TYPE=\"acetate\"",lpos);if(acetatepos==-1){LayerType[layerCount]="poly";LayerTypeById[LayerID[layerCount]]="poly";startpos=theReplyUC.indexOf("<FCLASS TYPE=",lpos);if(startpos!=-1){startpos=startpos+14;endpos=startpos+4;theLayerType=theReply.substring(startpos,endpos);LayerType[layerCount]=theLayerType;LayerTypeById[LayerID[layerCount].toString().toUpperCase()]=theLayerType;}}else{LayerType[layerCount]="acetate";LayerTypeById[LayerID[layerCount]]="acetate";}
layerCount+=1;endpos=zpos;lpos=theReplyUC.indexOf("<LAYERINFO",zpos);}else{lpos=-1;}}else{lpos=theReplyUC.indexOf("<LAYERINFO",lpos+10);}}}
LayerName.reverse();LayerVisible.reverse();LayerID.reverse();LayerType.reverse();ActiveLayer=LayerID[ActiveLayerIndex];if(customMapService){createNewCustomToc();}
for(var i=0;i<initialVisibleLayers.length;i++){var idxx=wmsIdxList[initialVisibleLayers[i]];if(idxx){wmsList[idxx]["visib"]=true;}}
for(var i=0;i<initialHiddenLayers.length;i++){var idxx=wmsIdxList[initialHiddenLayers[i]];if(idxx){wmsList[idxx]["visib"]=false;}}
if(hasToc){displayToc();}
return false;}
function createNewCustomToc(){toc=new TOCNR('','',false,'');for(var i=0;i<layerCount;i++){toc.addLayer(new LAYER(LayerName[i],null,''));}}
function getIdxFromIdLayer(theID){for(var i=0;i<layerCount;i++){if(LayerID[i]==theID){return i;}}
return-1;}
fullLeft=null;fullBottom=null;fullRight=null;fullTop=null;function boundingBox(x1,y1,x2,y2){this.minx=x1;this.maxx=x2;this.miny=y1;this.maxy=y2;}
function getFullMap(){getMap(fullLeft,fullBottom,fullRight,fullTop,false);}
xmin_old="";xmax_old="";ymin_old="";ymax_old="";function backupExtent(){xmin_old=minx;xmax_old=maxx;ymin_old=miny;ymax_old=maxy;}
function restoreExtent(){minx=xmin_old;maxx=xmax_old;miny=ymin_old;maxy=ymax_old;}
function fixedZoomIn(pxX,pxY,numVeces){backupExtent();var newPoint=getMapXY(pxX,pxY);growEnvelope(Math.pow(3/4,numVeces),newPoint[0],newPoint[1]);getMap(minx,miny,maxx,maxy,false);}
function fixedZoomOut(pxX,pxY,numVeces){backupExtent();var newPoint=getMapXY(pxX,pxY);growEnvelope(Math.pow(4/3,numVeces),newPoint[0],newPoint[1]);getMap(minx,miny,maxx,maxy,false);}
function zoom(left,bottom,right,topp){backupExtent();if(activeTool=="zoomIn"){getExtentForZoomIn(left,bottom,right,topp);}else{getExtentForZoomOut(left,bottom,right,topp);}
getMap(minx,miny,maxx,maxy,false);}
function pan(ix,iy){backupExtent();var dx=(maxx-minx)/mwidth;var mx=dx*ix;var my=dx*iy;minx+=mx;maxx+=mx;miny+=my;maxy+=my;getMap(minx,miny,maxx,maxy,true);}
function panDirection(dir){backupExtent();shift(dir);getMap(minx,miny,maxx,maxy,true);}
function shift(dir){backupExtent();var dx=maxx-minx;var dy=maxy-miny;switch(dir){case"north":miny+=0.3*dy;maxy+=0.3*dy;break;case"south":miny-=0.3*dy;maxy-=0.3*dy;break;case"east":minx+=0.3*dx;maxx+=0.3*dx;break;case"west":minx-=0.3*dx;maxx-=0.3*dx;break;case"ne":miny+=0.3*dy;maxy+=0.3*dy;minx+=0.3*dx;maxx+=0.3*dx;break;case"nw":miny+=0.3*dy;maxy+=0.3*dy;minx-=0.3*dx;maxx-=0.3*dx;break;case"se":miny-=0.3*dy;maxy-=0.3*dy;minx+=0.3*dx;maxx+=0.3*dx;break;case"sw":miny-=0.3*dy;maxy-=0.3*dy;minx-=0.3*dx;maxx-=0.3*dx;break;}}
function getExtentForZoomIn(left,bottom,right,topp){var LLPoint=getMapXY(left,bottom);var URPoint=getMapXY(right,topp);minx=LLPoint[0];miny=LLPoint[1];maxx=URPoint[0];maxy=URPoint[1];}
function getExtentForZoomOut(left,bottom,right,topp){var xDiff=maxx-minx;var yDiff=maxy-miny;var pwidth=right-left;var pheight=topp-bottom;var xRatio=mwidth/pwidth;var yRatio=mheight/pheight;var xAdd=xRatio*xDiff/2;var yAdd=yRatio*yDiff/2;minx=minx-xAdd;maxx=maxx+xAdd;miny=miny-yAdd;maxy=maxy+yAdd;}
function getMapXY(xIn,yIn){var newValues=new Array();var mouseX=xIn;var pixelX=(maxx-minx)/mwidth;var newX=pixelX*mouseX+minx;var mouseY=mheight-yIn;var pixelY=(maxy-miny)/mheight;var newY=(pixelY*mouseY)+miny;newValues[0]=newX;newValues[1]=newY;return newValues;}
function growEnvelope(value,cx,cy){var dx=maxx-minx;var dy=maxy-miny;var dx1=0.5*value*dx;var dy1=0.5*value*dy;minx=cx-dx1;miny=cy-dy1;maxx=cx+dx1;maxy=cy+dy1;}
function getMapWithCurrentExtent(){getMap(minx,miny,maxx,maxy,true);}
function contains(x,y,_minx,_miny,_maxx,_maxy){return(x>=_minx&&y>=_miny&&x<_maxx&&y<_maxy);}
function checkMaxScale(_minx,_maxx,_mwidth){if(getMapScale2(false,_minx,_maxx,_mwidth)>maxScaleAllowed){return false;}
return true;}
function checkMaxBbox(_minx,_miny,_maxx,_maxy){if(_minx>limitRight){return false;}
if(_maxx<limitLeft){return false;}
if(_miny>limitTop){return false;}
if(_maxy<limitBottom){return false;}
return true;}
function checkDeformation(_minx,_miny,_maxx,_maxy,mwidth,mheight){var newBBOX=new boundingBox(_minx,_miny,_maxx,_maxy);var ratioTamano=mwidth/mheight;var diffX=_maxx-_minx;var diffY=_maxy-_miny;var ratioCoord=diffX/diffY;if(ratioCoord>ratioTamano){var newDiffY=diffX/ratioTamano;var gapY=newDiffY-diffY;if(gapY>0){newBBOX.miny=_miny-(gapY/2);newBBOX.maxy=_maxy+(gapY/2);}else{newBBOX.maxy=_miny-(gapY/2);newBBOX.miny=_maxy+(gapY/2);}}else if(ratioCoord<ratioTamano){var newDiffX=ratioTamano*diffY;var gapX=newDiffX-diffX;if(gapX>0){newBBOX.minx=_minx-(gapX/2);newBBOX.maxx=_maxx+(gapX/2);}else{newBBOX.maxx=_minx-(gapX/2);newBBOX.minx=_maxx+(gapX/2);}}
return newBBOX;}
function doZoomScale(newScale){var tempFactor=96;var inchPerMeter=39.4;distanceInches=(newScale)/tempFactor;distanceOnePixel=distanceInches/inchPerMeter;xDistance=distanceOnePixel*mwidth;yDistance=distanceOnePixel*mheight;xMidPoint=minx+((maxx-minx)/2);yMidPoint=maxy-((maxy-miny)/2);newLeft=xMidPoint-(xDistance/2);newRight=xMidPoint+(xDistance/2);newTop=yMidPoint+(yDistance/2);newBottom=yMidPoint-(yDistance/2);getMap(newLeft,newBottom,newRight,newTop,true);}
var theHiddenURL="";var theHiddenURLGeneralAragon="";if(!isIE){Document.prototype.loadXML=function(s){var doc2=(new DOMParser()).parseFromString(s,"text/xml");while(this.hasChildNodes()){this.removeChild(this.lastChild);}
for(var i=0;i<doc2.childNodes.length;i++){this.appendChild(this.importNode(doc2.childNodes[i],true));}};}
function clearMap(){document.getElementById('theImage').style.display="none";document.getElementById('theAcetateEscala').style.display="none";document.getElementById('theAcetateMarca').style.display="none";jg.clear();limpiarEdicion();limpiarHistorico();limpiarBufferCirculo();limpiarBufferCirculoGranjas();}
function clearWMS(wmsIdx){document.getElementById(wmsList[wmsIdx]["id"]).style.display="none";}
function updateWMS(wmsIdx){if(!document.getElementById('bgFotoShowId').disabled){if(wmsIdx==idxWMSFondoFoto){if(wmsIdx!=0){return;}}}
wmsObj=wmsList[wmsIdx];urlWMS=wmsObj["url"]+'&WIDTH='+mwidth+'&HEIGHT='+mheight;urlWMS+='&BBOX='+minx+','+miny+','+maxx+','+maxy;document.getElementById(wmsObj["id"]).src=urlWMS;document.getElementById(wmsObj["id"]).style.zindex=wmsObj["zIdx"];loadingWMSId="wmsLoading"+wmsIdx;if(document.getElementById(loadingWMSId)){document.getElementById(loadingWMSId).style.visibility="visible";}}
function updateAcetateEscala(mustRefreshScale){http=getHTTPObject();if((http!=null)){var axlAcetate=getMapRequestAcetateEscala(minx,miny,maxx,maxy);if(mustRefreshScale){http.onreadystatechange=printResponseAcetateEscalaRefreshScale;}else{http.onreadystatechange=printResponseAcetateEscalaNoRefreshScale;}
http.open("POST",url,true);http.send(axlAcetate);}}
function updateAcetateMarca(theXMarca,theYMarca){http=getHTTPObject();if((http!=null)){var axlAcetate=getMapRequestAcetateMarca(minx,miny,maxx,maxy,theXMarca,theYMarca);http.onreadystatechange=printResponseAcetateMarca;http.open("POST",url,true);http.send(axlAcetate);}}
function getMap(_minx,_miny,_maxx,_maxy,avoidRefreshScale){minx=_minx;miny=_miny;maxx=_maxx;maxy=_maxy;http=getHTTPObject();if((http!=null)){var axl=getMapRequest(_minx,_miny,_maxx,_maxy);if(axl=="1"){getFullMap();}else if(axl=="2"){resetAfterPan();restoreExtent();}else{for(var ii=0;ii<wmsList["count"];ii++){clearWMS(ii);}
clearMap();http.open("POST",url,true);if(debugOn){alert("sending :"+axl);}
muestraLayerLoading();if(avoidRefreshScale){http.onreadystatechange=printResponseNoRefreshScale;}else{http.onreadystatechange=printResponseRefreshScale;}
http.send(axl);for(var ii=0;ii<wmsList["count"];ii++){if(wmsList[ii]["visib"]){updateWMS(ii);}}}}}
function getMapHidden(_minx,_miny,_maxx,_maxy,_mapSizeX,_mapSizeY,_theDPI,layerVisibilityList,tipoImagen){http=getHTTPObject();if((http!=null)){var axl=getMapRequestPrint(_minx,_miny,_maxx,_maxy,_mapSizeX,_mapSizeY,_theDPI,layerVisibilityList,tipoImagen);http.open("POST",url,true);http.onreadystatechange=eval("printResponseHidden"+tipoImagen);muestraLayerLoading();http.send(axl);}}
function getXMLDocResult(){isWorking=false;var result=http.responseText;if(debugOn){alert(result);}
var xmlDoc;if(document.implementation&&document.implementation.createDocument){xmlDoc=document.implementation.createDocument("","",null);xmlDoc.async="false";xmlDoc.loadXML(result);}else if(window.ActiveXObject){xmlDoc=new ActiveXObject("Microsoft.XMLDOM");xmlDoc.async="false";xmlDoc.loadXML(result);}
return xmlDoc;}
function correctPNG(imgMapaId,_theURL){var imgMapa=document.getElementById(imgMapaId);if(isIE6){imgMapa.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'"+_theURL+"\', sizingMethod='scale');";imgMapa.src=_theURL;}else{imgMapa.src=_theURL;}}
function printResponseRefreshScale(){printResponse(true,false);}
function printResponseNoRefreshScale(){printResponse(false,false);}
function printResponseHidden(){printResponse(false,true,"");}
function printResponseHiddenSituacion(){printResponse(false,true,"Situacion");}
function printResponseHiddenAragon(){printResponse(false,true,"Aragon");}
function printResponse(mustRefreshScale,isHidden,tipoImagen){if(http.readyState==4){if(http.status==200){var xmlDoc=getXMLDocResult();var theURL=xmlDoc.getElementsByTagName("OUTPUT").item(0).getAttribute("url");if(isHidden){if(tipoImagen=="Aragon"){eval("theHiddenURLGeneral"+tipoImagen+" = '"+theURL+"';");}else{theHiddenURL=theURL;}}else{correctPNG('theImage',theURL);setTimeout("muestraVisible('theImage')",400);var env=xmlDoc.getElementsByTagName("ENVELOPE").item(0);minx=parseFloat(env.getAttribute("minx"));miny=parseFloat(env.getAttribute("miny"));maxx=parseFloat(env.getAttribute("maxx"));maxy=parseFloat(env.getAttribute("maxy"));if(mustRefreshScale){newMapScale=getMapScale(false);setNewScale(newMapScale);}
rememberExtent(minx,miny,maxx,maxy,theURL);updateAcetateEscala(mustRefreshScale,isHidden);updateMarcaOverview();}}else{alert("Error retreiving data");}}}
function muestraVisible(theId){document.getElementById(theId).style.display="block";}
function printResponseAcetateEscalaRefreshScale(){printResponseAcetateEscala(true);}
function printResponseAcetateEscalaNoRefreshScale(){printResponseAcetateEscala(false);}
function printResponseAcetateEscala(mustRefreshScale){if(http.readyState==4){if(http.status==200){var xmlDoc=getXMLDocResult();var theURL=xmlDoc.getElementsByTagName("OUTPUT").item(0).getAttribute("url");correctPNG('theAcetateEscala',theURL);setTimeout("muestraVisible('theAcetateEscala')",200);if((findXCoordUsr!="")&&(findYCoordUsr!="")){updateAcetateMarca(findXCoordUsr,findYCoordUsr);}else{ocultaLayerLoading();}
afterMapRefresh(mustRefreshScale);}else{alert("Error retreiving data");}}}
function printResponseAcetateMarca(){if(http.readyState==4){if(http.status==200){var xmlDoc=getXMLDocResult();var theURL=xmlDoc.getElementsByTagName("OUTPUT").item(0).getAttribute("url");correctPNG('theAcetateMarca',theURL);setTimeout("muestraVisible('theAcetateMarca')",200);ocultaLayerLoading();}else{alert("Error retreiving data");}}}
minxArray=new Array();maxxArray=new Array();minyArray=new Array();maxyArray=new Array();theURLArray=new Array();scalesArray=new Array();idxArray=-1;function rememberExtent(_minx,_miny,_maxx,_maxy,_theURL){idxArray++;minxArray[idxArray]=_minx;maxxArray[idxArray]=_maxx;minyArray[idxArray]=_miny;maxyArray[idxArray]=_maxy;theURLArray[idxArray]=_theURL;scalesArray[idxArray]=document.getElementById('scaleTextBox').value;}
function previousExtent(){if(idxArray>0){idxArray--;minx=minxArray[idxArray];maxx=maxxArray[idxArray];miny=minyArray[idxArray];maxy=maxyArray[idxArray];correctPNG('theImage',theURLArray[idxArray]);setNewScale(scalesArray[idxArray]);updateMapClicks();for(var ii=0;ii<wmsList["count"];ii++){clearWMS(ii);}
for(var ii=0;ii<wmsList["count"];ii++){if(wmsList[ii]["visib"]){updateWMS(ii);}}}else{alert("No hay extent anterior");}}
function afterMapRefresh(mustRefreshScale){updateMapClicks();if(isGeoreferencing){updateGeorefMapClicks(jgPoint,pointRecordset,jgPointLabel);}
if(isHistorico){updateGeorefMapClicks(jgHistorico,historicoRecordset,jgHistoricoLabel);}
theHiddenURLGeneralAragon="";}
function getMapRequest(_minx,_miny,_maxx,_maxy,_mapSizeX,_mapSizeY,unitScaleBar,layerVisibility){if(_mapSizeX){if(!checkMaxScale(_minx,_maxx,_mapSizeX)){return"1";}}else{if(!checkMaxScale(_minx,_maxx,mwidth)){return"1";}}if(!checkMaxBbox(_minx,_miny,_maxx,_maxy)){return"2";}var newBbox;if(_mapSizeX&&_mapSizeY){newBbox=checkDeformation(_minx,_miny,_maxx,_maxy,_mapSizeX,_mapSizeY);}else{newBbox=checkDeformation(_minx,_miny,_maxx,_maxy,mwidth,mheight);}minx=newBbox.minx;maxx=newBbox.maxx;miny=newBbox.miny;maxy=newBbox.maxy;var axl=getCabeceraArcXML(minx,miny,maxx,maxy,_mapSizeX,_mapSizeY,false,layerVisibility);axl+=getArcXMLSelection();axl+=' </GET_IMAGE> </REQUEST></ARCXML>\n';return axl;}function getMapRequestPrint(_minx,_miny,_maxx,_maxy,_mapSizeX,_mapSizeY,_theDPI,layerVisibilityList,tipoImagen){var newBbox;if(_mapSizeX&&_mapSizeY){newBbox=checkDeformation(_minx,_miny,_maxx,_maxy,_mapSizeX,_mapSizeY);}else{newBbox=checkDeformation(_minx,_miny,_maxx,_maxy,mwidth,mheight);}var __minx=newBbox.minx;var __maxx=newBbox.maxx;var __miny=newBbox.miny;var __maxy=newBbox.maxy;var axl=getCabeceraArcXML(__minx,__miny,__maxx,__maxy,_mapSizeX,_mapSizeY,false,layerVisibilityList,_theDPI);if(tipoImagen=="Aragon"){axl+=getArcXMLOverviewExtension();}if(document.getElementById('printSeleccion')){if(document.getElementById('printSeleccion').checked){axl+=getArcXMLSelection();}}if(document.getElementById('printMediciones')){if(document.getElementById('printMediciones').checked){if(clickCount>0){var axl2=' <LAYER type="acetate" name="marcasMedicion">\n';for(var ii=0;ii<clickCount;ii++){axl2+=' <OBJECT units="database">\n';axl2+=' <POINT coords="'+clickPointX[ii]+' '+clickPointY[ii]+'" >';axl2+=' <SIMPLEMARKERSYMBOL color="255,0,0" type="circle" width="3" />';axl2+=' </POINT>';axl2+=' </OBJECT>\n';}axl2+='</LAYER>\n';axl2+='<LAYER type="acetate" name="lineasMedicion" id="acetate">';axl2+=' <OBJECT units="database">';axl2+=' <SIMPLELINESYMBOL color="255,0,0" width="1" />';axl2+=' <POLYLINE>';axl2+=' <PATH>';axl2+=' <COORDS>';for(var ii=0;ii<clickCount;ii++){axl2+=clickPointX[ii]+' '+clickPointY[ii]+';';if(isAreaMeasuring){if((ii==clickCount-1)&&(clickCount>=3)){axl2+=clickPointX[0]+' '+clickPointY[0];}}}axl2+=' </COORDS>';axl2+=' </PATH>';axl2+=' </POLYLINE>';axl2+=' </OBJECT>';axl2+='</LAYER>';axl+=axl2;}}}if(document.getElementById('printGeorref')){if(document.getElementById('printGeorref').checked){axl+=getArcXMLPointRecordset(pointRecordset,'text');}}if(document.getElementById('printHistorico')){if(document.getElementById('printHistorico').checked){axl+=getArcXMLPointRecordset(historicoRecordset);}}if(valueRadius!=-1){axl+=bufferDrawCircleAroundPt(valueRadius,xRadius,yRadius);}if(customToolType=="GRANJAS"){if(xRadiusGranjas!=null){for(var ii=0;ii<distanceList.length;ii++){axl+=bufferDrawCircleAroundPt(distanceList[ii],xRadiusGranjas,yRadiusGranjas);}}}axl+=' </GET_IMAGE> </REQUEST></ARCXML>\n';return axl;}function getMapRequestAcetateMarca(_minx,_miny,_maxx,_maxy,_xMarca,_yMarca){var axl=getCabeceraArcXML(_minx,_miny,_maxx,_maxy,null,null,true);axl+=getArcXMLAcetateMarca(_xMarca,_yMarca);axl+=' </GET_IMAGE> </REQUEST></ARCXML>\n';return axl;}function getCabeceraArcXML(_minx,_miny,_maxx,_maxy,_mapSizeX,_mapSizeY,allLayersFalse,layerVisibility,_theDPI){var axl='<?xml version="1.0" encoding="UTF-8"?>\n';axl+='<ARCXML version="1.1">\n';axl+=' <REQUEST>\n';axl+=' <GET_IMAGE>\n';axl+=' <PROPERTIES>\n';axl+=' <ENVELOPE minx="'+_minx+'" miny="'+_miny+'" maxx="'+_maxx+'" maxy="'+_maxy+'" />\n';if(_theDPI){if(_mapSizeX&&_mapSizeY){axl+=' <IMAGESIZE height="'+_mapSizeY+'" width="'+_mapSizeX+'" dpi="'+_theDPI+'" scalesymbols="false" />\n';}else{axl+=' <IMAGESIZE height="'+mheight+'" width="'+mwidth+'" dpi="'+_theDPI+'" scalesymbols="false" />\n';}}else{if(_mapSizeX&&_mapSizeY){axl+=' <IMAGESIZE height="'+_mapSizeY+'" width="'+_mapSizeX+'" />\n';}else{axl+=' <IMAGESIZE height="'+mheight+'" width="'+mwidth+'" />\n';}}axl+=' <LAYERLIST>\n';if(allLayersFalse){for(var i=0;i<layerCount;i++){axl+='<LAYERDEF id="'+LayerID[i]+'" visible="false" />\n';}}else{if(layerVisibility){for(var i=0;i<layerCount;i++){if(layerVisibility[i]==1){axl+='<LAYERDEF id="'+LayerID[i]+'" visible="true" />\n';}else{axl+='<LAYERDEF id="'+LayerID[i]+'" visible="false" />\n';}}}else{for(var i=0;i<layerCount;i++){if(LayerVisible[i]==1){axl+='<LAYERDEF id="'+LayerID[i]+'" visible="true" />\n';}else{axl+='<LAYERDEF id="'+LayerID[i]+'" visible="false" />\n';}}}}axl+=' </LAYERLIST>\n';axl+=' </PROPERTIES>\n';return axl;}function getMapRequestAcetateEscala(_minx,_miny,_maxx,_maxy,_mapSizeX,_mapSizeY){var axl=getCabeceraArcXML(_minx,_miny,_maxx,_maxy,_mapSizeX,_mapSizeY,true);var newMapScale=-1;if(_mapSizeX){newMapScale=getMapScale2(false,_minx,_maxx,_mapSizeX);}else{newMapScale=getMapScale2(false,_minx,_maxx,mwidth);}if(newMapScale>=100000){scaleunits="kilometers";}else{scaleunits="meters";}axl+=getArcXMLScaleBar(scaleunits);axl+=' </GET_IMAGE> </REQUEST></ARCXML>\n';return axl;}function getArcXMLScaleBar(scaleunits){var axl='<LAYER type="acetate" name="Escala">\n';axl+='<OBJECT units="pixel"><SCALEBAR precision="0" texttransparency="0.0" bartransparency="1.0" fontcolor="5,5,5" coords="10 10" barcolor="192,90,90" fontsize="11" screenlength="250" barwidth="5" mapunits="meters" antialiasing="true" scaleunits="'+scaleunits+'" overlap="False"/></OBJECT>\n';axl+='<OBJECT units="pixel"><SCALEBAR precision="0" texttransparency="0.0" bartransparency="1.0" fontcolor="5,5,5" coords="10 10" barcolor="255,255,255" fontsize="11" screenlength="175" barwidth="5" mapunits="meters" antialiasing="true" scaleunits="'+scaleunits+'" overlap="False"/></OBJECT>\n';axl+='<OBJECT units="pixel"><SCALEBAR precision="0" texttransparency="0.0" bartransparency="1.0" fontcolor="5,5,5" coords="10 10" barcolor="192,90,90" fontsize="11" screenlength="100" barwidth="5" mapunits="meters" antialiasing="true" scaleunits="'+scaleunits+'" overlap="False"/></OBJECT>\n';axl+='<OBJECT units="pixel"><SCALEBAR precision="0" texttransparency="0.0" bartransparency="1.0" fontcolor="5,5,5" coords="10 10" barcolor="255,255,255" fontsize="11" screenlength="25" barwidth="5" mapunits="meters" antialiasing="true" scaleunits="'+scaleunits+'" overlap="False"/></OBJECT>\n';axl+='<OBJECT units="pixel"><SCALEBAR precision="0" texttransparency="1.0" bartransparency="0.0" fontcolor="245,243,244" coords="10 20" barcolor="192,0,0" fontsize="11" fontstyle="bold" screenlength="250" barwidth="0" mapunits="meters" antialiasing="true" scaleunits="'+scaleunits+'" outline="0,0,0" overlap="False"/></OBJECT>\n';axl+='<OBJECT units="pixel"><SCALEBAR precision="0" texttransparency="1.0" bartransparency="0.0" fontcolor="245,243,244" coords="10 20" barcolor="255,255,255" fontsize="11" fontstyle="bold" screenlength="175" barwidth="0" mapunits="meters" antialiasing="true" scaleunits="'+scaleunits+'" outline="0,0,0" overlap="False"/></OBJECT>\n';axl+='<OBJECT units="pixel"><SCALEBAR precision="0" texttransparency="1.0" bartransparency="0.0" fontcolor="245,243,244" coords="10 20" barcolor="192,90,90" fontsize="11" fontstyle="bold" screenlength="100" barwidth="0" mapunits="meters" antialiasing="true" scaleunits="'+scaleunits+'" outline="0,0,0" overlap="False"/></OBJECT>\n';axl+='<OBJECT units="pixel"><SCALEBAR precision="0" texttransparency="1.0" bartransparency="0.0" fontcolor="245,243,244" coords="10 20" barcolor="255,255,255" fontsize="12" fontstyle="bold" screenlength="25" barwidth="0" mapunits="meters" antialiasing="true" scaleunits="'+scaleunits+'" outline="0,0,0" overlap="False"/></OBJECT>\n';axl+='</LAYER>\n';return axl;}function getArcXMLAcetateMarca(xMarca,yMarca){var axl='';axl+='<LAYER type="acetate" name="Texto Fondo" id="TextoFondo">';axl+='<OBJECT units="pixel">';axl+='<TEXT coords="280 20" label="'+getTextoFondo()+'">';axl+='<TEXTMARKERSYMBOL font="Verdana" fontstyle="bold" fontsize="14" outline="0,0,0" fontcolor="255,255,255" />';axl+='</TEXT>';axl+='</OBJECT>';axl+='</LAYER>';if((xMarca!="")&&(yMarca!="")){axl+=' <LAYER type="acetate" name="allTheClicks">\n';axl+=' <OBJECT units="database">\n';axl+=' <POINT coords="'+xMarca+' '+yMarca+'">\n';axl+=' <RASTERMARKERSYMBOL overlap="true" image="'+chinchetaInfoImagePath+'" url="'+chinchetaInfoURL+'" size="20,20" />\n';axl+=' </POINT>\n';axl+=' </OBJECT>\n';axl+='</LAYER>\n';}return axl;}function getArcXMLSelection(){var axl='';if(idSelectionLayer!=''){if(selectionWhere!=''){axl+=' <LAYER type="featureclass" name="selection">\n';axl+=' <DATASET fromlayer="'+idSelectionLayer+'" />\n';axl+=' <QUERY where="'+selectionWhere+'" />\n';axl+=' <SIMPLERENDERER>\n';if(selectionType=="poin"){axl+='<RASTERMARKERSYMBOL overlap="true" image="'+chinchetaQueryImagePath+'" url="'+chinchetaQueryURL+'" size="20,20" />\n';}else if(selectionType=="line"){axl+='<SIMPLELINESYMBOL type="SOLID" color="'+selectionColorLine+'" width="3" />\n';}else{axl+='<SIMPLEPOLYGONSYMBOL fillcolor="'+selectionColorPoly+'" filltype="solid" transparency="'+selectionTransparentLevel+'" boundarycolor="255,255,255" />\n';}axl+=' </SIMPLERENDERER>\n';axl+='</LAYER>\n';}}return axl;}function getCoords(x1,y1,x2,y2){var theCoords=x1+" "+y1+";";theCoords+=x1+" "+y2+";";theCoords+=x2+" "+y2+";";theCoords+=x2+" "+y1+";";return theCoords;}function getLayerPolygon(x1,y1,x2,y2,tipo){var theString='<LAYER type="ACETATE" id="extensionOverview'+tipo+'" name="extensionOverview'+tipo+'">\n';theString+='<OBJECT units="database">\n';var theCoords=getCoords(x1,y1,x2,y2);theString+='<POLYGON coords="'+theCoords+'">\n';theString+='<SIMPLEPOLYGONSYMBOL fillcolor="255,0,0" filltype="fdiagonal" transparency="0.5" boundarycolor="255,0,0" />\n';theString+='</POLYGON>\n';theString+='</OBJECT>\n';theString+='</LAYER>\n';return theString;}function getArcXMLOverviewExtension(){var theString='';theString+=getLayerPolygon(minxPrint,minyPrint,maxxPrint,maxyPrint,'');var midX=(maxxPrint+minxPrint)/2;var midY=(maxyPrint+minyPrint)/2;theString+=getLayerPolygon(midX,maxyPrint,midX,ymaxOverview,'N');theString+=getLayerPolygon(xminOverview,midY,minxPrint,midY,'W');theString+=getLayerPolygon(maxxPrint,midY,xmaxOverview,midY,'E');theString+=getLayerPolygon(midX,yminOverview,midX,minyPrint,'S');return theString;}function getArcXMLPointRecordset(_recordset,_nombreCampoTexto){var numData=_recordset.getVectorialDataCount();var axl='';if(numData>0){axl=' <LAYER type="acetate" name="theClicks">\n';for(var jj=0;jj<numData;jj++){aux=_recordset.getGeometry(jj);texto='';if(_nombreCampoTexto){texto=_recordset.getAttribute(jj,_nombreCampoTexto);}else{texto=RoundDecimal(aux.getX(),2)+', '+RoundDecimal(aux.getY(),2);}axl+=' <OBJECT units="database">\n';axl+=' <TEXT coords="'+aux.getX()+' '+aux.getY()+'" label="'+texto+'">\n';axl+=' <TEXTMARKERSYMBOL font="Arial" fontstyle="bold" fontsize="14" fontcolor="255,0,0" valignment="bottom"/>\n';axl+=' </TEXT>\n';axl+=' </OBJECT>\n';axl+=' <OBJECT units="database">\n';axl+=' <POINT coords="'+aux.getX()+' '+aux.getY()+'" >';axl+=' <SIMPLEMARKERSYMBOL color="255,0,0" />';axl+=' </POINT>';axl+=' </OBJECT>\n';}axl+='</LAYER>\n';}return axl;}function bufferDrawCircleAroundPt(radiusDistance,buffX,buffY){if(debugOn){alert("[function bufferDrawCircleAroundPt]\nradiusDistance="+radiusDistance+"\nbuffX="+buffX+"\nbuffY="+buffY);}var theCoords="";var increment=0.0;firstTime=true;distance=radiusDistance;x=buffX;y=buffY;while(increment<=359.0){var x1=x+(distance*Math.cos(increment*Math.PI/180));var y1=y+(distance*Math.sin(increment*Math.PI/180));theCoords=theCoords+String(x1)+" ";theCoords=theCoords+String(y1)+";";if(firstTime){firstString=theCoords;firstTime=false;}increment=increment+1;}var lastString=firstString.substring(0,firstString.length-1);theCoords=theCoords+lastString;var theString='<LAYER type="ACETATE" id="selRadiusCircle" name="Circle">\n';theString+='<OBJECT units="database">\n';theString+='<POLYGON coords="'+theCoords+'">\n';theString+='<SIMPLEPOLYGONSYMBOL fillcolor="255,0,0" filltype="fdiagonal" fillinterval="6" transparency="1,0" boundarycolor="255,0,0" boundarywidth="3" />\n';theString+='</POLYGON>\n';theString+='</OBJECT>\n';theString+='</LAYER>\n';theString+='<LAYER type="ACETATE" id="ptInCircle" name="PointInCircle">\n';theString+='<OBJECT units="database">\n';theString+='<POINT coords="'+x+' '+y+'">\n';theString+='<SIMPLEMARKERSYMBOL color="255,0,0" outline="255,0,0" type="cross" transparency="1,0" width="5" />\n';theString+='</POINT>\n';theString+='</OBJECT>\n';theString+='</LAYER>\n';if(debugOn){alert("[function bufferDrawCircleAroundPt]\ntheString="+theString);}return theString;}function getPoligonoSeleccionadoArcXML(tipoImagen,sinFondo){var axl="";axl+='<LAYER type="acetate" name="poligonoSeleccionado" id="poligonoSeleccionado">';axl+=' <OBJECT units="database">';if(tipoImagen==""){if(sinFondo){axl+=' <SIMPLEPOLYGONSYMBOL fillcolor="0,0,255" filltype="gray" filltransparency="0" boundarytransparency="1" boundarycolor="255,168,50" boundarywidth="'+selectionBoundaryWidthPoly+'" />\n';}else{axl+=' <SIMPLEPOLYGONSYMBOL fillcolor="255,0,0" filltype="gray" transparency="1" boundarycolor="255,128,0" boundarywidth="2" />\n';}axl+=coordsPoligono;}else if(tipoImagen=="Aragon"){var xCentroidePoligono=((maxxPoligono-minxPoligono)/2)+minxPoligono;var yCentroidePoligono=((maxyPoligono-minyPoligono)/2)+minyPoligono;axl+=' <POINT coords="'+xCentroidePoligono+' '+yCentroidePoligono+'">\n';axl+=' <SIMPLEMARKERSYMBOL color="255,0,0" outline="255,0,0" type="cross" transparency="1.0" width="5" />\n';axl+=' </POINT>\n';}else if(tipoImagen=="Situacion"){var diffXPoligono=(maxxPoligono-minxPoligono);var diffYPoligono=(maxyPoligono-minyPoligono);if((diffXPoligono<1000)||(diffXPoligono<1000)){var xCentroidePoligono=((maxxPoligono-minxPoligono)/2)+minxPoligono;var yCentroidePoligono=((maxyPoligono-minyPoligono)/2)+minyPoligono;axl+=' <POINT coords="'+xCentroidePoligono+' '+yCentroidePoligono+'">\n';axl+=' <SIMPLEMARKERSYMBOL color="255,0,0" outline="255,0,0" type="cross" transparency="1.0" width="5" />\n';axl+=' </POINT>\n';}else{axl+=' <SIMPLEPOLYGONSYMBOL fillcolor="255,0,0" filltype="gray" transparency="1" boundarycolor="255,128,0" boundarywidth="2" />\n';axl+=coordsPoligono;}}axl+='</OBJECT>\n';axl+='</LAYER>\n';return axl;}function getServiceInfo(){var axl='<?xml version="1.0" encoding="UTF-8"?><ARCXML version="1.1">\n<REQUEST>\n<GET_SERVICE_INFO renderer="false" extensions="false" fields="false" />\n</REQUEST>\n</ARCXML>\n';http=getHTTPObject();if((http!=null)){http.open("POST",url,true);http.onreadystatechange=parseLayers;isWorking=true;muestraLayerLoading();http.send(axl);}}function parseLayers(){if(http.readyState==4){if(http.status==200){var result=http.responseText;if(debugOn){alert("recibidas layers:"+result);}getLayers(result);getBbox(result);if(customQuery){eval(initialQueryString);}else{if(customInitialMap){getMap(customMinx,customMiny,customMaxx,customMaxy);}else{getFullMap();}}}else{alert("Error accediendo a la información. Por favor, vuelva a actualizar la página.");}}}function getBbox(reply){posEnv=reply.indexOf("<ENVELOPE ",0);startposEnv=posEnv+10;endposEnv=reply.indexOf('/>',startposEnv);envelopeData=reply.substring(startposEnv,endposEnv);bbox=new Array();if(envelopeData!=""){var fValueEnv=getFieldValuesQuery(envelopeData);var fNameEnv=getFieldNamesQuery(envelopeData);parseEnvelope(fNameEnv,fValueEnv,bbox);}fullLeft=parseFloat(bbox["minx"]);fullBottom=parseFloat(bbox["miny"]);fullRight=parseFloat(bbox["maxx"]);fullTop=parseFloat(bbox["maxy"]);}var tocVisible=true;var tocContent="";function displayToc(){tocContent=getLayersContent();for(var i=0;i<layerCount;i++){tocContent+=" <tr valign=\"middle\">\n";tocContent+=" <td></td>\n";tocContent+="   <td><img src=\"images/linelastnode.gif\" border=\"0\"></td>\n";tocContent+="     <td colspan=\"1\" NOWRAP>\n";tocContent+="  <input type=\"checkbox\" value=\"\" onclick=\"setVisibility("+i+");getMapWithCurrentExtent();\"";if(LayerVisible[i]==1)tocContent+=" CHECKED ";tocContent+="/>\n";tocContent+="          <input type=\"radio\" name=\"activelyr\" value=\"\" onclick=\"setActiveLayer("+i+")\"";if(i==ActiveLayerIndex)tocContent+=" CHECKED ";tocContent+="/> ";tocContent+=LayerName[i]+"</td></tr>\n";}tocContent+="</table>\n";if(hasTocInitialOpened){tocWin.show();}toc.divToc=document.getElementById("tocWincontent");tocWin.setcontent(toc.writeHTML());return false;}function getLayersContent(){var lyrsContent="";lyrsContent+="<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n";lyrsContent+="  <tr valign=\"middle\">\n";lyrsContent+="    <td><a href=\"#\" onclick=\"toggleVisibility();\" >";if(tocVisible)lyrsContent+="<img src=\"images/folderopened.gif\" border=\"0\"></a>\n";else lyrsContent+="<img src=\"images/folderclosed.gif\" border=\"0\"></a>\n";lyrsContent+="    </td>\n";lyrsContent+="    <td colspan=\"2\" NOWRAP>   Layers</td></tr>\n";return lyrsContent;}function toggleVisibility(){tocVisible=!tocVisible;var lyrsContent=getLayersContent();if(!tocVisible){tocWin.setcontent(lyrsContent);}else{displayToc();}}function setVisibility(lyrIndex){if(LayerVisible[lyrIndex]==1)LayerVisible[lyrIndex]=0;else LayerVisible[lyrIndex]=1;}function setActiveLayer(lyrIndex){ActiveLayerIndex=lyrIndex;ActiveLayer=LayerID[lyrIndex];}function updateContent(name,content){var theObj=document.getElementById(name);if(theObj!=null){theObj.innerHTML=content;}return false;}var idMinX,idMinY,idMaxX,idMaxY;var idCount=0;var selectedId=1;currentQueriedLayer=0;currentQueriedGFI=0;xUsr=-1;yUsr=-1;xCoordUsr="";yCoordUsr="";urlOVC="";altitudCalculada=false;laCota='';var resultOVC=-1;var countResultQueryableLayer=new Array();var askedI=-1;var askedJ=-1;var askedK=-1;function checkScale(actLayer){currentScale=getMapScale();if((minScale[actLayer]<currentScale)&&(currentScale>maxScale[actLayer])){return false;}else{return true;}}function descarga(x1,y1){resetResultadosAnterioresGFI();xUsr=x1;yUsr=y1;var coordUsr=convertPixelToMap(xUsr,yUsr);xCoordUsr=coordUsr[0];yCoordUsr=coordUsr[1];var urlGFI=urlGFI_SITAR;urlGFI+='&BBOX='+minx+','+miny+','+maxx+','+maxy;urlGFI+='&WIDTH='+mwidth+'&HEIGHT='+mheight+'&X='+xUsr+'&Y='+yUsr;if(debugOn){window.open(urlGFI);}http=getHTTPObject();if((http!=null)){http.open("GET",urlGFI);http.onreadystatechange=parseResultGFIQuery_sitar2;isWorking=true;muestraLayerLoading();t_timeout=setTimeout("sinRespuestaGFI()",12000);http.send(null);}}function identifyOVC(x1,y1){urlOVC='http:/'+'/www.sedecatastro.gob.es/Cartografia/WMS/ServidorWMS.aspx?SRS=EPSG:23030&Query_Layers=Catastro&service=WMS&request=GetFeatureInfo&version=1.1.1&WIDTH='+mwidth+'&HEIGHT='+mheight;urlOVC+='&INFO_FORMAT=text/html&EXCEPTIONS=application/vnd.ogc.se_xml&FEATURE_COUNT=5';urlOVC+='&BBOX='+minx+','+miny+','+maxx+','+maxy;urlOVC+='&X='+x1+'&Y='+y1;window.open(urlOVC);}function resetConsultaIdentify(){theHiddenURL=new Array();theHiddenURLGeneral="";selectedId=1;currentQueriedLayer=0;currentQueriedGFI=0;resetResultadosAnteriores();resetResultadosAnterioresGFI();altitudCalculada=false;resultOVC=-1;detailedResultsWin.hide();resultsWin.hide();xUsr=-1;yUsr=-1;xCoordUsr="";yCoordUsr="";}function identify(x1,y1){resetConsultaIdentify();urlOVC='http:/'+'/www.sedecatastro.gob.es/Cartografia/WMS/ServidorWMS.aspx?SRS=EPSG:23030&Query_Layers=Catastro&service=WMS&request=GetFeatureInfo&version=1.1.1&WIDTH='+mwidth+'&HEIGHT='+mheight;urlOVC+='&INFO_FORMAT=text/html&EXCEPTIONS=application/vnd.ogc.se_xml&FEATURE_COUNT=5';urlOVC+='&BBOX='+minx+','+miny+','+maxx+','+maxy;urlOVC+='&X='+x1+'&Y='+y1;xUsr=x1;yUsr=y1;var coordUsr=convertPixelToMap(xUsr,yUsr);xCoordUsr=coordUsr[0];yCoordUsr=coordUsr[1];if(toleranceInPixels){var idMins=convertPixelToMap(x1-(pixelTolerance/2),y1+(pixelTolerance/2));var idMaxs=convertPixelToMap(x1+(pixelTolerance/2),y1-(pixelTolerance/2));idMinX=idMins[0];idMinY=idMins[1];idMaxX=idMaxs[0];idMaxY=idMaxs[1];}else{idMinX=xCoordUsr-toleranceMeters;idMinY=yCoordUsr-toleranceMeters;idMaxX=xCoordUsr+(toleranceMeters*1);idMaxY=yCoordUsr+(toleranceMeters*1);}if(currentQueriedLayer+1<queryableLayerCount){muestraLayerLoading();ActiveLayer=queryableLayer[currentQueriedLayer]["ID_QUERY"];if(checkScale(ActiveLayer)){sendIdRequest(true);}else{countResultQueryableLayer[currentQueriedLayer]=0;doNextQuery();}}else{muestraLayerLoading();doNextQuery();}}function sendIdRequest(countOnly,beginRecord){var axl=getIdRequest(countOnly,beginRecord);var identifyUrl=defaultQueryUrl;http=getHTTPObject();if((http!=null)){http.open("POST",identifyUrl,true);if(countOnly){http.onreadystatechange=parseResultForCount;}else{http.onreadystatechange=parseResult;}isWorking=true;muestraLayerLoading();if(debugOn){alert(axl);}http.send(axl);}}function calculaAltitudXY(theX,theY,mustContinue){if(layerIdAltitud!=""){var axl=writeRasterInfoXML(layerIdAltitud,theX,theY,"23030");var identifyUrl=defaultQueryUrl;http=getHTTPObject();if((http!=null)){http.open("POST",defaultUrl,true);if(mustContinue){http.onreadystatechange=parseResultAltitud_mustContinue;}else{http.onreadystatechange=parseResultAltitud_noContinue;}isWorking=true;if(debugOn){alert(axl);}http.send(axl);}}else{laCota="No disponible";altitudCalculada=true;if(mustContinue){doNextQuery();}}}function sinRespuestaGFI_OVC(){resultOVC="El servicio no est&aacute; operativo en estos momentos.";doNextQuery();}function calculaRefCatOVC(){queryURL_OVC=urlGFI_OVC;queryURL_OVC+='&BBOX='+minx+','+miny+','+maxx+','+maxy;queryURL_OVC+='&WIDTH='+mwidth+'&HEIGHT='+mheight+'&X='+xUsr+'&Y='+yUsr;if(debugOn){window.open(queryURL_OVC);}http=getHTTPObject();if((http!=null)){http.open("GET",queryURL_OVC);http.onreadystatechange=parseResultOVC;isWorking=true;t_timeout=setTimeout("sinRespuestaGFI_OVC()",8000);http.send(null);}}function parseResultOVC(){if(http.readyState==4){if(http.status==200){clearTimeout(t_timeout);var result=http.responseText;processResultOVC(result);doNextQuery();}else{clearTimeout(t_timeout);sinRespuestaGFI_OVC();}}}function processResultOVC(theReply){searchStr='<a';startpos=theReply.indexOf(searchStr,1);endpos=theReply.indexOf("</a>",startpos);if((startpos!=-1)&&(endpos!=-1)){resultOVCAux=theReply.substring(startpos+2,endpos+4);resultOVC="<a class='itemEnlace normal' target='_blank' "+resultOVCAux;}else{resultOVC="No disponible";}}function processResultOVC_customGeorref(theReply){searchStr='<a';startpos=theReply.indexOf(searchStr,1);aux=theReply.substring(startpos+2);startpos2=aux.indexOf(">",1);endpos=aux.indexOf("</a>",startpos2);if((startpos!=-1)&&(startpos2!=-1)&&(endpos!=-1)){resultOVCAux=aux.substring(startpos2+1,endpos);resultOVC=resultOVCAux;}else{resultOVC="No disponible";}}function calculaRefCatOVC_customGeorref(x1,y1){xUsr=x1;yUsr=y1;var coordUsr=convertPixelToMap(xUsr,yUsr);xCoordUsr=coordUsr[0];yCoordUsr=coordUsr[1];queryURL_OVC=urlGFI_OVC;queryURL_OVC+='&BBOX='+minx+','+miny+','+maxx+','+maxy;queryURL_OVC+='&WIDTH='+mwidth+'&HEIGHT='+mheight+'&X='+xUsr+'&Y='+yUsr;if(debugOn){window.open(queryURL_OVC);}http=getHTTPObject();if((http!=null)){http.open("GET",queryURL_OVC);http.onreadystatechange=parseResultOVC_customGeorref;isWorking=true;t_timeout=setTimeout("sinRespuestaGFI_OVC_customGeorref()",8000);http.send(null);}}function parseResultOVC_customGeorref(){if(http.readyState==4){if(http.status==200){clearTimeout(t_timeout);var result=http.responseText;processResultOVC_customGeorref(result);writeRefCat_customGeorref();}else{clearTimeout(t_timeout);sinRespuestaGFI_OVC_customGeorref();}}}function writeRefCat_customGeorref(){if(resultOVC!="No disponible"){writePersistentCookie("refcat",resultOVC,"months",1);writePersistentCookie("parcela","","months",1);writePersistentCookie("poligono","","months",1);writePersistentCookie("coorX",xCoordUsr,"months",1);writePersistentCookie("coorY",yCoordUsr,"months",1);top.close();}else{alert("Error obteniendo la referencia catastral del servicio web de la Sede Electrónica de Catastro. Por favor, inténtelo más tarde.");}}function sinRespuestaGFI_OVC_customGeorref(){resultOVC="No disponible";writeRefCat_customGeorref();}function getIdRequest(countOnly,beginRecord){var axl='<?xml version="1.0"?>';var beginRecordNum=0;if(beginRecord){beginRecordNum=beginRecord;}axl+='<ARCXML version="1.1">\n<REQUEST>\n<GET_FEATURES geometry="false" outputmode="xml" checkesc ="true" ';if(countOnly)axl+='envelope="false" skipfeatures="true">\n';else axl+='envelope="true" skipfeatures="false" beginrecord="'+beginRecordNum+'" featurelimit="99">\n';axl+='<LAYER id="'+ActiveLayer+'" />';axl+='<SPATIALQUERY subfields="'+getFields(ActiveLayer)+'" where="'+getWhereQuery(ActiveLayer)+'">';axl+='<SPATIALFILTER relation="area_intersection" >';axl+='<ENVELOPE maxy="'+idMaxY+'" maxx="'+idMaxX+'" miny="'+idMinY+'" minx="'+idMinX+'" />';axl+='</SPATIALFILTER>';axl+='</SPATIALQUERY>';axl+='</GET_FEATURES>';axl+='</REQUEST>';axl+='</ARCXML>';return axl;}function writeRasterInfoXML(theLayer,theX,theY,theCoordSys){var theString='<?xml version="1.0"?>';theString+='<ARCXML version="1.1">\n<REQUEST>\n';theString+='<GET_RASTER_INFO x="'+theX+'" y="'+theY+'" layerid="'+theLayer+'" >';theString+='<COORDSYS id="'+theCoordSys+'" />';theString+='</GET_RASTER_INFO>';theString+='</REQUEST>';theString+='</ARCXML>';return theString;}function genericParseResult(callFunc){if(http.readyState==4){if(http.status==200){var result=http.responseText;if(debugOn){alert(result);}eval(callFunc);}else{alert("Error de ejecución");}}}function parseResultForCount(){genericParseResult("idCount = getCount(result);countResultQueryableLayer[currentQueriedLayer] = idCount;doNextQuery();");}function parseResult(){genericParseResult("processResult(result);drawDetailedResult(askedI,askedJ,askedK);");}function parseResultAltitud_mustContinue(){genericParseResult("processResultAltitud(result);doNextQuery();");}function parseResultAltitud_noContinue(){genericParseResult("processResultAltitud(result);altitudEstaCalculada();");}function processResultAltitud(theReply){searchStr='<BAND number="0" value="';pos=theReply.indexOf(searchStr,1);startpos=pos+searchStr.length;endpos=theReply.indexOf(".",startpos);if(endpos==-1){endpos=theReply.indexOf(",",startpos);}
if(endpos==-1){endpos=theReply.indexOf("\"",startpos);}if((pos!=-1)&&(endpos!=-1)){laCota=theReply.substring(startpos,endpos);}altitudCalculada=true;}function getCount(theReply){var theCount;var startpos=0;var endpos=0;var pos=theReply.indexOf("FEATURECOUNT");var pos1=theReply.indexOf("count",pos+12);if(pos1!=-1){pos1+=7;var pos2=theReply.indexOf("\"",pos1);theCount=parseFloat(theReply.substring(pos1,pos2));}else{theCount=0;}
return theCount;}
function processResult(theReply){var selectedData="";var endpos=1;reply=theReply;resultNum=0;var pos=reply.indexOf("<FIELDS ",endpos);while(pos!=-1){startpos=pos+8;endpos=reply.indexOf('" />',startpos);selectedData=reply.substring(startpos,endpos);if(selectedData!=""){var fValue1=getFieldValues(selectedData);var fName1=getFieldNames(selectedData);queryableLayer[currentQueriedLayer]["camposRespuesta"][resultNum]=fName1;queryableLayer[currentQueriedLayer]["valoresRespuesta"][resultNum]=fValue1;queryableLayer[currentQueriedLayer]["camposRespuesta"]["count"]++;queryableLayer[currentQueriedLayer]["valoresRespuesta"]["count"]++;resultNum++;}reply=reply.substring(endpos);pos=reply.indexOf("<FIELDS ",1);}}function doNextQuery(){if(currentQueriedLayer+1<queryableLayerCount){currentQueriedLayer++;ActiveLayer=queryableLayer[currentQueriedLayer]["ID_QUERY"];if(checkScale(ActiveLayer)){sendIdRequest(true);}else{countResultQueryableLayer[currentQueriedLayer]=0;doNextQuery();}}else{if(currentQueriedLayer<9999){if((resultOVC==-1)&&(needCalculateOVC)){calculaRefCatOVC();}else{if((!altitudCalculada)&&(needCalculateAltitud)){if(debugOn){alert("calcular altitud");}calculaAltitudXY(xCoordUsr,yCoordUsr,true);}else{if(currentQueriedGFI<gfiCount){var urlGFI=gfiList[currentQueriedGFI]["url"];urlGFI+='&BBOX='+minx+','+miny+','+maxx+','+maxy;urlGFI+='&WIDTH='+mwidth+'&HEIGHT='+mheight+'&X='+xUsr+'&Y='+yUsr;if(debugOn){alert("envio la GFI "+currentQueriedGFI);}sendGFIQuery(urlGFI);}else{currentQueriedLayer=0;currentQueriedGFI=0;updateAcetateMarca();updateResults();}}}}else{if(currentQueriedLayer=="9999"){if(queryableLayer[9999]["camposRespuesta"]["count"]>0){refCatUEstaCalculada();}else{currentQueriedLayer++;ActiveLayer="CatR";sendIdRequest(false);}}else{refCatREstaCalculada();}}}}function activarCapaConcreta(idx){layerID=queryableLayer[idx]["ID"];var lay=toc.findItemByAxlID(layerID);if(!lay){var layerName=queryableLayer[idx]["NAME"];lay=toc.findItemByCaption(layerName);}if(lay){if(!lay.getVisible()){lay.setVisible(true);toc.refresh();getMapWithCurrentExtent();}}else{alert("la capa "+layerID+" no se encuentra definida");}}function calculateAltitud(x1,y1){xUsr=x1;yUsr=y1;var coordUsr=convertPixelToMap(xUsr,yUsr);xCoordUsr=coordUsr[0];yCoordUsr=coordUsr[1];calculaAltitudXY(xCoordUsr,yCoordUsr,false);writePersistentCookie("coordenadas",RoundDecimal(xCoordUsr,2)+","+RoundDecimal(yCoordUsr,2)+","+"ee","months",1);}function calculateRefCat(x1,y1){xUsr=x1;yUsr=y1;var coordUsr=convertPixelToMap(xUsr,yUsr);xCoordUsr=coordUsr[0];yCoordUsr=coordUsr[1];ActiveLayer="CatU";currentQueriedLayer=9999;sendIdRequest(false);}function altitudEstaCalculada(){writePersistentCookie("coordenadas",RoundDecimal(xCoordUsr,2)+","+RoundDecimal(yCoordUsr,2)+","+laCota,"months",1);top.close();altitudCalculada=false;}function refCatUEstaCalculada(){var idx=9999;if(queryableLayer[idx]["camposRespuesta"]["count"]>0){var kk=0;fName1=queryableLayer[idx]["camposRespuesta"][kk];fValue1=queryableLayer[idx]["valoresRespuesta"][kk];var indexRefCat=-1;var indexParcela=-1;var indexCoorX=-1;var indexCoorY=-1;for(var ii=0;ii<fName1.length;ii++){tempString=fName1[ii];if((shortenSDENames==true)&&(tempString.split(".").length>2)){nombreCampo=tempString.split(".")[tempString.split(".").length-1];}else{nombreCampo=tempString;}if(nombreCampo=="REFCAT"){indexRefCat=ii;}if(nombreCampo=="PARCELA"){indexParcela=ii;}if(nombreCampo=="COORX"){indexCoorX=ii;}if(nombreCampo=="COORY"){indexCoorY=ii;}}writePersistentCookie("refcat",fValue1[indexRefCat],"months",1);writePersistentCookie("parcela",fValue1[indexParcela],"months",1);writePersistentCookie("poligono","0000","months",1);writePersistentCookie("coorX",fValue1[indexCoorX],"months",1);writePersistentCookie("coorY",fValue1[indexCoorY],"months",1);top.close();}}function refCatREstaCalculada(){var idx=10000;if(queryableLayer[idx]["camposRespuesta"]["count"]>0){var kk=0;fName1=queryableLayer[idx]["camposRespuesta"][kk];fValue1=queryableLayer[idx]["valoresRespuesta"][kk];var indexRefCat=-1;var indexParcela=-1;var indexPoligono=-1;var indexCoorX=-1;var indexCoorY=-1;for(var ii=0;ii<fName1.length;ii++){tempString=fName1[ii];if((shortenSDENames==true)&&(tempString.split(".").length>2)){nombreCampo=tempString.split(".")[tempString.split(".").length-1];}else{nombreCampo=tempString;}if(nombreCampo=="REFCAT"){indexRefCat=ii;}if(nombreCampo=="PARCELA"){indexParcela=ii;}if(nombreCampo=="SUBPARCE"){indexPoligono=ii;}if(nombreCampo=="COORX"){indexCoorX=ii;}if(nombreCampo=="COORY"){indexCoorY=ii;}}writePersistentCookie("refcat",fValue1[indexRefCat],"months",1);writePersistentCookie("parcela",fValue1[indexParcela],"months",1);writePersistentCookie("poligono",fValue1[indexPoligono],"months",1);writePersistentCookie("coorX",fValue1[indexCoorX],"months",1);writePersistentCookie("coorY",fValue1[indexCoorY],"months",1);top.close();}else{writePersistentCookie("refcat","","months",1);top.close();}}function getFieldNames(recordString){var theStuff=new String(recordString);var theList=theStuff.split('" ');var fName1=new Array();for(var f=0;f<theList.length;f++){var v=theList[f].split('="');fName1[f]=v[0];}return fName1;}function getFieldValues(recordString){var theStuff=new String(recordString);var theList=theStuff.split('" ');var fValue1=new Array();for(var f=0;f<theList.length;f++){var v=theList[f].split('="');if((v[1]=="")||(v[1]==null))v[1]="&nbsp;";fValue1[f]=v[1];}return fValue1;}function getWhereQuery(idCapa){if(whereQuery[idCapa]){return whereQuery[idCapa];}else{return'';}}function getFields(idCapa){selectFields='';if(selFieldList[idCapa]){selectFields=selFieldList[idCapa];}else{selectFields="#ALL#";}return selectFields;}function resetResultadosAnteriores(){for(var jj=0;jj<queryableLayerCount;jj++){queryableLayer[jj]["camposRespuesta"]=new Array();queryableLayer[jj]["camposRespuesta"]["count"]=0;queryableLayer[jj]["valoresRespuesta"]=new Array();queryableLayer[jj]["valoresRespuesta"]["count"]=0;countResultQueryableLayer[jj]=-1;}}function convertPixelToMap(px,py){var dx=(maxx-minx)/mwidth;var mx=minx+(dx*px);var my=miny+(dx*(mheight-py));var newpoint=new Array();newpoint[0]=mx;newpoint[1]=my;return newpoint;}function updateResultsGFI_SITAR(){var idContent=getResultsGFIHTML_sitar();document.getElementById('resultadosIdZone').innerHTML=idContent;hideFotograma();hideTextoAyuda();showResults();}var theX,theY;var x1,y1,x2,y2;var zleft,zright,ztop,zbottom;var mtop,mleft,mwidth,mheight,mbroder;var mapDivId;var activeTool='zoomIn';var dragging=false;var panning=false;var waitingForResponse=false;function setMapDivProperties(_top,_left,_width,_height,_border,_mapId){mtop=_top+_border;mleft=_left+_border;mwidth=_width-(2*_border);mheight=_height-(2*_border);mborder=_border;mapDivId=_mapId;}function updateMapDivProperties(width,height){mwidth=width-(2*borderr);mheight=height-(2*borderr);}function createZoomBoxDivs(){createLayer("zoomboxTop",mleft,mtop,mwidth,mheight,false,"",11001);createLayer("zoomboxBottom",mleft,mtop,mwidth,mheight,false,"",11001);createLayer("zoomboxLeft",mleft,mtop,mwidth,mheight,false,"",11001);createLayer("zoomboxRight",mleft,mtop,mwidth,mheight,false,"",11001);setLayerBackgroundColor("zoomboxTop","blue");setLayerBackgroundColor("zoomboxBottom","blue");setLayerBackgroundColor("zoomboxLeft","blue");setLayerBackgroundColor("zoomboxRight","blue");}function createIdResultDiv(){document.writeln('<div id="IdResult" style="position:absolute; overflow:auto; left:0px; top:0px; width:500px; height:460px; background-color:White; border-style:ridge;visibility:hidden;">');document.writeln('</div>');}function changeActiveTool(newActiveTool){switch(newActiveTool){case'zoomIn':case'zoomOut':case'pan':case'identifyAll':case'descarga':case'identifyOVC':case'distanceMeasure':case'areaMeasure':case'editar':case'historico':case'bufferCirculo':limpiaActiveTool(activeTool);activeTool=newActiveTool;marcaActiveTool(activeTool);break;default:break;}}function limpiaActiveTool(i){switch(i){case'zoomIn':document.getElementById('toolImg_zoomIn').src='images/zoomIn.png';break;case'zoomOut':document.getElementById('toolImg_zoomOut').src='images/zoomOut.png';break;case'pan':document.getElementById('toolImg_pan').src='images/pan.png';break;case'identifyAll':document.getElementById('toolImg_identifyAll').src='images/identifyAll.png';break;case'descarga':document.getElementById('toolImg_descarga').src='images/descarga.png';break;case'identifyOVC':document.getElementById('toolImg_identifyOVC').src='images/identifyOVC.png';break;case'distanceMeasure':document.getElementById('toolImg_distanceMeasure').src='images/distanceMeasure.png';break;case'areaMeasure':document.getElementById('toolImg_areaMeasure').src='images/areaMeasure.png';break;case'editar':document.getElementById('toolImg_editar').src='images/editar.png';break;case'historico':document.getElementById('toolImg_historico').src='images/historico.png';break;case'bufferCirculo':document.getElementById('toolImg_bufferCirculo').src='images/bufferCirculo.png';break;}}function marcaActiveTool(i){switch(i){case'zoomIn':document.getElementById('toolImg_zoomIn').src='images/zoomInRO.png';break;case'zoomOut':document.getElementById('toolImg_zoomOut').src='images/zoomOutRO.png';break;case'pan':document.getElementById('toolImg_pan').src='images/panRO.png';break;case'identifyAll':document.getElementById('toolImg_identifyAll').src='images/identifyAllRO.png';break;case'descarga':document.getElementById('toolImg_descarga').src='images/descargaRO.png';break;case'identifyOVC':document.getElementById('toolImg_identifyOVC').src='images/identifyOVCRO.png';break;case'distanceMeasure':document.getElementById('toolImg_distanceMeasure').src='images/distanceMeasureRO.png';break;case'areaMeasure':document.getElementById('toolImg_areaMeasure').src='images/areaMeasureRO.png';break;case'editar':document.getElementById('toolImg_editar').src='images/editarRO.png';break;case'historico':document.getElementById('toolImg_historico').src='images/historicoRO.png';break;case'bufferCirculo':document.getElementById('toolImg_bufferCirculo').src='images/bufferCirculoRO.png';break;}}function setActiveTool(newActiveTool){changeActiveTool(newActiveTool);var layer=document.getElementById("eventosMapa");if(newActiveTool=="zoomIn"||newActiveTool=="zoomOut"){layer.onmousedown=startDragging;layer.onclick=null;layer.style.cursor="crosshair";}else if(newActiveTool=="pan"){layer.onmousedown=startMapDragging;layer.onclick=null;layer.style.cursor="move";}else if(newActiveTool=="identifyAll"){layer.onmousedown=pointClick;layer.onclick=null;layer.style.cursor="crosshair";}else if(newActiveTool=="descarga"){layer.onmousedown=pointClickDescarga;layer.onclick=null;layer.style.cursor="crosshair";}else if(newActiveTool=="identifyOVC"){layer.onmousedown=pointClickOVC;layer.onclick=null;layer.style.cursor="crosshair";}else if(newActiveTool=="toc"){showToc();}else if(newActiveTool=="find"){showFind();}else if(newActiveTool=="ayuda"){window.open("http://sitar.aragon.es/docs/manual-uso-visor2d-sitar.pdf");}else if(newActiveTool=="fullExtent"){getFullMap();}else if(newActiveTool=="overview"){showOverview();}else if(newActiveTool=="bufferCirculo"){isDistanceMeasuring=false;isAreaMeasuring=false;isDistanceMeasuring=false;isGeoreferencing=false;isHistorico=false;forceHideGenerica(distanceMeasureWin);forceHideGenerica(areaMeasureWin);forceHideGenerica(editarWin);forceHideGenerica(historicoWin);bufferCircleWin.show();layer.onmousedown=pointClickBufferCirculo;layer.onclick=null;layer.style.cursor="crosshair";}else if(newActiveTool=="imprimir"){printOptionsWin.show();}else if(newActiveTool=="borrar"){limpiarMapa();limpiarMarcaMapa();borrarBufferCirculo();borrarBufferCirculoGranjas();}else if(newActiveTool=="zoomLast"){previousExtent();}else if(newActiveTool=="informeGeneral"){informeGeneral();}else if(newActiveTool=="distanceMeasure"){if(clickCount>0){if(isAreaMeasuring){resetClick();}}if(isGeoreferencing||isAreaMeasuring||isHistorico){limpiarMapa();areaMeasureWin.forceHide();editarWin.forceHide();historicoWin.forceHide();}isDistanceMeasuring=true;isAreaMeasuring=false;isGeoreferencing=false;isHistorico=false;layer.onmousedown=clickAddPoint_distanceMeasure;layer.onclick=null;layer.style.cursor="crosshair";forceHideGenerica(bufferCircleWin);distanceMeasureWin.show();clearDistanceMeasureBox();}else if(newActiveTool=="areaMeasure"){if(clickCount>0){if(isDistanceMeasuring){resetClick();}}if(isGeoreferencing||isDistanceMeasuring||isHistorico){limpiarMapa();distanceMeasureWin.forceHide();editarWin.forceHide();historicoWin.forceHide();}isDistanceMeasuring=false;isAreaMeasuring=true;isGeoreferencing=false;isHistorico=false;layer.onmousedown=clickAddPoint_areaMeasure;layer.onclick=null;layer.style.cursor="crosshair";forceHideGenerica(bufferCircleWin);areaMeasureWin.show();clearAreaMeasureBox();}else if(newActiveTool=="editar"){if(clickCount>0){resetClick();}if(isDistanceMeasuring||isAreaMeasuring||isHistorico){limpiarMapa();distanceMeasureWin.forceHide();areaMeasureWin.forceHide();historicoWin.forceHide();}isDistanceMeasuring=false;isAreaMeasuring=false;isGeoreferencing=true;isHistorico=false;forceHideGenerica(bufferCircleWin);if(customToolEditar){if(customToolEditarType=="GEOREF1"){layer.onmousedown=georef1PointClick;layer.onclick=null;layer.style.cursor="crosshair";}else{layer.onmousedown=georef2PointClick;layer.onclick=null;layer.style.cursor="crosshair";}}else{if(originador==null){changeOriginador();}updateGeorefMapClicks(jgPoint,pointRecordset,jgPointLabel);layer.onmousedown=clickAddPoint_editar;layer.onclick=null;layer.style.cursor="crosshair";editarWin.show();}}else if(newActiveTool=="historico"){if(clickCount>0){resetClick();}if(isDistanceMeasuring||isAreaMeasuring||isGeoreferencing){limpiarMapa();distanceMeasureWin.forceHide();areaMeasureWin.forceHide();editarWin.forceHide();}isDistanceMeasuring=false;isAreaMeasuring=false;isGeoreferencing=false;isHistorico=true;updateGeorefMapClicks(jgHistorico,historicoRecordset,jgHistoricoLabel);layer.onmousedown=clickAddPoint_historico;layer.onclick=null;layer.style.cursor="crosshair";historicoWin.show();}}function limpiarMarcaMapa(){xCoordUsr="";yCoordUsr="";findXCoordUsr="";findYCoordUsr="";document.getElementById('theAcetateMarca').style.display='none';}function limpiarMapa(){limpiarMedicionDistancia();limpiarMedicionArea();limpiarEdicion();limpiarHistorico();if(idSelectionLayer){idSelectionLayer="";getMapWithCurrentExtent();}}function startDragging(e){panning=false;if(!dragging){dragging=true;getXY(e);x1=theX;y1=theY;x2=x1+1;y2=y1+1;showZoomBox(x1,y1,x2,y2);document.onmousemove=updateDragging;document.onmouseup=stopDragging;}return false;}function startMapDragging(e){dragging=false;if(!panning){panning=true;getXY(e);x1=theX;y1=theY;x2=x1+1;y2=y1+1;var layer=document.getElementById(mapDivId);jg.clear();limpiarEdicion();limpiarHistorico();limpiarBufferCirculo();document.onmousemove=updateMapDragging;document.onmouseup=stopMapDragging;}return false;}function georef1PointClick(e){getXY(e);var x1=theX-mleft;var y1=theY-mtop;calculateAltitud(x1,y1);return false;}function georef2PointClick(e){getXY(e);var x1=theX-mleft;var y1=theY-mtop;calculaRefCatOVC_customGeorref(x1,y1);return false;}function pointClick(e){getXY(e);var x1=theX-mleft;var y1=theY-mtop;identify(x1,y1);return false;}function pointClickDescarga(e){getXY(e);var x1=theX-mleft;var y1=theY-mtop;descarga(x1,y1);return false;}function pointClickBufferCirculo(e){getXY(e);var x1=theX-mleft;var y1=theY-mtop;doBufferCirculo(x1,y1);return false;}var valueRadius=-1;var xRadius=-1;var yRadius=-1;var xRadiusGranjas=-1;var yRadiusGranjas=-1;function doBufferCirculo(x1,y1){var coordClick=getMapXY(x1,y1);xRadius=coordClick[0];yRadius=coordClick[1];valueRadius=document.getElementById('radiusTextId').value;valueRadius=replaceChar(valueRadius,',','.');if(!isNaN(valueRadius)){var tamPixel=Math.abs(maxx-minx)/mwidth;var numPixels=valueRadius/tamPixel;if((numPixels>0)&&(numPixels*2<=Math.max(mwidth,mheight))){jgCircle.clear();jgCircle.drawEllipse(x1-numPixels,y1-numPixels,numPixels*2,numPixels*2);if(numPixels*2>10){jgCircle.drawLine(x1-4,y1-4,x1+4,y1+4);jgCircle.drawLine(x1+4,y1-4,x1-4,y1+4);}jgCircle.paint();}else{alert("El valor del radio debe ser inferior al tamaño del mapa actual")}}else{alert("El valor del radio debe ser un número");}}function pointClickOVC(e){getXY(e);var x1=theX-mleft;var y1=theY-mtop;identifyOVC(x1,y1);return false;}function updateDragging(e){if(dragging){getXY(e);x2=theX;y2=theY;if(x2<mleft){x2=mleft;}if(x2>mleft+mwidth){x2=mleft+mwidth;}if(y2<mtop){y2=mtop;}if(y2>mtop+mheight){y2=mtop+mheight;}setClip();}return false;}function updateMapDragging(e){if(panning){getXY(e);x2=theX;y2=theY;if(x2<mleft)x2=mleft;if(x2>mleft+mwidth)x2=mleft+mwidth;if(y2<mtop)y2=mtop;if(y2>mtop+mheight)y2=mtop+mheight;var dx=x2-x1;var dy=y2-y1;var cLeft=-dx;var cTop=-dy;var cRight=mwidth;var cBottom=mheight;if(dx>0){cLeft=0;cRight=mwidth-dx;}if(dy>0){cTop=0;cBottom=mheight-dy;}moveLayer(mapDivId,dx,dy);panClipLayer(mapDivId,cLeft,cTop,cRight,cBottom);}return false;}function stopDragging(e){if(dragging){dragging=false;getXY(e);document.onmousemove=null;document.onmouseup=null;hideZoomBox();setClip();zleft-=mleft;zright-=mleft;zbottom-=mtop;ztop-=mtop;if(((zright-zleft)==1)&&((zbottom-ztop)==1)){if(activeTool=="zoomIn"){fixedZoomIn(zright,zbottom,1);}else{fixedZoomOut(zright,zbottom,1);}}else{zoom(zleft,zbottom,zright,ztop);}return false;}}function stopMapDragging(e){if(panning){panning=false;getXY(e);document.onmousemove=null;document.onmouseup=null;var ixOffset=x1-x2;var iyOffset=y2-y1;resetAfterPan();pan(ixOffset,iyOffset);return false;}}function resetAfterPan(){moveLayer(mapDivId,0,0);clipLayer2(mapDivId,0,0,mwidth,mheight);document.getElementById('theImage').onload=null;}function createLayer(name,inleft,intop,width,height,visible,content,zidx){var layer;_zidx=zidx||1;document.writeln('<div id="'+name+'" style="position:absolute; overflow:hidden; left:'+inleft+'px; top:'+intop+'px; width:'+width+'px; height:'+height+'px;'+'; z-index:'+_zidx+'; visibility:'+(visible?'visible;':'hidden;')+'">');document.writeln(content);document.writeln('</div>');}function createMapContainer(name,content,itop,ileft,iwidth,iheight,border,mapclass){if(!isIE){iwidth=iwidth-(2*border);iheight=iheight-(2*border);}document.writeln('<div id="'+name+'" class="'+mapclass+'" style="position:absolute; overflow:hidden; left:'+ileft+'px; top:'+itop+'px; width:'+iwidth+'px; height:'+iheight+'px;'+';visibility:visible;border-width:'+border+'">');document.writeln(content);document.writeln('</div>');}function updateMapContainer(name,iwidth,iheight){if(!isIE){iwidth=iwidth-(2*borderr);iheight=iheight-(2*borderr);}document.getElementById(name).style.width=iwidth+"px";document.getElementById(name).style.height=iheight+"px";}function getLayer(name){var theObj=document.getElementById(name);if(theObj!=null){return theObj.style}else{return(null);}}function isVisible(name){var layer=getLayer(name);if(isNav&&layer.visibility=="show"){return(true);}if(isIE&&layer.visibility=="visible"){return(true);}return(false);}function getXY(e){if(isNav){theX=e.pageX;theY=e.pageY;}else{theX=event.clientX+document.body.scrollLeft;theY=event.clientY+document.body.scrollTop;}return false;}function getXY2(e){if(isNav){theX=e.pageX;theY=e.pageY;theX=theX-mleft;theY=theY-mtop;}else{theX=event.clientX+document.body.scrollLeft;theY=event.clientY+document.body.scrollTop;theX=theX-mleft-borderr;theY=theY-mtop-borderr;}return false;}function showZoomBox(left,top,right,bottom){clipLayer("zoomboxTop",left,top,right,bottom);clipLayer("zoomboxLeft",left,top,right,bottom);clipLayer("zoomboxRight",left,top,right,bottom);clipLayer("zoomboxBottom",left,top,right,bottom);showLayer("zoomboxTop");showLayer("zoomboxLeft");showLayer("zoomboxRight");showLayer("zoomboxBottom");}function hideZoomBox(){window.scrollTo(0,0);hideLayer("zoomboxTop");hideLayer("zoomboxLeft");hideLayer("zoomboxRight");hideLayer("zoomboxBottom");}function moveLayer(name,x,y){var layer=getLayer(name);layer.left=x+"px";layer.top=y+"px";}function setLayerBackgroundColor(name,color){var layer=getLayer(name);layer.backgroundColor=color;}function hideLayer(name){var layer=getLayer(name);layer.visibility="hidden";}function showLayer(name){var layer=getLayer(name);layer.visibility="visible";}function clipLayer2(name,clipleft,cliptop,clipright,clipbottom){var layer=getLayer(name);layer.clip='rect('+cliptop+' '+clipright+' '+clipbottom+' '+clipleft+')';}function clipLayer(name,clipleft,cliptop,clipright,clipbottom){var layer=getLayer(name);var newWidth=clipright-clipleft;var newHeight=clipbottom-cliptop;layer.height=newHeight;layer.width=newWidth;layer.top=cliptop+"px";layer.left=clipleft+"px";}function panClipLayer(name,clipleft,cliptop,clipright,clipbottom){var layer=getLayer(name);if(layer!=null){layer.clip='rect('+cliptop+' '+clipright+' '+clipbottom+' '+clipleft+')';}return false;}function setClip(){var inSize=3;var lSize=parseInt(inSize)-1;if(lSize<1)lSize=1;var tempX=x1;var tempY=y1;if(x1>x2){zright=x1;zleft=x2;}else{zleft=x1;zright=x2;}if(y1>y2){zbottom=y1;ztop=y2;}else{ztop=y1;zbottom=y2;}if((x1!=x2)&&(y1!=y2)){clipLayer("zoomboxTop",zleft,ztop,zright,ztop+lSize);clipLayer("zoomboxLeft",zleft,ztop,zleft+lSize,zbottom);clipLayer("zoomboxRight",zright-lSize,ztop,zright,zbottom);clipLayer("zoomboxBottom",zleft,zbottom-lSize,zright,zbottom);}return false;}var isMoving=false;var idx,idy;var idLayer;function getMapScale(formated){return(getMapScale2(formated,minx,maxx,mwidth));}function getMapScale2(formated,_minx,_maxx,_mwidth){var tempScale=(_maxx-_minx)/_mwidth;var tempFactor=96;var inchPerMeter=39.4;if(formated){var scaleValue=parseInt((tempScale*tempFactor*inchPerMeter)+0.5);var scale=scaleValue.toString(10);var formatedScale="";var scaleLength=scale.length;if(scaleLength>3){var rightPos=scaleLength;formatedScale=scale.substring(rightPos-3,rightPos);for(rightPos-=3;rightPos>3;rightPos-=3){formatedScale=scale.substring(rightPos-3,rightPos)+"."+formatedScale;}formatedScale=scale.substring(0,rightPos)+"."+formatedScale;}else{formatedScale=scale;}return"1:"+formatedScale;}else{return parseInt((tempScale*tempFactor*inchPerMeter)+0.5);}}var resultCount=-1;var initialRecord=-1;var nomCalleToFind="";var numPortalToFind=-1;var cviaPortalToFind=-1;var locCallejeroToFind="";var txtToQuery="";var txtToQueryNoExact="";var featureCountLimit=30;var nomTopoToFind="";var theMuniTopoToFind="";var numFaseTopo=0;var numMaxFaseTopo=3;var resultTopo=new Array();var seguirBuscandoTopo=true;var queryUrl="";var bestMinx,bestMiny,bestMaxx,bestMaxy;function initialQuery(findQuery,activeLyr,newQueryURL){ActiveLayer=activeLyr;var axl=getIdRequestQuery(findQuery,false,0,"");if(newQueryURL){queryUrl=newQueryURL;}else{queryUrl=defaultQueryUrl;}if(debugOn){alert("consultando a la URL: "+queryUrl);}http=getHTTPObject();if((http!=null)){http.open("POST",queryUrl,true);http.onreadystatechange=parseInitialResultQuery;isWorking=true;muestraLayerLoading();if(debugOn){alert("enviando la consulta: \n"+axl);}http.send(axl);}}function query(txt,txtNoExact,activeLyr,isExact,newQueryURL){resultCount=-1;initialRecord=1;nomCalleToFind="";numPortalToFind=-1;cviaPortalToFind=-1;locCallejeroToFind="";txtToQuery=txt;txtToQueryNoExact=txtNoExact;if(newQueryURL){queryUrl=newQueryURL;}else{queryUrl=defaultQueryUrl;}ActiveLayer=activeLyr;if(isExact){sendIdRequestQuery(txt,true,initialRecord,false,isExact,false,"");}else{sendIdRequestQuery(txtNoExact,true,initialRecord,false,isExact,false,"");}}function queryToponimo(theValue,theMuni){resultCount=-1;initialRecord=1;seguirBuscandoTopo=true;nomTopoToFind=theValue;theMuniTopoToFind=theMuni;numFaseTopo=-1;resultTopo=new Array();doNextQueryTopo();}function doNextQueryTopo(){queryUrl=defaultQueryUrl;numFaseTopo++;if((numFaseTopo>=numMaxFaseTopo)||(resultCount>featureCountLimit)){seguirBuscandoTopo=false;}if(seguirBuscandoTopo){txtToQuery=getQueryToponimo(nomTopoToFind,theMuniTopoToFind,numFaseTopo);ActiveLayer="Toponimo";sendIdRequestQuery(txtToQuery,true,initialRecord,false,false,false,"",true);}else{if(resultCount==0){alert("No se han encontrado coincidencias");queryResultsWin.hide();}else{if(debugOn){alert("Finalmente se han encontrado un total de "+resultCount+" resultados de toponimos");}updateSeleccionCandidatos(null,false,false,true,false);}}}function queryCallejero(calle,loc,numportal,isExact){resultCount=-1;initialRecord=1;nomCalleToFind=calle;numPortalToFind=numportal;locCallejeroToFind=loc;txtToQuery=getQueryCallejero(nomCalleToFind,locCallejeroToFind,isExact);queryUrl=defaultQueryUrl;ActiveLayer="BusCallUrb";sendIdRequestQuery(txtToQuery,true,initialRecord,true,isExact,false,"");}function locatePortal(numVia,numportal,isExact){muestraLayerLoading();cviaPortalToFind=numVia;numPortalToFind=numportal;if(isExact){txtToQuery=getQueryPortal(numVia,numportal,numportal);}else{txtToQuery=getQueryPortal(numVia,numportal-5,(numportal-0)+5);}ActiveLayer="TroidesV";sendIdRequestQuery(txtToQuery,true,initialRecord,true,isExact,true,"NUMERO");}function sendIdRequestQuery(findQuery,countOnly,beginRecord,isCallejero,isExact,isPortal,fieldOrderBy,isToponimo){var axl=getIdRequestQuery(findQuery,countOnly,beginRecord,fieldOrderBy);if(debugOn){alert("consultando a la URL: "+queryUrl);}http=getHTTPObject();if((http!=null)){http.open("POST",queryUrl,true);if(isCallejero){if(isPortal){if(countOnly){if(isExact){http.onreadystatechange=parseResultQueryForCountPortalExacto;}else{http.onreadystatechange=parseResultQueryForCountPortalNoExacto;}}else{http.onreadystatechange=parseResultQueryPortal;}}else{if(countOnly){if(isExact){http.onreadystatechange=parseResultQueryForCountCallejeroExacto;}else{http.onreadystatechange=parseResultQueryForCountCallejeroNoExacto;}}else{http.onreadystatechange=parseResultQueryCallejero;}}}else if(isToponimo){if(countOnly){http.onreadystatechange=parseResultQueryForCountTopo;}else{http.onreadystatechange=parseResultQueryTopo;}}else{if(countOnly){if(isExact){http.onreadystatechange=parseResultQueryForCountExacto;}else{http.onreadystatechange=parseResultQueryForCountNoExacto;}}else{http.onreadystatechange=parseResultQuery;}}isWorking=true;muestraLayerLoading();if(debugOn){alert("enviando la consulta: \n"+axl);}http.send(axl);}}function getIdRequestQuery(findQuery,countOnly,beginRecord,fieldOrderBy){var axl='<?xml version="1.0" encoding="UTF-8"?>';axl+='<ARCXML version="1.1">\n<REQUEST>\n<GET_FEATURES geometry="false" outputmode="xml" checkesc ="true" ';if(countOnly){axl+='envelope="false" skipfeatures="true">\n';}else{axl+='envelope="true" skipfeatures="false" beginrecord="'+beginRecord+'" featurelimit="'+featureCountLimit+'">\n';}axl+='<LAYER id="'+ActiveLayer+'" />';if(fieldOrderBy){axl+='<SPATIALQUERY subfields="'+getFields(ActiveLayer)+'" where="'+findQuery+'" order_by="ORDER BY '+fieldOrderBy+'" />';}else{axl+='<SPATIALQUERY subfields="'+getFields(ActiveLayer)+'" where="'+findQuery+'" />';}axl+='</GET_FEATURES>';axl+='</REQUEST>';axl+='</ARCXML>';return axl;}function parseResultQueryForCountExacto(){parseResultQueryForCount(true);}function parseResultQueryForCountNoExacto(){parseResultQueryForCount(false);}function parseResultQueryForCount(esExacto){if(http.readyState==4){if(http.status==200){var result=http.responseText;resultCount=getCountQuery(result);if(resultCount!=0){if(esExacto){sendIdRequestQuery(txtToQuery,false,initialRecord,false,false,false,"");}else{sendIdRequestQuery(txtToQueryNoExact,false,initialRecord,false,false,false,"");}}else{if(esExacto){if(debugOn){alert("busco por palabras independientes")}query(txtToQuery,txtToQueryNoExact,ActiveLayer,false);}else{alert("No se encontraron coincidencias");}}}else{alert("Error retreiving data");}}}function parseResultQueryForCountTopo(){if(http.readyState==4){if(http.status==200){var result=http.responseText;resultCountAux=getCountQuery(result);if(debugOn){alert("En la fase "+numFaseTopo+" he tenido "+resultCountAux+" y ya llevo de antes "+resultCount+" toponimos");}if(resultCount!=-1){resultCount+=resultCountAux;}else{resultCount=resultCountAux;}if(resultCount!=0){sendIdRequestQuery(txtToQuery,false,initialRecord,false,false,false,"",true);}else{if(numFaseTopo==0){updateSeleccionCandidatos(null,false,false,true,false);}doNextQueryTopo();}}else{alert("Error retreiving data");}}}function parseResultQueryForCountCallejeroExacto(){parseResultQueryForCountCallejero(true);}function parseResultQueryForCountCallejeroNoExacto(){parseResultQueryForCountCallejero(false);}function parseResultQueryForCountCallejero(esExacto){if(http.readyState==4){if(http.status==200){var result=http.responseText;resultCount=getCountQuery(result);if(debugOn){alert("num result "+resultCount);}if(resultCount==0){if(!esExacto){if(debugOn){alert("busco por palabras independientes")}queryCallejero(nomCalleToFind,locCallejeroToFind,numPortalToFind,false);}else{alert("No se localiza el nombre de vía");}}else{if(debugOn){alert("hay al menos 1 calle, busco para hacer join")}txtToQuery=getQueryCallejero(nomCalleToFind,locCallejeroToFind,esExacto);ActiveLayer="BusCallUrb";sendIdRequestQuery(txtToQuery,false,initialRecord,true,false,false,"");}}else{alert("Error retreiving data");}}}function parseResultQueryForCountPortalExacto(){parseResultQueryForCountPortal(true);}function parseResultQueryForCountPortalNoExacto(){parseResultQueryForCountPortal(false);}function parseResultQueryForCountPortal(esExacto){if(http.readyState==4){if(http.status==200){var result=http.responseText;resultCount=getCountQuery(result);if(debugOn){alert("num result "+resultCount);}if(resultCount==0){if(esExacto){if(debugOn){alert("busco por los portales cercanos de esa calle")}locatePortal(cviaPortalToFind,numPortalToFind,false);}else{alert("No se localiza ningún número de portal cercano al solicitado. Se muestra la calle completa.");if(((bestMaxx-bestMinx)>0.5)&&((bestMaxy-bestMiny)>0.5)){getMap(bestMinx,bestMiny,bestMaxx,bestMaxy);}else{doRecenterXYWithScale(bestMinx,bestMiny,1500);}}}else{if(debugOn){alert("hay al menos 1 portal, busco para hacer join")}txtToQuery="";if(esExacto){txtToQuery=getQueryPortal(cviaPortalToFind,numPortalToFind,numPortalToFind);}else{txtToQuery=getQueryPortal(cviaPortalToFind,numPortalToFind-5,(numPortalToFind-0)+5);}ActiveLayer="TroidesV";sendIdRequestQuery(txtToQuery,false,initialRecord,true,true,true,"");}}else{alert("Error retreiving data");}}}function parseResultQuery(){if(http.readyState==4){if(http.status==200){var result=http.responseText;if(debugOn){alert("RESULTADO:"+result);}processResultQuery(result,false,false,false);}else{alert("Error retreiving data");}}}function parseResultQueryTopo(){if(http.readyState==4){if(http.status==200){var result=http.responseText;if(debugOn){alert("RESULTADO:"+result);}resultTopo[numFaseTopo]=result;updateSeleccionCandidatos(null,false,false,true,false);doNextQueryTopo();}else{alert("Error retreiving data");}}}function parseResultQueryCallejero(){if(http.readyState==4){if(http.status==200){var result=http.responseText;if(debugOn){alert("RESULTADO:"+result);}processResultQuery(result,true,false,false);}else{alert("Error retreiving data");}}}function parseResultQueryPortal(){if(http.readyState==4){if(http.status==200){var result=http.responseText;if(debugOn){alert("RESULTADO:"+result);}processResultQuery(result,true,true,false);}else{alert("Error retreiving data");}}}function parseInitialResultQuery(){if(http.readyState==4){if(http.status==200){var result=http.responseText;if(debugOn){alert("RESULTADO:"+result);}resultCount=getCountQuery(result);processResultQuery(result,false,false,false);}else{alert("Error retreiving data");}}}function getCountQuery(theReply){var theCount;var startpos=0;var endpos=0;var pos=theReply.indexOf("FEATURECOUNT");var pos1=theReply.indexOf("count",pos+12);if(pos1!=-1){pos1+=7;var pos2=theReply.indexOf("\"",pos1);theCount=parseFloat(theReply.substring(pos1,pos2));}else{theCount=0;}
return theCount;}
var idSelectionLayer="";var selectionWhere="";var selectionType="";function processResultQuery(theReply,isCallejero,isPortal,isTopo,isGoogle){var endpos=1;reply=theReply;var notHideLayer=false;var posIni=reply.indexOf("<ENVELOPE ",endpos);var posFin=reply.indexOf("<ENVELOPE ",posIni+1);if(posIni==-1){alert("No se encontraron coincidencias");}else{if(resultCount==1){if(isCallejero&&!isPortal&&numPortalToFind!=""){if(debugOn){alert("hay 1 calle candidata");}
var posFie=reply.indexOf("<FIELDS ",endpos);startposFie=posFie+8;endposFie=reply.indexOf('" />',startposFie);selectedDataFie=reply.substring(startposFie,endposFie);cviaIndex=-1;if(selectedDataFie!=""){var fValue1=getFieldValuesQuery(selectedDataFie);var fName1=getFieldNamesQuery(selectedDataFie);for(var ii=0;ii<fName1.length;ii++){tempString=fName1[ii];if((shortenSDENames==true)&&(tempString.split(".").length>2)){nombreCampo=tempString.split(".")[tempString.split(".").length-1];}else{nombreCampo=tempString;}if(nombreCampo=="MUN_VIA"){cviaIndex=ii;}}}if(debugOn){alert("munvia"+fValue1[cviaIndex]);}posEnv=reply.indexOf("<ENVELOPE ",endpos);startposEnv=posEnv+10;endposEnv=reply.indexOf('"/>',startposEnv);envelopeData=reply.substring(startposEnv,endposEnv);bbox=new Array();if(envelopeData!=""){var fValueEnv=getFieldValuesQuery(envelopeData);var fNameEnv=getFieldNamesQuery(envelopeData);parseEnvelope(fNameEnv,fValueEnv,bbox);}
idSelectionLayer=ActiveLayer;posId=reply.indexOf(nombreCampoId+'="',endpos);startposId=posId+nombreCampoId.length+2;endposId=reply.indexOf('"',startposId);theId=reply.substring(startposId,endposId);selectionWhere=nombreCampoId+'='+theId;selectionType=LayerTypeById[ActiveLayer.toString().toUpperCase()];bestMinx=parseFloat(bbox["minx"]);bestMiny=parseFloat(bbox["miny"]);bestMaxx=parseFloat(bbox["maxx"]);bestMaxy=parseFloat(bbox["maxy"]);notHideLayer=true;locatePortal(fValue1[cviaIndex],numPortalToFind,true);}else{var posFie=reply.indexOf("<FIELDS ",endpos);startposFie=posFie+8;endposFie=reply.indexOf('" />',startposFie);selectedDataFie=reply.substring(startposFie,endposFie);var scaleIdx=-1;if(selectedDataFie!=""){var fValue1=getFieldValuesQuery(selectedDataFie);var fName1=getFieldNamesQuery(selectedDataFie);for(var ii=0;ii<fName1.length;ii++){tempString=fName1[ii];if((shortenSDENames==true)&&(tempString.split(".").length>2)){nombreCampo=tempString.split(".")[tempString.split(".").length-1];}else{nombreCampo=tempString;}if(nombreCampo=="ESCALA"){scaleIdx=ii;}}}posEnv=reply.indexOf("<ENVELOPE ",endpos);startposEnv=posEnv+10;endposEnv=reply.indexOf('"/>',startposEnv);envelopeData=reply.substring(startposEnv,endposEnv);bbox=new Array();if(envelopeData!=""){var fValueEnv=getFieldValuesQuery(envelopeData);var fNameEnv=getFieldNamesQuery(envelopeData);parseEnvelope(fNameEnv,fValueEnv,bbox);}
idSelectionLayer=ActiveLayer;posId=reply.indexOf(nombreCampoId+'="',endpos);startposId=posId+nombreCampoId.length+2;endposId=reply.indexOf('"',startposId);theId=reply.substring(startposId,endposId);selectionWhere=nombreCampoId+'='+theId;selectionType=LayerTypeById[ActiveLayer.toString().toUpperCase()];minx=parseFloat(bbox["minx"]);miny=parseFloat(bbox["miny"]);maxx=parseFloat(bbox["maxx"]);maxy=parseFloat(bbox["maxy"]);if(maxy<=200000){updateSeleccionCandidatos(reply,isCallejero,isPortal,isTopo,isGoogle);}else{if(((maxx-minx)>0.5)&&((maxy-miny)>0.5)){getMap(minx,miny,maxx,maxy);}else{if(isPortal){doRecenterXYWithScale(minx,miny,1000);}else{var scaleLevel=15000;if(scaleIdx!=-1){if(!isNaN(fValue1[scaleIdx])){if(fValue1[scaleIdx]>0){scaleLevel=fValue1[scaleIdx];}}}
doRecenterXYWithScale(minx,miny,scaleLevel);}}}}}else{updateSeleccionCandidatos(reply,isCallejero,isPortal,isTopo,isGoogle);}}
if(!notHideLayer){ocultaLayerLoading();}}
function processGoogleResults(jsonData){var jsonResults=JSON.parse(jsonData);var resultData=filtraResultados(jsonResults['results']);resultCount=resultData.length;if(resultCount<=0){alert("No se encontraron coincidencias");}else{if(resultCount==1){doRecenterGeogrXYWithScale(resultData[0]['geometry']['location']['lng'],resultData[0]['geometry']['location']['lat'],15000);}else{updateSeleccionCandidatos(resultData,false,false,false,true);}}}
function filtraResultados(resultList){var resultListFiltrado=new Array();var idx=0;var esValido=false;for(var ii=0;ii<resultList.length;ii++){var obj=resultList[ii]['address_components'];for(var jj=0;jj<obj.length;jj++){if(obj[jj]["long_name"]=="Aragón"){if(obj[jj]["types"][0]=="administrative_area_level_1"){esValido=true;}}
if(esValido){resultListFiltrado[idx]=resultList[ii];idx++;esValido=false;}}}
return resultListFiltrado;}
function doRecenterGeogrXYWithScale(theX,theY,theScale){var coords=coordTransform("EPSG:4326","EPSG:23030",theX,theY);doRecenterXYWithScale(coords[0],coords[1],theScale);}
function updateSeleccionCandidatos(reply,isCallejero,isPortal,isTopo,isGoogle){idContent=getHTMLUserSelection(reply,isCallejero,isPortal,isTopo,isGoogle);queryResultsWin.setcontent(idContent);queryResultsWin.settitle("Resultados de la búsqueda");queryResultsWin.show();}
function getHTMLCabeceraCandidato(reply,isCallejero,isPortal,isTopo,isGoogle){var idContent="";if(isGoogle){idContent+="<tr>";idContent+="<td><b>";idContent+="Nombre";idContent+="</b></td>";idContent+="</tr>";}else{idSelectionLayer=ActiveLayer;var listaFieldNames=mainFieldName[idSelectionLayer].split(' ');if(queryResultsFieldName[idSelectionLayer]){listaFieldNames=queryResultsFieldName[idSelectionLayer].split(' ');}
if(listaFieldNames.length>1){idContent+="<tr>";if(moreDetails[idSelectionLayer]){idContent+="<td style='width:20px'></td>";}
for(var jj=0;jj<listaFieldNames.length;jj++){idContent+="<td><b>";if(fieldAliasList2[idSelectionLayer][listaFieldNames[jj]]){idContent+=fieldAliasList2[idSelectionLayer][listaFieldNames[jj]];}else{idContent+=listaFieldNames[jj];}
idContent+="</b></td>";}
idContent+="</tr>";}}
return idContent;}
function getHTMLCandidato(reply,isCallejero,isPortal,isTopo,numFaseT,isGoogle){var idContent="";if(isGoogle){for(var ii=0;ii<resultCount;ii++){idContent+="<tr>";idContent+="<td class='item'>";idContent+="<a class='itemEnlace' href='javascript:";var scaleLevel=15000;idContent+="doRecenterGeogrXYWithScale("+reply[ii]['geometry']['location']['lng']+","+reply[ii]['geometry']['location']['lat']+", "+scaleLevel+");";mainFieldText=reply[ii]['formatted_address'];idContent+="' title='"+mainFieldText+"'>"+mainFieldText+"</a>";idContent+="<td class='item'>";idContent+=mainFieldText;idContent+="</td>";idContent+="</tr>";}}else{var endpos=1;var posEnv=reply.indexOf("<ENVELOPE ",endpos);var posFie=reply.indexOf("<FIELDS ",endpos);var evenOdd;var ii=0;idSelectionLayer=ActiveLayer;while(posEnv!=-1){if((ii%2)==0){evenOdd="evenRow";}else{evenOdd="oddRow";}
ii++;startposEnv=posEnv+10;endposEnv=reply.indexOf('" />',startposEnv);envelopeData=reply.substring(startposEnv,endposEnv);bbox=new Array();if(envelopeData!=""){var fValueEnv=getFieldValuesQuery(envelopeData);var fNameEnv=getFieldNamesQuery(envelopeData);parseEnvelope(fNameEnv,fValueEnv,bbox);}posId=reply.indexOf(nombreCampoId+'="',endpos);startposId=posId+nombreCampoId.length+2;if(posId==-1){posId=reply.indexOf(nombreCampoId2+'="',endpos);startposId=posId+nombreCampoId2.length+2;}endposId=reply.indexOf('"',startposId);theId=reply.substring(startposId,endposId);selectionType=LayerTypeById[ActiveLayer.toString().toUpperCase()];startposFie=posFie+8;endposFie=reply.indexOf('" />',startposFie);selectedDataFie=reply.substring(startposFie,endposFie);if(selectedDataFie!=""){var fValue1=getFieldValuesQuery(selectedDataFie);var fName1=getFieldNamesQuery(selectedDataFie);idContent+=displayIdResultQuery(evenOdd,fName1,fValue1,bbox,theId,isCallejero,isPortal,numPortalToFind,idSelectionLayer,isTopo,numFaseT);}reply=reply.substring(endposFie);posEnv=reply.indexOf("<ENVELOPE ",1);posFie=reply.indexOf("<FIELDS ",1);}}return idContent;}function getHTMLUserSelection(reply,isCallejero,isPortal,isTopo,isGoogle){var idContent='';if(isTopo){if(seguirBuscandoTopo){idContent+='<p align="center"><b>Se han encontrado '+resultCount+' coincidencias.</b></p>';idContent+='<p align="center">Buscando top&oacute;nimos similares.</p><br/>';idContent+='<p align="center"><img src="images/loadingWMS.gif" alt="Espere por favor..." /></p>';}else{idContent+='<p align="center"><b>B&uacute;squeda finalizada.</b></p>';if(resultCount>featureCountLimit){idContent+='<p align="center">Se han encontrado m&aacute;s de '+featureCountLimit+' resultados.</p>';idContent+='<p align="center">Si no ha obtenido el resultado deseado, redefina el criterio de la b&uacute;squeda.</p><br/>';}else{idContent+='<p align="right">Se han encontrado '+resultCount+' resultados.</p>';}}}else{idContent+='<p align="center">Se han encontrado '+resultCount+' coincidencias</p>';idContent+='<p align="center">Mostrando resultados '+(initialRecord)+' a '+Math.min(initialRecord+featureCountLimit-1,resultCount)+'</p>';}idContent+='Seleccione uno de los siguientes elementos:';idContent+="<table align='center' width='90%' cellpadding='5' cellspacing='0' class='item' style='table-layout:fixed'>";if(isTopo){idContent+=getHTMLCabeceraCandidato(resultTopo[0],isCallejero,isPortal,isTopo,isGoogle);for(var ii=0;ii<numMaxFaseTopo;ii++){if(resultTopo[ii]!=null){idContent+=getHTMLCandidato(resultTopo[ii],isCallejero,isPortal,isTopo,ii,isGoogle);}}}else{idContent+=getHTMLCabeceraCandidato(resultTopo[ii],isCallejero,isPortal,isTopo,isGoogle);idContent+=getHTMLCandidato(reply,isCallejero,isPortal,isTopo,0,isGoogle);}idContent+="</table>";if(!isTopo){idContent+="<p>";idContent+="<center>";var numPaginasResultado=Math.ceil(resultCount/featureCountLimit);var currentPage=Math.floor((initialRecord-1)/featureCountLimit)+1;var validPageMin=Math.max(1,currentPage-10);var validPageMax=Math.min(numPaginasResultado,currentPage+10);if(currentPage<10){validPageMin=1;validPageMax=Math.min(numPaginasResultado,20);}if(currentPage>(numPaginasResultado-10)){validPageMin=Math.max(numPaginasResultado-20,1);validPageMax=numPaginasResultado;}if(validPageMin!=1){idContent+=getNavigationCodeHTML(1,currentPage);idContent+="...";}for(var kk=validPageMin;kk<=validPageMax;kk++){idContent+=getNavigationCodeHTML(kk,currentPage);}if(validPageMax!=numPaginasResultado){idContent+="...";idContent+=getNavigationCodeHTML(numPaginasResultado,currentPage);}idContent+="</center>";idContent+="</p>";}return idContent;}function getNavigationCodeHTML(kk,currentPage){var idContent="";if(kk==currentPage){idContent+="<b>";idContent+="<a align='center' class='itemEnlace' href='javascript:navigateResultsPage("+kk+")' title='Ir a la p&aacute;gina "+kk+" de resultados'>"+kk+"</a>&nbsp;";idContent+="</b>";}else{idContent+="<a align='center' class='itemEnlace' href='javascript:navigateResultsPage("+kk+")' title='Ir a la p&aacute;gina "+kk+" de resultados'>"+kk+"</a>&nbsp;";}return idContent;}function navigateResultsPage(numPage){initialRecord=((numPage-1)*featureCountLimit)+1;sendIdRequestQuery(txtToQuery,false,initialRecord,false,false,false,"");}function previousResultQuery(){initialRecord=initialRecord-featureCountLimit;sendIdRequestQuery(txtToQuery,false,initialRecord,false,false,false,"");}function nextResultQuery(){initialRecord=initialRecord+featureCountLimit;sendIdRequestQuery(txtToQuery,false,initialRecord,false,false,false,"");}function getFieldNamesQuery(recordString){var theStuff=new String(recordString);var theList=theStuff.split('" ');var fName1=new Array();for(var f=0;f<theList.length;f++){var v=theList[f].split('="');fName1[f]=v[0];}return fName1;}function getFieldValuesQuery(recordString){var theStuff=new String(recordString);var theList=theStuff.split('" ');var fValue1=new Array();for(var f=0;f<theList.length;f++){var v=theList[f].split('="');if((v[1]=="")||(v[1]==null))v[1]="&nbsp;";fValue1[f]=v[1];}return fValue1;}function parseEnvelope(fName1,fValue1,bbox){for(var ii=0;ii<fValue1.length;ii++){nombreCampo=fName1[ii];valorCampo=fValue1[ii];bbox[nombreCampo]=valorCampo;}}function changeId(_theId){selectionWhere=nombreCampoId+'='+_theId;}function displayIdResultQuery(evenOdd,fName1,fValue1,bbox,_id,isCallejero,isPortal,numPortalToFind,idLayer,isTopo,numFaseT){var idContent='';var listaIndexMainField=new Array();var listaFieldNames=mainFieldName[idLayer].split(' ');if(queryResultsFieldName[idLayer]){listaFieldNames=queryResultsFieldName[idLayer].split(' ');}var cviaIndex=-1;var moreDetailsCampo=moreDetails[idLayer]||"";var moreDetailsIdx=-1;var scaleIdx=-1;for(var ii=0;ii<fName1.length;ii++){tempString=fName1[ii];if((shortenSDENames==true)&&(tempString.split(".").length>2)){nombreCampo=tempString.split(".")[tempString.split(".").length-1];}else{nombreCampo=tempString;}if(isIncluded(listaFieldNames,nombreCampo,listaFieldNames.length)){listaIndexMainField[nombreCampo]=ii;}if(isCallejero){if(nombreCampo=="MUN_VIA"){cviaIndex=ii;}}if(nombreCampo=="ESCALA"){scaleIdx=ii;}if(moreDetailsCampo==nombreCampo){moreDetailsIdx=ii;}}var idEnlace=_id;if(isTopo){idEnlace=_id+"_"+numFaseT;}idContent+="<tr>";_minx=parseFloat(bbox["minx"]);_miny=parseFloat(bbox["miny"]);_maxx=parseFloat(bbox["maxx"]);_maxy=parseFloat(bbox["maxy"]);isFirst=true;for(var jj=0;jj<listaFieldNames.length;jj++){if(isFirst){isFirst=false;if(moreDetailsIdx!=-1){if((fValue1[moreDetailsIdx]!="")&&(fValue1[moreDetailsIdx]!="&nbsp;")){idContent+="<td class='item' style='width:20px'>";idContent+="<a id='detalles"+idEnlace+"Link' class='itemEnlace' href='javascript:toggleZoneCarpeta(\"detalles"+idEnlace+"\", \"detalles\")' title='Mostrar detalles'>";idContent+="<img src='imagesTOC/old_icon_closed.gif' border='0'></img></a>";idContent+="</td>";}else{idContent+="<td>";idContent+="</td>";}}var generateLink=true;if(_maxy<=200000){generateLink=false;}if(generateLink){idContent+="<td class='item'>";idContent+="<a class='itemEnlace' href='javascript:";if(isCallejero&&!isPortal&&numPortalToFind!=""){idContent+="locatePortal(\""+fValue1[cviaIndex]+"\","+numPortalToFind+", true);";}else{if(((_maxx-_minx)>0.5)&&((_maxy-_miny)>0.5)){idContent+="changeId("+_id+");getMap("+_minx+","+_miny+",";idContent+=_maxx+","+_maxy+");";}else{if(isPortal){idContent+="changeId("+_id+");doRecenterXYWithScale("+_minx+","+_miny+", 1000);";}else{var scaleLevel=15000;if(scaleIdx!=-1){if(!isNaN(fValue1[scaleIdx])){if(fValue1[scaleIdx]>0){scaleLevel=fValue1[scaleIdx];}}}idContent+="changeId("+_id+");doRecenterXYWithScale("+_minx+","+_miny+", "+scaleLevel+");";}}}mainFieldText=corrigeCaracteresExtranos(fValue1[listaIndexMainField[listaFieldNames[jj]]]);idContent+="' title='"+mainFieldText+"'>"+mainFieldText+"</a>";}else{idContent+="<td class='item'>";mainFieldText=corrigeCaracteresExtranos(fValue1[listaIndexMainField[listaFieldNames[jj]]]);idContent+=mainFieldText;}}else{idContent+="<td class='item'>";mainFieldText=corrigeCaracteresExtranos(fValue1[listaIndexMainField[listaFieldNames[jj]]]);idContent+=mainFieldText;}idContent+="</td>";}idContent+="</tr>";if(moreDetailsIdx!=-1){if((fValue1[moreDetailsIdx]!="")||(fValue1[moreDetailsIdx]!="&nbsp;")){idContent+="<tr id='detalles"+idEnlace+"Table' style='display:none'>";idContent+="<td class='item' style='width:20px;visibility:hidden;'>";idContent+="<img src='imagesTOC/old_icon_closed.gif' border='0'></img>";idContent+="</td>";idContent+="<td colspan='"+(listaFieldNames.length)+"'><div style='width:"+((queryResultsWin.sx*0.9)-40)+"px'>";idContent+=corrigeCaracteresExtranos(fValue1[moreDetailsIdx]);idContent+="</div>";idContent+="</td>";idContent+="</tr>";}}return idContent;}var findXCoordUsr="";var findYCoordUsr="";function input_onkeypress(evt){if(isEnterKey(evt)){doSearch();}}function replaceChar(entry,oldCh,newCh){var result=entry;var posAnt=-1;var posActual=result.indexOf(oldCh);while((posActual!=-1)&&(posAnt!=posActual)){result=result.replace(oldCh,newCh);posAnt=posActual;posActual=result.indexOf(oldCh);}return result;}function corrigeCaracteresExtranos(entry){entry=replaceChar(entry,'Ã¡','&aacute;');entry=replaceChar(entry,'Ã©','&eacute;');entry=replaceChar(entry,'Ã­','&iacute;');entry=replaceChar(entry,'Ã³','&oacute;');entry=replaceChar(entry,'Ãº','&uacute;');entry=replaceChar(entry,'Ã?','&Aacute;');entry=replaceChar(entry,'É','&Eacute;');entry=replaceChar(entry,'Ã?','&Iacute;');entry=replaceChar(entry,'Ã“','&Oacute;');entry=replaceChar(entry,'Ú','&Uacute;');entry=replaceChar(entry,'Ã?','&Auml;');entry=replaceChar(entry,'Ã¤','&auml;');entry=replaceChar(entry,'Ã«','&euml;');entry=replaceChar(entry,'Ã¯','&iuml;');entry=replaceChar(entry,'Ã¼','&uuml;');entry=replaceChar(entry,'Ãœ','&Uuml;');entry=replaceChar(entry,'Ã±','&ntilde;');entry=replaceChar(entry,'Ã‘','&Ntilde;');entry=replaceChar(entry,'Ã€','&Agrave;');entry=replaceChar(entry,'Ã ','&agrave;');entry=replaceChar(entry,'Ã¨','&egrave;');entry=replaceChar(entry,'Ã²','&ograve;');entry=replaceChar(entry,'Ã§','&ccedil;');entry=replaceChar(entry,'Ã‡','&Ccedil;');entry=replaceChar(entry,'Â´','&acute;');entry=replaceChar(entry,'â€™','&#39;');entry=replaceChar(entry,'â€˜','&#39;');entry=replaceChar(entry,'Âº','&ordm;');entry=replaceChar(entry,'Âª','&ordf;');entry=replaceChar(entry,'Â¡','&iexcl;');return entry;}function normalizaCadenaSimple(entry){entry=replaceChar(entry,'á','a');entry=replaceChar(entry,'é','e');entry=replaceChar(entry,'í','i');entry=replaceChar(entry,'ó','o');entry=replaceChar(entry,'ú','u');entry=replaceChar(entry,'Á','A');entry=replaceChar(entry,'É','E');entry=replaceChar(entry,'Í','I');entry=replaceChar(entry,'Ó','O');entry=replaceChar(entry,'Ú','U');return entry;}function normalizaCadena(entry){entry=normalizaCadenaSimple(entry);entry=replaceChar(entry,'ü','ü');entry=replaceChar(entry,'Ü','Ü');entry=replaceChar(entry,'ñ','ñ');entry=replaceChar(entry,'Ñ','Ñ');return entry;}function normalizaCadenaURL(entry){entry=normalizaCadena(entry);entry=replaceChar(entry,'%E1','a');entry=replaceChar(entry,'%E9','e');entry=replaceChar(entry,'%ED','i');entry=replaceChar(entry,'%F3','o');entry=replaceChar(entry,'%FA','u');entry=replaceChar(entry,'%FC','u');entry=replaceChar(entry,'%C1','a');entry=replaceChar(entry,'%C9','e');entry=replaceChar(entry,'%CD','i');entry=replaceChar(entry,'%D3','o');entry=replaceChar(entry,'%DA','u');entry=replaceChar(entry,'%DC','u');entry=replaceChar(entry,'%20',' ');entry=replaceChar(entry,'%F1','ñ');entry=replaceChar(entry,'%D1','ñ');return entry;}function geocodeGoogle(nombre){var nombre2=nombre.replace(" ","+");var details_url=server+"/googleGeocode?address="+nombre2+"&sensor=false";http=getHTTPObject();if((http!=null)){http.open("GET",details_url,true);http.onreadystatechange=parseGoogleResults;muestraLayerLoading();if(debugOn){alert("enviando la consulta: \n"+details_url);}http.send(null);}}function parseGoogleResults(){if(http.readyState==4){if(http.status==200){var jsonData=http.responseText;processGoogleResults(jsonData);}else{alert("Ocurrio un problema con la consulta a Google Maps.");}ocultaLayerLoading();}}function doSearch(){limpiaAutocomplete();combo=document.getElementById('cboTipoBusqueda');tipoBusqueda=combo.options[combo.selectedIndex].value;theQuery=null;switch(tipoBusqueda){case'Z':geocodeGoogle(document.getElementById('textoBusqueda').value);break;case'U':doNormalQuery('getQueryParcelaUrbana','BusParUrb','laRefCatU');break;case'R':txt=getQueryParcelaRustica();if(txt!=""){query(txt,txt,'ParRus',false);}else{alert("Introduzca un valor");}break;case'C':theName=document.getElementById('calleBus').value;theName=normalizaCadena(theName);theLoc=document.getElementById('localidadBus').value;theLoc=normalizaCadena(theLoc);thePortal=document.getElementById('portalBus').value;if(theName==""){alert("Introduzca un valor en el campo Nombre vía");}else if(theLoc==""){alert("Introduzca un valor en el campo Municipio");}else{queryCallejero(theName,theLoc,thePortal,true);}break;case'S':theQuery=getQuerySIGPAC();if(theQuery!=''){query(theQuery,theQuery,"ParSIGPAC",false);}break;case'T':theX=document.getElementById('utmXBus').value;theY=document.getElementById('utmYBus').value;comboSRS=document.getElementById('cboSRS');if((theX!="")&&(theY!="")){if((!isNaN(theX))&&(!isNaN(theY))){theSRS=comboSRS.options[comboSRS.selectedIndex].value;doXYQuery(theX,theY,theSRS);}else{alert("Los valores introducidos no son correctos. Deben ser números");}}else{alert("Introduzca un valor");}break;case'W':theName=document.getElementById('topoBus').value;theMun=document.getElementById('muniBus').value;theMun=normalizaCadena(theMun);if(theName!=""){queryToponimo(theName,theMun);}else{alert("Introduzca un valor");}break;case'A':doNormalQuery('getQueryComarca','Comarca','textoComarca');break;case'M':doNormalQuery('getQueryMunicipio','BusMun','textoMuni');break;case'Q':doNormalNumericQuery('getQueryCuadricula50K','Cuad50k','textoBusqueda');break;case'K':theValue=document.getElementById('textoBusqueda').value;if(theValue!=""){var words=theValue.split('-');if(words.length!=2){alert("El valor introducido no es correcto. Debe escribir el número de la hoja 50000, seguida de un guión y seguido del número de la hoja 5000");}else{if(!isNaN(words[0])&&!isNaN(words[1])){txt=getQueryCuadricula5K(theValue);query(txt,txt,'Cuad5k',false);}else{alert("El valor introducido no es correcto. Deben ser números");}}}else{alert("Introduzca un valor");}break;case'H':doNormalQuery('getQueryCuadricula10K','CuaUTM10k','textoBusqueda');break;case'G':alert("Acceso por coordenadas geográficas no disponible en este momento");break;case'L':doNormalQuery('getQueryLocalidad','Localidad','textoLocali');break;case'N':doNormalQuery('getQueryCatastroMinero','CatMin','textoBusqueda');break;case'MA':doNormalQuery('getQueryMA',getIdCapaActivaMA(),'textoBusquedaMA',queryUrlMA);break;default:alert("Tipo de búsqueda desconocido: "+tipoBusqueda);}}function getQueryMA(theValue){var combo=document.getElementById('cboTipoBusquedaMA');var tipoBusqueda=combo.options[combo.selectedIndex].value;switch(tipoBusqueda){case'VRTCC1':return'MATRICULA LIKE (\''+theValue+'\')';case'MONTES':return'MATRICULA LIKE (\''+theValue+'\')';case'CONSREP':return'MATRICULA LIKE (\''+theValue+'\')';case'VVVPP_R':return'MATRICULA LIKE (\''+theValue+'\')';case'ENP':return'CODIGO LIKE (\''+theValue+'\')';case'ZENP':return'CODIGO LIKE (\''+theValue+'\')';case'PORN':return'CODIGO LIKE (\''+theValue+'\')';case'APPE':return'CODIGO LIKE (\''+theValue+'\')';case'ACRIT':return'CODIGO LIKE (\''+theValue+'\')';case'HMD':return'CODIGO LIKE (\''+theValue+'\')';case'LICS':return'CODIGO LIKE (\''+theValue+'\')';case'ZEPAS':return'CODIGO LIKE (\''+theValue+'\')';case'ZECS':return'CODIGO LIKE (\''+theValue+'\')';case'COTOSPESCA':return'CMATCOTO LIKE (\''+theValue+'\')';default:alert("Tipo de búsqueda desconocido: "+tipoBusqueda);}return"";}function getIdCapaActivaMA(){var combo=document.getElementById('cboTipoBusquedaMA');var tipoBusqueda=combo.options[combo.selectedIndex].value;return tipoBusqueda;}function doNormalQuery(nomFuncQuery,nomCapa,idTxtBus,theQueryURL){theValue=document.getElementById(idTxtBus).value;theValue=normalizaCadena(theValue);if(theValue!=""){txt=eval(nomFuncQuery+"(\'"+theValue+"\')");query(txt,txt,nomCapa,false,theQueryURL);}else{alert("Introduzca un valor");}}function doNormalNumericQuery(nomFuncQuery,nomCapa,idTxtBus){theValue=document.getElementById(idTxtBus).value;if(theValue!=""){if(!isNaN(theValue)){txt=eval(nomFuncQuery+"(\'"+theValue+"\')");query(txt,txt,nomCapa,false);}else{alert("El valor introducido no es correcto. Debe ser un número");}}else{alert("Introduzca un valor");}}function doXYQuery(_theX,_theY,_theSRS){var theX=_theX;var theY=_theY;if(_theSRS!="EPSG:23030"){destino=coordTransform(_theSRS,"EPSG:23030",theX,theY);theX=destino[0];theY=destino[1];}if((theX<=limitLeft)||(theY<=limitBottom)||(theX>=limitRight)||(theY>=limitTop)){alert("La coordenada está fuera del rango del visor");}else{findXCoordUsr=theX;findYCoordUsr=theY;if(getMapScale(false)>25000){doRecenterXYWithScale(theX,theY,25000);}else{doRecenterXYWithScale(theX,theY,getMapScale(false));}}}function doRecenterXYWithScale(_theX,_theY,_scale){minx=parseFloat(_theX);maxx=parseFloat(_theX);miny=parseFloat(_theY);maxy=parseFloat(_theY);doZoomScale(_scale);setNewScale(_scale);}function abrirAyudaMunicipios(provTxt){switch(provTxt){case"Huesca":detailedQueryWin.loadcontent("municipios_catastrales_huesca.html");detailedQueryWin.settitle("Listado de municipios catastrales de Huesca");detailedQueryWin.show();break;case"Teruel":detailedQueryWin.loadcontent("municipios_catastrales_teruel.html");detailedQueryWin.settitle("Listado de municipios catastrales de Teruel");detailedQueryWin.show();break;case"Zaragoza":detailedQueryWin.loadcontent("municipios_catastrales_zaragoza.html");detailedQueryWin.settitle("Listado de municipios catastrales de Zaragoza");detailedQueryWin.show();break;default:break;}}function ayudaMunicipios_sigpac(){combo_laProvincia_sigpac=document.getElementById('laProvincia_sigpac');var provTxt=combo_laProvincia_sigpac.options[combo_laProvincia_sigpac.selectedIndex].value;abrirAyudaMunicipios(provTxt);}function ayudaMunicipios_parceR(){combo_laProvincia_parceR=document.getElementById('laProvincia_parceR');var provTxt=combo_laProvincia_parceR.options[combo_laProvincia_parceR.selectedIndex].value;abrirAyudaMunicipios(provTxt);}function ayudaProvincia(){alert("El 22 es el código correspondiente a Huesca.\nEl 44 es el código correspondiente a Teruel.\nEl 50 es el código correspondiente a Zaragoza.");}function getQueryParcelaUrbana(theValue){theQuery='CAT_U.PARCELA.REFCAT=&apos;'+theValue+'&apos;';return theQuery;}function getQueryParcelaRustica(){combo_laProvincia_parceR=document.getElementById('laProvincia_parceR');var provTxt=combo_laProvincia_parceR.options[combo_laProvincia_parceR.selectedIndex].value;prov=-1;switch(provTxt){case"Huesca":prov='22';break;case"Teruel":prov='44';break;case"Zaragoza":prov='50';break;default:alert('El valor introducido ('+provTxt+') no es correcto para el campo provincia');return'';}var muni=getNumericValueField('elMunicipio_parceR',3);if(isNaN(muni)){alert('El valor introducido ('+muni+') no es correcto para el campo municipio');return'';}var hoja=getNumericValueField('laHoja_parceR',5);if(isNaN(hoja)){alert('El valor introducido ('+hoja+') no es correcto para el campo hoja');return'';}hoja=parseInt(hoja);if(hoja==0){hoja=muni+'00';}var poligono=getNumericValueField('elPoligono_parceR',3);if(isNaN(poligono)){alert('El valor introducido ('+poligono+') no es correcto para el campo polígono');return'';}var parcela=getNumericValueField('laParcela_parceR',5);if(isNaN(parcela)){alert('El valor introducido ('+parcela+') no es correcto para el campo parcela');return'';}txt=prov+''+muni+''+hoja+''+poligono+''+parcela;theQuery="REFCAT = '"+txt+"'";return theQuery;}function getQuerySIGPAC(theValue){combo_laProvincia_sigpac=document.getElementById('laProvincia_sigpac');var provTxt=combo_laProvincia_sigpac.options[combo_laProvincia_sigpac.selectedIndex].value;prov=-1;switch(provTxt){case"Huesca":prov='22';break;case"Teruel":prov='44';break;case"Zaragoza":prov='50';break;default:alert('El valor introducido ('+provTxt+') no es correcto para el campo provincia');return'';}var muni=getNumericValueField('elMunicipio_sigpac',3);if(isNaN(muni)){alert('El valor introducido ('+muni+') no es correcto para el campo municipio');return'';}var agreg=getNumericValueField('elAgregado_sigpac',3);if(isNaN(agreg)){alert('El valor introducido ('+agreg+') no es correcto para el campo agregado');return'';}var zona=getNumericValueField('laZona_sigpac',2);if(isNaN(zona)){alert('El valor introducido ('+zona+') no es correcto para el campo zona');return'';}var poligono=getNumericValueField('elPoligono_sigpac',3);if(isNaN(poligono)){alert('El valor introducido ('+poligono+') no es correcto para el campo polígono');return'';}var parcela=getNumericValueField('laParcela_sigpac',5);if(isNaN(parcela)){alert('El valor introducido ('+parcela+') no es correcto para el campo parcela');return'';}txt=prov+''+muni+''+agreg+''+zona+''+poligono+''+parcela;theQuery="REFCAT = '"+txt+"'";return theQuery;}function getNumericValueField(idElement,numCerosARellenar){var val=document.getElementById(idElement).value;if(!isNaN(val)){var previo='';for(var i=val.length;i<numCerosARellenar;i++){previo='0'+previo;}val=previo+''+val;}return val;}commonWords=new Array();commonWords[0]="DE";commonWords[1]="LOS";commonWords[2]="LAS";commonWords[3]="SAN";commonWords[4]="EL";commonWords[5]="LA";commonWords[6]="DEL";function isCommonWord(theWord){if(theWord!=''){for(jj=0;jj<commonWords.length;jj++){if(commonWords[jj]==theWord.toUpperCase()){return true;}}}return false;}function getQueryPortal(munVia,portalBajo,portalAlto){theQuery='MUN_VIA=&apos;'+munVia+'&apos; AND NUMERO &gt;='+portalBajo+' AND NUMERO &lt;='+portalAlto;return theQuery;}function getQueryCallejero(theValue,theLoc,exact){theQuery='( ';var operadorLogico;if(exact){operadorLogico="AND";}else{operadorLogico="OR";}isFirst=true;words=theValue.split(' ');if(words.length>0){for(i=0;i<words.length;i++){if(!isCommonWord(words[i])){if(isFirst){theQuery+='(NOMVIA LIKE UPPER(&apos;%'+words[i]+'%&apos;))';isFirst=false;}else{theQuery+=operadorLogico+' (NOMVIA LIKE UPPER(&apos;%'+words[i]+'%&apos;))';}}}}theQuery+=') ';if(theLoc){theQuery+='AND D_MUN_INE LIKE UPPER(&apos;%'+theLoc+'%&apos;) ';}return theQuery;}function quitaCommonWords(theValue){var valorAObtener="";var isFirst=true;var words=theValue.split(' ');if(words.length>0){for(i=0;i<words.length;i++){if(!isCommonWord(words[i])){if(isFirst){valorAObtener+=words[i];isFirst=false;}else{valorAObtener+=" "+words[i];}}}}return valorAObtener;}function getQueryComarca(theValue){theQuery='FONETICA LIKE carto.f_fonetica(&apos;%'+theValue+'%&apos;)';return theQuery;}function getQueryMunicipio(theValue){theQuery='FONETICA LIKE carto.f_fonetica(&apos;%'+theValue+'%&apos;)';return theQuery;}function getQueryLocalidad(theValue){theQuery='FONETICA LIKE carto.f_fonetica(&apos;%'+theValue+'%&apos;)';return theQuery;}function getQueryToponimo(theValue,theMuni,fase){var theQuery="";switch(fase){case 0:theQuery='FONETICA = carto.f_fonetica(&apos; '+theValue+' &apos;)';break;case 1:theQuery='NOT FONETICA = carto.f_fonetica(&apos; '+theValue+' &apos;) AND FONETICA LIKE carto.f_fonetica(&apos;% '+theValue+' %&apos;)';break;case 2:theQuery='FONETICA LIKE carto.f_fonetica(&apos;%'+theValue+'%&apos;) AND NOT FONETICA LIKE carto.f_fonetica(&apos;% '+theValue+' %&apos;)';break;}if(theMuni!=""){theQuery+=' AND D_MUNI_INE LIKE UPPER(&apos;'+theMuni+'&apos;)';}return theQuery;}function getQueryCuadricula50K(theValue){theQuery='HOJA50=&apos;'+theValue+'&apos;';return theQuery;}function getQueryCuadricula5K(theValue){theQuery='HOJA50_H5=&apos;'+theValue+'&apos;';return theQuery;}function getQueryCuadricula10K(theValue){theQuery='CODIGO LIKE UPPER(&apos;'+theValue+'&apos;)';return theQuery;}function getQueryCatastroMinero(theValue){theQuery='N_SINACEN LIKE UPPER(&apos;%'+theValue+'%&apos;)';return theQuery;}function showOnlyOneZone(textId){document.getElementById('comarca_table').style.display='none';document.getElementById('muni_table').style.display='none';document.getElementById('locali_table').style.display='none';document.getElementById('parceR_table').style.display='none';document.getElementById('sigpac_table').style.display='none';document.getElementById('normal_table').style.display='none';document.getElementById('callejero_table').style.display='none';document.getElementById('utmXY_table').style.display='none';document.getElementById('parceU_table').style.display='none';document.getElementById('toponimo_table').style.display='none';document.getElementById('MA_table').style.display='none';limpiaAutocomplete();document.getElementById(textId).style.display='block';}function limpiaAutocomplete(){if(document.getElementById('tat_table')){document.body.removeChild(document.getElementById('tat_table'));}}function showNormalFindOption(txtEjemplo,txtToFind,txtBusqueda){document.getElementById('labelEjemplo').innerHTML=txtEjemplo;document.getElementById('textToFind').innerHTML=txtToFind;document.getElementById("textoBusqueda").value=txtBusqueda;showOnlyOneZone('normal_table');}function changeTipoBusqueda(){combo=document.getElementById('cboTipoBusqueda');tipoBusqueda=combo.options[combo.selectedIndex].value;switch(tipoBusqueda){case'Z':showNormalFindOption('Godojos','Nombre a buscar:','');break;case'U':showOnlyOneZone('parceU_table');break;case'R':showOnlyOneZone('parceR_table');break;case'C':showOnlyOneZone('callejero_table');actb(document.getElementById("localidadBus"),customarrayMuni);break;case'S':showOnlyOneZone('sigpac_table');break;case'Q':showNormalFindOption('286','Hoja a buscar:','');break;case'A':showOnlyOneZone('comarca_table');actb(document.getElementById("textoComarca"),customarrayComarca);break;case'M':showOnlyOneZone('muni_table');actb(document.getElementById("textoMuni"),customarrayMuni);break;case'K':showNormalFindOption('409-62','Hoja a buscar:','');break;case'H':showNormalFindOption('30TXK69','Hoja a buscar:','');break;case'T':showOnlyOneZone('utmXY_table');break;case'G':showNormalFindOption('N/A','','');break;case'W':showOnlyOneZone('toponimo_table');actb(document.getElementById("muniBus"),customarrayMuni);break;case'L':showOnlyOneZone('locali_table');actb(document.getElementById("textoLocali"),customarrayLocali);break;case'N':showNormalFindOption('Montse','Explotación a buscar:','');break;case'MA':showOnlyOneZone('MA_table');break;default:alert("Tipo de búsqueda desconocido");}}function changeTipoBusquedaMA(){var combo=document.getElementById('cboTipoBusquedaMA');var tipoBusqueda=combo.options[combo.selectedIndex].value;switch(tipoBusqueda){case'VRTCC1':case'MONTES':case'CONSREP':case'VVVPP_R':document.getElementById('textToFindMA').innerHTML="Matrícula:";break;default:document.getElementById('textToFindMA').innerHTML="Código:";}}var originador=null;function changeOriginador(){if(originador==null){originador='';}originador=window.prompt("Introduzca su nombre de usuario",originador);if(originador==null){originador='';}}function endGeoref(){clickPointX=new Array();clickPointY=new Array();screenClickPointX=new Array();screenClickPointY=new Array();clickCount=0;resetClick();}function finPointGeoref(){texto=window.prompt("Introduzca el texto asociado","");if((texto!=null)&&(texto!='')){attrib=new Array();attrib['text']=texto;attrib['escala']=getMapScale(false);attrib['originador']=originador;attrib['fecha']=new Date();attrib['SRS']="EPSG:23030";gg=new Point(clickPointX[0],clickPointY[0]);pointRecordset.addVectorialData(gg,attrib);}updateGeorefMapClicks(jgPoint,pointRecordset,jgPointLabel);endGeoref();}function finLineGeoref(){if(clickCount>=2){texto=window.prompt("Introduzca el texto asociado","");if((texto!=null)&&(texto!='')){attrib=new Array();attrib['text']=texto;attrib['escala']=getMapScale(false);attrib['originador']=originador;attrib['fecha']=new Date();attrib['SRS']="EPSG:23030";gg=new LineString();for(var ii=0;ii<clickCount;ii++){gg.addPoint(clickPointX[ii],clickPointY[ii]);}lineRecordset.addVectorialData(gg,attrib);updateGeorefMapClicks(jgLine,lineRecordset,jgLineLabel);}}else{alert("Para generar una línea debe haber al menos 2 puntos");}endGeoref();}function finPolGeoref(){if(clickCount>=3){texto=window.prompt("Introduzca el texto asociado","");if((texto!=null)&&(texto!='')){attrib=new Array();attrib['text']=texto;attrib['escala']=getMapScale(false);attrib['originador']=originador;attrib['fecha']=new Date();attrib['SRS']="EPSG:23030";gg=new LinearRing();for(var ii=0;ii<clickCount;ii++){gg.addPoint(clickPointX[ii],clickPointY[ii]);}gg.addPoint(clickPointX[0],clickPointY[0]);polRecordset.addVectorialData(gg,attrib);updateGeorefMapClicks(jgPol,polRecordset,jgPolLabel);}}else{alert("Para generar un polígono debe haber al menos 3 puntos");}endGeoref();}function finGeom(){switch(getTipoGeorref()){case'point':break;case'line':finLineGeoref();break;case'polygon':finPolGeoref();break;default:break;}}function deleteAllGeom(tipoGeom){if(window.confirm("¿Está seguro de que desea borrar todos los elementos?")){clickPointX=new Array();clickPointY=new Array();screenClickPointX=new Array();screenClickPointY=new Array();clickCount=0;if(tipoGeom==Geometry.LINEAR_RING){polRecordset.clearVectorialData();updateGeorefMapClicks(jgPol,polRecordset,jgPolLabel);}else if(tipoGeom==Geometry.LINE_STRING){lineRecordset.clearVectorialData();updateGeorefMapClicks(jgLine,lineRecordset,jgLineLabel);}else{pointRecordset.clearVectorialData();updateGeorefMapClicks(jgPoint,pointRecordset,jgPointLabel);}resetClick();}}function exportGeoref(tipoGeom){if(tipoGeom==Geometry.LINEAR_RING){generateFileExcel(polRecordset,"/servlet/SITAR_georref_pol.jsp");}else if(tipoGeom==Geometry.LINE_STRING){generateFileExcel(lineRecordset,"/servlet/SITAR_georref_lin.jsp");}else{generateFileExcel(pointRecordset,"/servlet/SITAR_georref_pun.jsp");}}function exportGeorefCSV(tipoGeom){if(tipoGeom==Geometry.LINEAR_RING){generateCSVFile(polRecordset);}else if(tipoGeom==Geometry.LINE_STRING){generateCSVFile(lineRecordset);}else{generateCSVFile(pointRecordset);}}function generateCSVFile(recordset){w=window.open('','');numData=recordset.getVectorialDataCount();w.document.writeln("<html><body>");for(var jj=0;jj<numData;jj++){aux=recordset.getGeometry(jj);w.document.writeln(aux.getX()+"\t"+aux.getY());}w.document.writeln("</body></html>");w.document.close();}function num2Coord(aux){coord=String(RoundDecimal(aux,3));if(coord.indexOf(".")!=-1){posPunto=coord.indexOf(".");st1=coord.substr(0,posPunto);st2=coord.substr(posPunto+1);}coord=st1+st2+"E-"+st2.length;return coord;}function generateItemCSV(x,y,text,id){coordX=num2Coord(x);coordY=num2Coord(y);return(id+"\t"+text+"\t"+coordX+"\t"+coordY);}function generateFileCSV(rec){w=window.open();numData=rec.getVectorialDataCount();for(var jj=0;jj<numData;jj++){aux=rec.getGeometry(jj);texto=rec.getAttribute(jj,'text');if((aux.getClass()==Geometry.LINEAR_RING)||(aux.getClass()==Geometry.LINE_STRING)){for(var kk=0;kk<aux.npoints;kk++){w.document.writeln(generateItemCSV(aux.xpoints[kk],aux.ypoints[kk],texto,jj));}}else{w.document.writeln(generateItemCSV(aux.getX(),aux.getY(),texto,jj));}}}function generateItemExcel(x,y,text,id,escala,originador,fecha,srs){coordX=num2Coord(x);coordY=num2Coord(y);return("<tr><td>"+id+"</td><td>"+text+"</td><td>"+coordX+"</td><td>"+coordY+"</td><td>"+escala+"</td><td>"+originador+"</td><td>"+fecha+"</td><td>"+srs+"</td></tr>");}function getExcelTable(rec){numData=rec.getVectorialDataCount();excelTablevar='<table border="1" class="textoInv"><tr style="background-color:#FFCC99;"><th width="100">Id</th><th width="300">Texto</th><th width="250">Coord X</th><th width="250">Coord Y</th><th width="150">Escala</th><th width="150">Creador</th><th width="350">Fecha</th><th width="250">SRS</th></tr>';for(var jj=0;jj<numData;jj++){aux=rec.getGeometry(jj);texto=rec.getAttribute(jj,'text');escala=rec.getAttribute(jj,'escala');originador=rec.getAttribute(jj,'originador');fecha=rec.getAttribute(jj,'fecha');srs=rec.getAttribute(jj,'SRS');if((aux.getClass()==Geometry.LINEAR_RING)||(aux.getClass()==Geometry.LINE_STRING)){for(var kk=0;kk<aux.npoints;kk++){excelTablevar+=(generateItemExcel(aux.xpoints[kk],aux.ypoints[kk],texto,jj,escala,originador,fecha,srs));}}else{excelTablevar+=(generateItemExcel(aux.getX(),aux.getY(),texto,jj,escala,originador,fecha,srs));}}excelTablevar=excelTablevar+"</table>";return excelTablevar;}function generateFileExcel(rec,actionName){document.excelForm.resultsTable.value=getExcelTable(rec);document.excelForm.target="_blank";document.excelForm.action=actionName;document.excelForm.submit();}function deleteClickByText(tipoGeom){texto=window.prompt("Introduzca el texto de la geometría a borrar","");if((texto!=null)&&(texto!='')){if(tipoGeom==Geometry.LINEAR_RING){deleteAGeomByText(polRecordset,texto);updateGeorefMapClicks(jgPol,polRecordset,jgPolLabel);}else if(tipoGeom==Geometry.LINE_STRING){deleteAGeomByText(lineRecordset,texto);updateGeorefMapClicks(jgLine,lineRecordset,jgLineLabel);}else{deleteAGeomByText(pointRecordset,texto);updateGeorefMapClicks(jgPoint,pointRecordset,jgPointLabel);}}}function deleteAGeomByText(rec,text){numData=rec.getVectorialDataCount();indiceData=0;finalizado=false;while(indiceData<numData){if(rec.getAttribute(indiceData,'text')==text){rec.removeVectorialData(indiceData);numData--;}else{indiceData++;}}}function drawLabel(divToLabel,geom,texto){xCenter=0;yCenter=0;if(geom.getClass()==Geometry.LINE_STRING){numPuntos=geom.npoints;indexCenter=Math.floor(numPuntos/2);if((numPuntos%2)==0){x0=geom.xpoints[indexCenter-1];y0=geom.ypoints[indexCenter-1];x1=geom.xpoints[indexCenter];y1=geom.ypoints[indexCenter];xOffset=x1-x0;yOffset=y1-y0;xCenter=x0+(xOffset/2);yCenter=y0+(yOffset/2);}else{xCenter=geom.xpoints[indexCenter];yCenter=geom.ypoints[indexCenter];}}else{rectangle=geom.getBounds();xCenter=rectangle.getX()+(rectangle.getWidth()/2);yCenter=rectangle.getY()+(rectangle.getHeight()/2);}pixelLabelPoint=getScreenXY(xCenter,yCenter);divToLabel.drawString(texto,pixelLabelPoint[0],pixelLabelPoint[1]);}function deleteLastGeorefPoint(){numData=pointRecordset.getVectorialDataCount();if(numData>0){pointRecordset.removeVectorialData(numData-1);}else{alert("No hay puntos para borrar");}updateGeorefMapClicks(jgPoint,pointRecordset,jgPointLabel);}attributesNames=new Array();attributesNames[0]="text";attributesNames[1]="escala";attributesNames[2]="originador";attributesNames[3]="fecha";attributesNames[4]="SRS";pointRecordset=new Recordset(attributesNames);lineRecordset=new Recordset(attributesNames);polRecordset=new Recordset(attributesNames);historicoRecordset=new Recordset(attributesNames);function pintaGeorrefZones(hspc,vspc,iWidth,iHeight){var content='<DIV style="width:100%;height:100%;visibility:visible;" id="georefPointGeomDiv"></DIV>';content+='<DIV style="width:100%;height:100%;visibility:visible;" id="georefPointLabelDiv"></DIV>';createLayer("georefPointDiv",hspc,vspc,iWidth,iHeight,true,content,999);content='<DIV style="width:100%;height:100%;visibility:visible;" id="georefLineGeomDiv"></DIV>';content+='<DIV style="width:100%;height:100%;visibility:visible;" id="georefLineLabelDiv"></DIV>';createLayer("georefLineDiv",hspc,vspc,iWidth,iHeight,true,content,999);content='<DIV style="width:100%;height:100%;visibility:visible;" id="georefPolyGeomDiv"></DIV>';content+='<DIV style="width:100%;height:100%;visibility:visible;" id="georefPolyLabelDiv"></DIV>';createLayer("georefPolyDiv",hspc,vspc,iWidth,iHeight,true,content,999);content='<DIV style="width:100%;height:100%;visibility:visible;" id="georefHistoricoGeomDiv"></DIV>';content+='<DIV style="width:100%;height:100%;visibility:visible;" id="georefHistoricoLabelDiv"></DIV>';createLayer("georefHistoricoDiv",hspc,vspc,iWidth,iHeight,true,content,999);content='<DIV style="width:100%;height:100%;visibility:visible;" id="circleGeomDiv"></DIV>';createLayer("circleDiv",hspc,vspc,iWidth,iHeight,true,content,999);content='<DIV style="width:100%;height:100%;visibility:visible;" id="circleGranjasGeomDiv"></DIV>';createLayer("circleGranjasDiv",hspc,vspc,iWidth,iHeight,true,content,999);}function updateGeorrefZones(doc,hspc,vspc,iWidth,iHeight){doc.getLayer("georefPointDiv").width=iWidth+"px";doc.getLayer("georefPointDiv").height=iHeight+"px";doc.getLayer("georefLineDiv").width=iWidth+"px";doc.getLayer("georefLineDiv").height=iHeight+"px";doc.getLayer("georefPolyDiv").width=iWidth+"px";doc.getLayer("georefPolyDiv").height=iHeight+"px";doc.getLayer("georefHistoricoDiv").width=iWidth+"px";doc.getLayer("georefHistoricoDiv").height=iHeight+"px";}function updateOtherZones(doc,hspc,vspc,iWidth,iHeight){doc.getLayer("circleDiv").width=iWidth+"px";doc.getLayer("circleDiv").height=iHeight+"px";doc.getLayer("circleGranjasDiv").width=iWidth+"px";doc.getLayer("circleGranjasDiv").height=iHeight+"px";}function finHistorico(){txt=RoundDecimal(clickPointX[0],2)+", "+RoundDecimal(clickPointY[0],2);attrib=new Array();attrib['text']=txt;gg=new Point(clickPointX[0],clickPointY[0]);historicoRecordset.addVectorialData(gg,attrib);updateGeorefMapClicks(jgHistorico,historicoRecordset,jgHistoricoLabel);addNewPointHistorico(txt);clickPointX=new Array();clickPointY=new Array();screenClickPointX=new Array();screenClickPointY=new Array();clickCount=0;resetClick();}historicoClicksCount=0;function addNewPointHistorico(txt){document.getElementById('historicoSelect').options[historicoClicksCount]=new Option(txt,historicoClicksCount);historicoClicksCount++;}function exportaHistorico(){w=window.open('','');numData=historicoRecordset.getVectorialDataCount();w.document.writeln("<html><body>");for(var jj=0;jj<numData;jj++){aux=historicoRecordset.getGeometry(jj);w.document.writeln(aux.getX()+"\t"+aux.getY());}w.document.writeln("</body></html>");w.document.close();}function borraHistorico(){if(window.confirm("¿Está seguro de que desea borrar todos los elementos?")){historicoRecordset.clearVectorialData();updateGeorefMapClicks(jgHistorico,historicoRecordset,jgHistoricoLabel);clickPointX=new Array();clickPointY=new Array();screenClickPointX=new Array();screenClickPointY=new Array();clickCount=0;resetClick();historicoClicksCount=0;combo=document.getElementById('historicoSelect');if(combo.options.length>0){combo.options.length=null;}}}function toggleLabel(idLabel,idSpan){obj=document.getElementById(idLabel);if(obj.style.visibility=="visible"){hideZone(idLabel);document.getElementById(idSpan).innerHTML='Mostrar etiquetas';}else{document.getElementById(idSpan).innerHTML='Ocultar etiquetas';showZone(idLabel);}}var onOVArea=false;var totalMeasure=0;var currentMeasure=0;var lastTotMeasure=0;tamPixel=0;areaMeasure=0;perimeter=0;errorAreaMeasure=0;errorDistMeasure=0;RAIZ_DE_DOS=Math.sqrt(2);var clickCount=0;var clickPointX=new Array();var clickPointY=new Array();var clickMeasure=new Array();var clickType=1;var leftButton=1;var rightButton=2;if(isNav){leftButton=1;rightButton=3;}var screenClickPointX=new Array();var screenClickPointY=new Array();isHistorico=false;isGeoreferencing=false;isAreaMeasuring=false;isDistanceMeasuring=false;function movement_distanceMeasure(coordActualX,coordActualY){if(clickCount>=1){calcDistance(coordActualX,coordActualY);var segmentoText="";var unitText="";if(getScaleUnit()=="Km"){segmentoText=RoundDecimal(currentMeasure/1000,numDecimals);unitText="Km";}else{segmentoText=RoundDecimal(currentMeasure,numDecimals);unitText="m";}document.getElementById("medSegmento").value=segmentoText+" "+unitText;}}function clickAddPoint_distanceMeasure(e){clickAddPoint(e);updateDistanceMeasureBox();jg.fillRect(screenClickPointX[clickCount-1]-1,screenClickPointY[clickCount-1]-1,3,3);if(clickCount>1){jg.drawLine(screenClickPointX[clickCount-1],screenClickPointY[clickCount-1],screenClickPointX[clickCount-2],screenClickPointY[clickCount-2]);}jg.paint();}function clickAddPoint_areaMeasure(e){clickAddPoint(e);area=0;for(var i=0;i<clickCount;i++){j=(i+1)%clickCount;area+=clickPointX[i]*clickPointY[j];area-=clickPointY[i]*clickPointX[j];}area/=2;if(area<0){areaMeasure=(area*-1);}else{areaMeasure=area;}updateAreaMeasureBox();updateMapClicks();if(clickCount>1){jg.drawPolygon(screenClickPointX,screenClickPointY);}jg.paint();}function clickAddPoint_editar(e){var theButton=0;if(isNav){theButton=e.which;}else{theButton=window.event.button;}if(theButton==leftButton){clickAddPoint(e);switch(getTipoGeorref()){case'point':jgPoint.fillRect(screenClickPointX[clickCount-1]-1,screenClickPointY[clickCount-1]-1,3,3);jgPoint.paint();finPointGeoref();break;case'line':jgLine.fillRect(screenClickPointX[clickCount-1]-1,screenClickPointY[clickCount-1]-1,3,3);if(clickCount>1){jgLine.drawLine(screenClickPointX[clickCount-1],screenClickPointY[clickCount-1],screenClickPointX[clickCount-2],screenClickPointY[clickCount-2]);}jgLine.paint();break;case'polygon':updateMapClicks();jgPol.fillRect(screenClickPointX[clickCount-1]-1,screenClickPointY[clickCount-1]-1,3,3);if(clickCount>1){jgPol.drawPolygon(screenClickPointX,screenClickPointY);}jgPol.paint();break;default:}}else if(theButton==rightButton){finGeom();return false;}}function clickAddPoint_historico(e){clickAddPoint(e);jgHistorico.fillRect(screenClickPointX[clickCount-1]-1,screenClickPointY[clickCount-1]-1,3,3);jgHistorico.paint();finHistorico();}function clickAddPoint(e){getXY2(e);screenClickPointX[clickCount]=theX;screenClickPointY[clickCount]=theY;var coordClick=getMapXY(theX,theY);var coordClickX=coordClick[0];var coordClickY=coordClick[1];clickPointX[clickCount]=coordClickX;clickPointY[clickCount]=coordClickY;calcDistance(coordClickX,coordClickY);clickCount+=1;selectCount=0;totalMeasure=totalMeasure+currentMeasure;clickMeasure[clickCount]=totalMeasure;}function resetClick(){var c1=clickCount;clickCount=0;clickPointX.length=1;clickPointY.length=1;screenClickPointX.length=1;screenClickPointY.length=1;currentMeasure=0;totalMeasure=0;lastTotMeasure=0;clickMeasure.length=1;selectCount=0;areaMeasure=0;errorAreaMeasure=0;errorDistMeasure=0;perimeter=0;}function deleteClick(){var c1=clickCount;clickCount=clickCount-1;selectCount=0;if(clickCount<0)clickCount=0;if(clickCount>0){totalMeasure=clickMeasure[clickCount];clickPointX.length=clickCount;clickPointY.length=clickCount;screenClickPointX.length=clickCount;screenClickPointY.length=clickCount;clickMeasure.length=clickCount;}else{totalMeasure=0;clickMeasure[0]=0;}currentMeasure=0;updateMapClicks();}function clearDistanceMeasureBox(){document.getElementById("medTotal").value="";document.getElementById("medSegmento").value="";document.getElementById("medErrorDist").value="";}function clearAreaMeasureBox(){document.getElementById("theAreaMedTotal").value="";document.getElementById("medErrorArea").value="";}function updateDistanceMeasureBox(){tamPixel=Math.abs(maxx-minx)/mwidth;var currentMeasureText;var totalMeasureText;var errorMeasureText;var unitText;errorUnPixel=Math.sqrt((Math.pow(tamPixel/2,2))*2);errorDistMeasure=clickCount*errorUnPixel;if(getScaleUnit()=="Km"){currentMeasureText=RoundDecimal(currentMeasure/1000,numDecimals);totalMeasureText=RoundDecimal(totalMeasure/1000,numDecimals);errorMeasureText=RoundDecimal(errorDistMeasure/1000,numDecimals);unitText="Km";}else{currentMeasureText=RoundDecimal(currentMeasure,numDecimals);totalMeasureText=RoundDecimal(totalMeasure,numDecimals);errorMeasureText=RoundDecimal(errorDistMeasure,numDecimals);unitText="m";}document.getElementById("medTotal").value=totalMeasureText+" "+unitText;document.getElementById("medSegmento").value=currentMeasureText+" "+unitText;document.getElementById("medErrorDist").value="± "+errorMeasureText+" "+unitText;}function updateAreaMeasureBox(){tamPixel=Math.abs(maxx-minx)/mwidth;if(areaMeasure>0){var measTotal;var unitText;if(clickCount>0){var xD=Math.abs(clickPointX[clickCount-1]-clickPointX[0]);var yD=Math.abs(clickPointY[clickCount-1]-clickPointY[0]);mDistance=Math.sqrt(Math.pow(xD,2)+Math.pow(yD,2));perimeter=totalMeasure+mDistance;}errorAreaMeasure=perimeter*RAIZ_DE_DOS*tamPixel;if(getScaleAreaUnit()=="Km2"){measTotal=RoundDecimal(areaMeasure/1000000,numDecimals);errorMeasureText=RoundDecimal(errorAreaMeasure/1000000,numDecimals);unitText="Km²";}else if(getScaleAreaUnit()=="Ha"){measTotal=RoundDecimal(areaMeasure/10000,numDecimals);errorMeasureText=RoundDecimal(errorAreaMeasure/10000,numDecimals);unitText="Ha";}else{measTotal=RoundDecimal(areaMeasure,numDecimals);errorMeasureText=RoundDecimal(errorAreaMeasure,numDecimals);unitText="m²";}document.getElementById("theAreaMedTotal").value=measTotal+" "+unitText;document.getElementById("medErrorArea").value="± "+errorMeasureText+" "+unitText;}else{var unitText;if(getScaleAreaUnit()=="Km2"){unitText="Km²";}else if(getScaleAreaUnit()=="Ha"){unitText="Ha";}else{unitText="m²";}document.getElementById("theAreaMedTotal").value="0 "+unitText;document.getElementById("medErrorArea").value="± 0 "+unitText;}}function updateMapClicks(){jg.clear();pixelPointPrev=null;firstPixelPoint=null;for(var ii=0;ii<clickCount;ii++){pixelPoint=getScreenXY(clickPointX[ii],clickPointY[ii]);jg.fillRect(pixelPoint[0]-1,pixelPoint[1]-1,3,3);if(ii>0){jg.drawLine(pixelPoint[0],pixelPoint[1],pixelPointPrev[0],pixelPointPrev[1]);}else{firstPixelPoint=pixelPoint;}if(isAreaMeasuring){if((ii==clickCount-1)&&(clickCount>=3)){jg.drawLine(pixelPoint[0],pixelPoint[1],firstPixelPoint[0],firstPixelPoint[1]);}}screenClickPointX[ii]=pixelPoint[0];screenClickPointY[ii]=pixelPoint[1];pixelPointPrev=pixelPoint;}jg.paint();if(valueRadius!=-1){var tamPixel=Math.abs(maxx-minx)/mwidth;jgCircle.setStroke(2);var numPixels=valueRadius/tamPixel;if((numPixels>0)&&(numPixels*2<=Math.max(mwidth,mheight))){jgCircle.clear();var pixelPoint=getScreenXY(xRadius,yRadius);jgCircle.drawEllipse(pixelPoint[0]-numPixels,pixelPoint[1]-numPixels,numPixels*2,numPixels*2);if(numPixels*2>10){jgCircle.drawLine(pixelPoint[0]-4,pixelPoint[1]-4,pixelPoint[0]+4,pixelPoint[1]+4);jgCircle.drawLine(pixelPoint[0]+4,pixelPoint[1]-4,pixelPoint[0]-4,pixelPoint[1]+4);}jgCircle.paint();}else{jgCircle.clear();var pixelPoint=getScreenXY(xRadius,yRadius);if(numPixels*2>10){jgCircle.drawLine(pixelPoint[0]-4,pixelPoint[1]-4,pixelPoint[0]+4,pixelPoint[1]+4);jgCircle.drawLine(pixelPoint[0]+4,pixelPoint[1]-4,pixelPoint[0]-4,pixelPoint[1]+4);}jgCircle.paint();}}if(customToolType=="GRANJAS"){if(xRadiusGranjas!=null){xRadiusGranjas=maxx-(Math.abs(maxx-minx)/2);yRadiusGranjas=maxy-(Math.abs(maxy-miny)/2);if(distanceList.length==0){distanceList[0]=5000;}}var yaHayAspa=false;var tamPixel=Math.abs(maxx-minx)/mwidth;jgCircleGranjas.clear();for(var ii=0;ii<distanceList.length;ii++){var numPixels=Math.round(distanceList[ii]/tamPixel);if((numPixels>0)&&(numPixels*2<=Math.max(mwidth,mheight))){var pixelPoint=getScreenXY(xRadiusGranjas,yRadiusGranjas);jgCircleGranjas.drawEllipse(pixelPoint[0]-numPixels,pixelPoint[1]-numPixels,numPixels*2,numPixels*2);if(!yaHayAspa){if(numPixels*2>10){jgCircleGranjas.drawLine(pixelPoint[0]-4,pixelPoint[1]-4,pixelPoint[0]+4,pixelPoint[1]+4);jgCircleGranjas.drawLine(pixelPoint[0]+4,pixelPoint[1]-4,pixelPoint[0]-4,pixelPoint[1]+4);}yaHayAspa=true;}}}jgCircleGranjas.paint();}}function updateGeorefMapClicks(divToPaint,rec,divToLabel){divToPaint.clear();divToLabel.clear();pixelPointPrev=null;numData=rec.getVectorialDataCount();for(var jj=0;jj<numData;jj++){geom=rec.getGeometry(jj);texto=rec.getAttribute(jj,'text');if((geom.getClass()==Geometry.LINEAR_RING)||(geom.getClass()==Geometry.LINE_STRING)){for(var kk=0;kk<geom.npoints;kk++){pixelPoint=getScreenXY(geom.xpoints[kk],geom.ypoints[kk]);divToPaint.fillRect(pixelPoint[0]-1,pixelPoint[1]-1,3,3);if(kk>0){divToPaint.drawLine(pixelPoint[0],pixelPoint[1],pixelPointPrev[0],pixelPointPrev[1]);}pixelPointPrev=pixelPoint;}drawLabel(divToLabel,geom,texto);}else{pixelPoint=getScreenXY(geom.getX(),geom.getY());divToPaint.fillRect(pixelPoint[0]-1,pixelPoint[1]-1,3,3);if(getTipoGeorref()=='point'){drawLabel(divToLabel,geom,texto);}}}divToPaint.paint();divToLabel.paint();}newScaleUnit="m";newScaleAreaUnit="Ha";function onChangeLineScale(){combo=document.getElementById('cboLineScale');newScaleUnit=combo.options[combo.selectedIndex].value;updateDistanceMeasureBox();}function getScaleUnit(){return newScaleUnit;}function onChangeAreaScale(){combo=document.getElementById('cboAreaScale');newScaleAreaUnit=combo.options[combo.selectedIndex].value;updateAreaMeasureBox();}function getScaleAreaUnit(){return newScaleAreaUnit;}function limpiarMedicionDistancia(){jg.clear();resetClick();clearDistanceMeasureBox();}function limpiarMedicionArea(){jg.clear();resetClick();clearAreaMeasureBox();}function limpiarEdicion(){jgPoint.clear();jgLine.clear();jgPol.clear();jgPointLabel.clear();jgLineLabel.clear();jgPolLabel.clear();}function limpiarHistorico(){jgHistorico.clear();jgHistoricoLabel.clear();}function limpiarBufferCirculo(){jgCircle.clear();}function borrarBufferCirculo(){limpiarBufferCirculo();valueRadius=-1;}function limpiarBufferCirculoGranjas(){jgCircleGranjas.clear();}function borrarBufferCirculoGranjas(){limpiarBufferCirculoGranjas();valueRadiusGranjas=-1;if(customToolType=="GRANJAS"){customToolType="";}}function onChangeGeorefType(){combo=document.getElementById('cboGeorefType');newValue=combo.options[combo.selectedIndex].value;showOnlyOneGeoref(newValue);}function showOnlyOneGeoref(id){document.getElementById('georefPointOptions').style.display='none';document.getElementById('georefLineOptions').style.display='none';document.getElementById('georefPolyOptions').style.display='none';document.getElementById(id).style.display='block';}function getTipoGeorref(){return'point';}function getScreenXY(xIn,yIn){pixelX=(maxx-minx)/mwidth;pixelY=(maxy-miny)/mheight;screenPoint=new Array();screenPoint[0]=Math.round((xIn-minx)/pixelX);screenPoint[1]=Math.round((maxy-yIn)/pixelY);return screenPoint;}function calcDistance(mX,mY){if(clickCount>0){var xD=Math.abs(mX-clickPointX[clickCount-1]);var yD=Math.abs(mY-clickPointY[clickCount-1]);var mDistance=Math.sqrt(Math.pow(xD,2)+Math.pow(yD,2));currentMeasure=RoundDecimal(mDistance,numDecimals);}}var xminOverview=530000;var ymaxOverview=4760000;var xmaxOverview=855000;var yminOverview=4410000;var tamPixelOverviewX=(xmaxOverview-xminOverview)/130;var tamPixelOverviewY=(ymaxOverview-yminOverview)/140;function icsl857px_overview(_theX,_theY){var result=new Array();var offsetX=_theX-xminOverview;var offsetY=ymaxOverview-_theY;result["x"]=Math.round(offsetX/tamPixelOverviewX);result["y"]=Math.round(offsetY/tamPixelOverviewY);if(result["x"]<=0){result["x"]=0;}if(result["y"]<=0){result["y"]=0;}if(result["x"]>=130){result["x"]=130;}if(result["y"]>=140){result["y"]=140;}return result;}function updateMarcaOverview(){var topLeftPx=icsl857px_overview(minx,maxy);var bottomRightPx=icsl857px_overview(maxx,miny);var diffX=bottomRightPx["x"]-topLeftPx["x"];var diffY=bottomRightPx["y"]-topLeftPx["y"];document.getElementById('marcaOverview').style.left=topLeftPx["x"]+"px";document.getElementById('marcaOverview').style.top=topLeftPx["y"]+"px";document.getElementById('marcaOverview').style.width=diffX+"px";document.getElementById('marcaOverview').style.height=diffY+"px";var mitadX=Math.round(topLeftPx["x"]+(diffX/2));var mitadY=Math.round(topLeftPx["y"]+(diffY/2));if(topLeftPx["y"]>2){document.getElementById('marcaOverviewN').style.display="block";document.getElementById('marcaOverviewN').style.left=mitadX+"px";document.getElementById('marcaOverviewN').style.top="0px";document.getElementById('marcaOverviewN').style.width="1px";document.getElementById('marcaOverviewN').style.height=(topLeftPx["y"]-1)+"px";}else{document.getElementById('marcaOverviewN').style.display="none";}if(bottomRightPx["y"]<138){var aux=bottomRightPx["y"];aux++;document.getElementById('marcaOverviewS').style.display="block";document.getElementById('marcaOverviewS').style.left=mitadX+"px";document.getElementById('marcaOverviewS').style.top=(aux++)+"px";document.getElementById('marcaOverviewS').style.width="1px";document.getElementById('marcaOverviewS').style.height=(140-bottomRightPx["y"]-1)+"px";}else{document.getElementById('marcaOverviewS').style.display="none";}if(topLeftPx["x"]>2){document.getElementById('marcaOverviewW').style.display="block";document.getElementById('marcaOverviewW').style.left="0px";document.getElementById('marcaOverviewW').style.top=mitadY+"px";document.getElementById('marcaOverviewW').style.width=(topLeftPx["x"]-1)+"px";document.getElementById('marcaOverviewW').style.height="1px";}else{document.getElementById('marcaOverviewW').style.display="none";}if(bottomRightPx["x"]<128){var aux=bottomRightPx["x"];aux++;document.getElementById('marcaOverviewE').style.display="block";document.getElementById('marcaOverviewE').style.left=(aux++)+"px";document.getElementById('marcaOverviewE').style.top=mitadY+"px";document.getElementById('marcaOverviewE').style.width=(130-bottomRightPx["x"]-2)+"px";document.getElementById('marcaOverviewE').style.height="1px";}else{document.getElementById('marcaOverviewE').style.display="none";}}function getXY_overview(e){var posVentanaX=parseInt(document.getElementById('overviewWin').style.left);var posVentanaY=parseInt(document.getElementById('overviewWin').style.top)+20;if(isNav){theX=e.pageX-posVentanaX;theY=e.pageY-posVentanaY;}else{theX=event.clientX+document.body.scrollLeft-posVentanaX;theY=event.clientY+document.body.scrollTop-posVentanaY;}return false;}function click_overview(e){getXY_overview(e);if((theX>=0)&&(theY>=0)){var newX=xminOverview+(theX*tamPixelOverviewX);var newY=ymaxOverview-(theY*tamPixelOverviewY);doRecenterXYWithScale(newX,newY,getMapScale(false));}}function generaInicioCabecera(_nombre,_id){var idContent='';idContent+="<tr class='itemBig header blanco'>";idContent+="<td colspan='2'>";idContent+="<a href='javascript:toggleZoneCarpeta(\""+_id+"\", \"información de "+_nombre+"\")' title='Mostrar información de "+_nombre+"' id='"+_id+"Link'>";idContent+="<img src='imagesTOC/old_icon_opened.gif' border='0'></img></a>";idContent+=_nombre;idContent+="</td>";idContent+="</tr>";idContent+="<tr><td colspan='2'><table width='100%' cellpadding='0' cellspacing='0' id='"+_id+"Table' style='display:block;visibility:visible;table-layout:fixed;'><tr><td width='50%'></td><td width='50%'></td></tr>";return idContent;}function generaFinCabecera(){return"</table></td></tr>";}function isIncluded(listaNames,nombre,numTotal){if(numTotal>0){for(var i=0;i<numTotal;i++){if(listaNames[i]==nombre){return true;}}}return false;}var opcionSelecc='';function highlightOpcion(newI,newJ,newK){unselectOpcion();opcionSelecc='opcion_'+newI+"_"+newJ+"_"+newK;document.getElementById(opcionSelecc).style.fontWeight='bold';document.getElementById(opcionSelecc).style.color='#bb0000';}function unselectOpcion(){if(opcionSelecc!=''){document.getElementById(opcionSelecc).style.fontWeight='normal';document.getElementById(opcionSelecc).style.color='#000000';}opcionSelecc='';}function updateResults(){var idContent='';idContent+="<table width='100%' cellpadding='0' cellspacing='0' style='table-layout:fixed;'>";idContent+="<tr>";idContent+="<td valign='top' width='240px'>";idContent+="<table width='100%' cellpadding='0' cellspacing='2'>";for(var i=0;i<restrictionGrupoCount;i++){if(i==0){idContent+="<tr class='itemBig header blanco'>";idContent+="<td colspan='2'>";idContent+=restrictions[i]["nombre"];idContent+="</td>";idContent+="</tr>";}else{idContent+=generaInicioCabecera(restrictions[i]["nombre"],"apartado_"+i);}for(var j=0;j<restrictions[i]["count"];j++){if(restrictions[i][j]["nombre"]!=""){var numResultados=0;for(var k=0;k<restrictions[i][j]["count"];k++){numResultados+=getNumResultados(i,j,k);}idContent+="<tr>";idContent+="<td colspan='2'>";idContent+="<fieldset class='item normal'>";if(numResultados==0){idContent+="<legend class='item disabled cursiva'>";}else{idContent+="<legend class='item normal cursiva'>";}idContent+=restrictions[i][j]["nombre"];idContent+="</legend>";for(var k=0;k<restrictions[i][j]["count"];k++){idContent+="<table width='100%' cellpadding='0' cellspacing='0'>";idContent+=drawResult(i,j,k);idContent+="</table>";}idContent+="</fieldset>";idContent+="</td>";idContent+="</tr>";}else{for(var k=0;k<restrictions[i][j]["count"];k++){idContent+=drawResult(i,j,k);}}}if(i!=0){idContent+=generaFinCabecera();}}idContent+="</table>";idContent+="</td>";idContent+="<td valign='top' width='540px' id='detailedResultsTable'>";idContent+=getDetailedResultHTML(0,0,0);idContent+="</td>";idContent+="</tr>";idContent+="</table>";detailedResultsWin.setcontent('');detailedResultsWin.hide();resultsWin.setcontent(idContent);resultsWin.settitle("Resultados sobre ("+RoundDecimal(xCoordUsr,2)+", "+RoundDecimal(yCoordUsr,2)+")");resultsWin.show();getDetailedResult(0,0,0);}function getNumResultados(i,j,k){var numResultados=0;for(var l=0;l<restrictions[i][j][k]["count"];l++){idx=restrictions[i][j][k][l]["posicion"];if(restrictions[i][j][k][l]["esGFI"]){numResultados=numResultados+gfiList[idx]["camposRespuesta"]["count"];}else{numResultados=numResultados+countResultQueryableLayer[idx];}}return numResultados;}function drawResult(i,j,k){idContent='';nombre=restrictions[i][j][k]["NOMBRE"];tooltip=restrictions[i][j][k]["TOOLTIP"];theId=restrictions[i][j][k]["ID"];var numResultados=0;if((i==0)&&(j==0)&&(k==0)){numResultados=1;}else{numResultados=getNumResultados(i,j,k);}if(numResultados==0){idContent+="<tr class='item disabled'><td colspan='2'>";idContent+=nombre;idContent+="</td>";idContent+="</tr>";}else{idContent+="<tr class='item normal'><td colspan='2'>";idContent+="<a class='itemEnlace' id='opcion_"+i+"_"+j+"_"+k+"' href='#' onclick='javascript:getDetailedResult("+i+","+j+","+k+");' title='"+tooltip+"'>"+nombre;if(restrictions[i][j][k]["showResultCount"]){idContent+=" ("+numResultados+")";}idContent+="</a>";idContent+="</td>";idContent+="</tr>";}return idContent;}function getNombreCampo(str){var tempString=str;var nombreCampo="";if((shortenSDENames==true)&&(tempString.split(".").length>2)){nombreCampo=tempString.split(".")[tempString.split(".").length-1];}else{nombreCampo=tempString;}return nombreCampo;}function getData(i,j,k){idContent="";for(var l=0;l<restrictions[i][j][k]["count"];l++){if(restrictions[i][j][k][l]["esGFI"]){idContent+=getResultsGFIHTML(i,j,k,l);}else{var idx=restrictions[i][j][k][l]["posicion"];if(queryableLayer[idx]["camposRespuesta"]["count"]>0){id=queryableLayer[idx]["ID"];for(var kk=0;kk<queryableLayer[idx]["camposRespuesta"]["count"];kk++){fName1=queryableLayer[idx]["camposRespuesta"][kk];fValue1=queryableLayer[idx]["valoresRespuesta"][kk];var idFeature="";var listaIndexMainField=new Array();var listaFieldNames=mainFieldName[id].split(' ');indexIdField=-1;for(var ii=0;ii<fName1.length;ii++){nombreCampo=getNombreCampo(fName1[ii]);if(isIncluded(listaFieldNames,nombreCampo,listaFieldNames.length)){listaIndexMainField[nombreCampo]=ii;}if(nombreCampo==nombreCampoId){indexIdField=ii;}}if(fName1.length==3){mainFieldText="";for(var jj=0;jj<listaFieldNames.length;jj++){mainFieldText+=corrigeCaracteresExtranos(fValue1[listaIndexMainField[listaFieldNames[jj]]])+" ";}idContent+="<tr><td colspan='3' class='item normal'>";if(titleFieldName[id]!=null){idContent+="<b>"+titleFieldName[id]+"</b> "+mainFieldText;}else{idContent+=mainFieldText;}if(indexIdField!=-1){if(queryableLayer[idx]["TIPO"]==1){idContent+="&nbsp;&nbsp;(<a class='textoInvEnlace' href='javascript:activarCapaConcreta(\""+idx+"\");'>Activar capa temática en la ventana de Contenidos</a>)";}}idContent+="</td></tr>";}else{mainFieldText="";for(var jj=0;jj<listaFieldNames.length;jj++){if(fValue1[listaIndexMainField[listaFieldNames[jj]]]){mainFieldText+=corrigeCaracteresExtranos(fValue1[listaIndexMainField[listaFieldNames[jj]]])+" ";}}idContent+="<tr><td colspan='3' class='item normal'>";idContent+="<fieldset>";idContent+="<legend>";if(titleFieldName[id]!=null){idContent+=titleFieldName[id]+" "+mainFieldText;}else{idContent+=mainFieldText;}idContent+="</legend>";idContent+="<table id='detailData"+l+"_"+kk+"Table' width='100%' cellpadding='5' cellspacing='0' style='display:block;'>";jj=0;for(var ii=0;ii<fName1.length;ii++){idContent+="<tr>";nombreCampo=getNombreCampo(fName1[ii]);if(isValidField(nombreCampo)){if(fieldAliasList2[id]){if(fieldAliasList2[id][nombreCampo]){idContent+="<td class='item normal'><b>"+(fieldAliasList2[id][nombreCampo])+"</b>: "+corrigeCaracteresExtranos(fValue1[ii])+"</td>";}else{idContent+="<td class='item normal'><b>"+nombreCampo+"</b>: "+corrigeCaracteresExtranos(fValue1[ii])+"</td>";}}else{idContent+="<td class='item normal header'><b>"+nombreCampo+"</b>: "+corrigeCaracteresExtranos(fValue1[ii])+"</td>";}jj++;}idContent+="</tr>";}if(indexIdField!=-1){if(queryableLayer[idx]["TIPO"]==1){idContent+="<tr>";idContent+="<td class='item normal' align='left'><a class='textoInvEnlace' href='javascript:activarCapaConcreta(\""+idx+"\");'>Activar capa temática en la ventana de Contenidos</a>";idContent+="</td>";idContent+="</tr>";}}idContent+="</table>";idContent+="</fieldset>";idContent+="</td></tr>";}}}}}return idContent;}function isValidField(nombreCampo){if(nombreCampo=="#SHAPE#"){}else if(nombreCampo=="#ID#"){}else if(nombreCampo=="OBJECTID"){}else if(nombreCampo=="OBJECTID_1"){}else{return true;}return false;}function drawDetailedResult(i,j,k){if(capasEstanListas(i,j,k)){idContent=getDetailedResultHTML(i,j,k);document.getElementById('detailedResultsTable').innerHTML=idContent;highlightOpcion(i,j,k);ocultaLayerLoading();}}function getDetailedResultHTML(i,j,k){idContent='';if(restrictions[i][j][k]["count"]>0){idContent+="<table valign='top' width='100%' cellpadding='0' cellspacing='10'>";idContent+="<tr><td align='center' class='itemTitulo' colspan='3'>";idContent+=restrictions[i][j][k]["NOMBRE"];idContent+="</td></tr>";idContent+="<tr><td colspan='3'>";idContent+="<table valign='top' width='100%' cellpadding='0' cellspacing='10'>";idContent+="<tr><td align='center'>";if((i==0)&&(j==0)&&(k==0)){idContent+="<fieldset class='item normal'>";idContent+="<legend>";idContent+="Coordenadas";idContent+="</legend>";idContent+="<table width='100%' cellpadding='0' cellspacing='0'>";idContent+="<tr><td class='item normal' align='left'><b>Sistema de referencia espacial</b>: UTM ED50 Huso 30</td></tr>";idContent+="<tr><td class='item normal' align='left'><b>Coordenada X</b>: "+RoundDecimal(xCoordUsr,2)+"</td></tr>";idContent+="<tr><td class='item normal' align='left'><b>Coordenada Y</b>: "+RoundDecimal(yCoordUsr,2)+"</td></tr>";if(needCalculateAltitud){idContent+="<tr><td class='item normal' align='left'><b>Altitud aproximada</b>: "+laCota+" metros</td></tr>";}idContent+="</table>";idContent+="</fieldset>";if(needCalculateOVC){idContent+="<tr><td class='item normal' align='left'><b>Referencia catastral de la parcela según la Sede Electr&oacute;nica de Catastro</b>: "+resultOVC+"</td></tr>";}}idContent+=getData(i,j,k);idContent+="<tr><td class='item normal' align='center'><br>Para más información: <b>sitar@aragon.es</b></td></tr>";idContent+="</td></tr>";idContent+="</table>";idContent+="</td></tr>";idContent+="</table>";}return idContent;}function getDetailedResult(i,j,k){askedI=i;askedJ=j;askedK=k;drawDetailedResult(askedI,askedJ,askedK);}function capasEstanListas(i,j,k){for(var l=0;l<restrictions[i][j][k]["count"];l++){if(!restrictions[i][j][k][l]["esGFI"]){var idx=restrictions[i][j][k][l]["posicion"];if(countResultQueryableLayer[idx]>0){if(queryableLayer[idx]["camposRespuesta"]["count"]==0){currentQueriedLayer=idx;ActiveLayer=queryableLayer[currentQueriedLayer]["ID_QUERY"];if(checkScale(ActiveLayer)){sendIdRequest(false);return false;}else{countResultQueryableLayer[currentQueriedLayer]=0;}}}}}return true;}function writeSessionCookie(cookieName,cookieValue){if(testSessionCookie()){document.cookie=escape(cookieName)+"="+escape(cookieValue)+"; path=/";return true;}else{return false;}}function getCookieValue(cookieName){var exp=new RegExp(escape(cookieName)+"=([^;]+)");if(exp.test(document.cookie+";")){exp.exec(document.cookie+";");return unescape(RegExp.$1);}else return false;}function testSessionCookie(){document.cookie="testSessionCookie=Enabled";if(getCookieValue("testSessionCookie")=="Enabled"){return true;}else{return false;}}function testPersistentCookie(){writePersistentCookie("testPersistentCookie","Enabled","minutes",1);if(getCookieValue("testPersistentCookie")=="Enabled"){return true;}else{return false;}}function writePersistentCookie(CookieName,CookieValue,periodType,offset){var expireDate=new Date();offset=offset/1;var myPeriodType=periodType;switch(myPeriodType.toLowerCase()){case"years":expireDate.setYear(expireDate.getFullYear()+offset);break;case"months":expireDate.setMonth(expireDate.getMonth()+offset);break;case"days":expireDate.setDate(expireDate.getDate()+offset);break;case"hours":expireDate.setHours(expireDate.getHours()+offset);break;case"minutes":expireDate.setMinutes(expireDate.getMinutes()+offset);break;default:alert("Invalid periodType parameter for writePersistentCookie()");break;}document.cookie=escape(CookieName)+"="+escape(CookieValue)+"; expires="+expireDate.toGMTString()+"; domain=aragon.es; path=/";}function deleteCookie(cookieName){if(getCookieValue(cookieName)){writePersistentCookie(cookieName,"Pending delete","years",-1);}return true;}
