////////////////////////////////////////////////////////////////////////////////////////
var navegador = navigator.userAgent.toLowerCase();
var esNetscape = /a/[-1]=='a'|| navegador.indexOf('firefox') > -1;
var esExplorer = ('\v'=='v') || navegador.indexOf('msie')>-1;
//var esChrome = /source/.test((/a/.toString+''));
var esChrome = navegador.indexOf('chrome') > -1;
var esSafari = /a/.__proto__=='//';
var esOpera =/^function \(/.test([].sort);
var versionNavegador = parseInt(navigator.appVersion);
var esExplorer6 = /MSIE 6.0/i.test(navigator.userAgent);
var ieVer=/*@cc_on function(){ switch(@_jscript_version){ case 1.0:return 3; case 3.0:return 4; case 5.0:return 5; case 5.1:return 5; case 5.5:return 5.5; case 5.6:return 6; case 5.7:return 7; case 5.8:return 8; case 9:return 9; }}()||@*/0;
var esExplorer7 = (ieVer==7);
var esExplorer8 = (ieVer==8);
var esExplorer9 = (ieVer==9);


var versionParam = '&v='+version;
var rutaScripts = rutaPrincipal+'scripts/'; 
var rutaCss = rutaPrincipal+'css/';
var displayMostrar = (esExplorer)?'inline':'table-row'; 
var displayMostrarTable = (esNetscape)?'table-row':'inline'; 
var acc='';
var pagoYaRealizado = false;
var mostrandoVentanaPagar = false;

var directorioImagenes=rutaPrincipal + "img/";
var rutaImagenCargando = directorioImagenes+"cargando3.gif?v="+version;
var imagespng = directorioImagenes + "images3.png?&v="+ version;
var imgCargando = '<img style="border:none;" src="'+rutaImagenCargando+'">';
var mostrandoEn3d = false;
var listaMarkersAux = [];
var srs4326 = 'EPSG:4326';
var srs900913 = 'EPSG:900913';
var srs3857 = 'EPSG:3857';
var srs3785 = 'EPSG:3785';
var srs5400 = 'EPSG:5400';
var version130 = '1.3.0';

var mapasWMSCargados = [];
var mapasWMSMostrados =[];




////////////////////////////////////////////////////////////////////////////////////////
(function(){var toPixels=function(widthValue){var px;switch(widthValue){case"thin":px="2px";break;case"medium":px="4px";break;case"thick":px="6px";break;default:px=widthValue}return px};var getBorderWidths=function(h){var computedStyle;var bw={};if(document.defaultView&&document.defaultView.getComputedStyle){computedStyle=h.ownerDocument.defaultView.getComputedStyle(h,"");if(computedStyle){bw.top=parseInt(computedStyle.borderTopWidth,10)||0;bw.bottom=parseInt(computedStyle.borderBottomWidth,10)||0;bw.left=parseInt(computedStyle.borderLeftWidth,10)||0;bw.right=parseInt(computedStyle.borderRightWidth,10)||0;return bw}}else if(document.documentElement.currentStyle){if(h.currentStyle){bw.top=parseInt(toPixels(h.currentStyle.borderTopWidth),10)||0;bw.bottom=parseInt(toPixels(h.currentStyle.borderBottomWidth),10)||0;bw.left=parseInt(toPixels(h.currentStyle.borderLeftWidth),10)||0;bw.right=parseInt(toPixels(h.currentStyle.borderRightWidth),10)||0;return bw}}bw.top=parseInt(h.style["border-top-width"],10)||0;bw.bottom=parseInt(h.style["border-bottom-width"],10)||0;bw.left=parseInt(h.style["border-left-width"],10)||0;bw.right=parseInt(h.style["border-right-width"],10)||0;return bw};var scroll={x:0,y:0};var getScrollValue=function(e){scroll.x=(typeof document.documentElement.scrollLeft!=="undefined"?document.documentElement.scrollLeft:document.body.scrollLeft);scroll.y=(typeof document.documentElement.scrollTop!=="undefined"?document.documentElement.scrollTop:document.body.scrollTop)};getScrollValue();var getMousePosition=function(e){var posX=0,posY=0;e=e||window.event;if(typeof e.pageX!=="undefined"){posX=e.pageX;posY=e.pageY}else if(typeof e.clientX!=="undefined"){posX=e.clientX+scroll.x;posY=e.clientY+scroll.y}return{left:posX,top:posY}};var getElementPosition=function(h){var posX=h.offsetLeft;var posY=h.offsetTop;var parent=h.offsetParent;while(parent!==null){if(parent!==document.body&&parent!==document.documentElement){posX-=parent.scrollLeft;posY-=parent.scrollTop}var m=parent;var moffx=m.offsetLeft;var moffy=m.offsetTop;if(!moffx&&!moffy&&window.getComputedStyle){var matrix=document.defaultView.getComputedStyle(m,null).MozTransform||document.defaultView.getComputedStyle(m,null).WebkitTransform;if(matrix){if(typeof matrix==="string"){var parms=matrix.split(",");moffx+=parseInt(parms[4],10)||0;moffy+=parseInt(parms[5],10)||0}}}posX+=moffx;posY+=moffy;parent=parent.offsetParent}return{left:posX,top:posY}};var setVals=function(obj,vals){if(obj&&vals){for(var x in vals){if(vals.hasOwnProperty(x)){obj[x]=vals[x]}}}return obj};var setOpacity=function(h,op){if(typeof op!=="undefined"){h.style.opacity=op}if(typeof h.style.opacity!=="undefined"){h.style.filter="alpha(opacity="+(h.style.opacity*100)+")"}};function DragZoom(map,opt_zoomOpts){var me=this;var ov=new google.maps.OverlayView();ov.onAdd=function(){me.init_(map,opt_zoomOpts)};ov.draw=function(){};ov.onRemove=function(){};ov.setMap(map);this.prjov_=ov}DragZoom.prototype.init_=function(map,opt_zoomOpts){var i;var me=this;this.map_=map;opt_zoomOpts=opt_zoomOpts||{};this.key_=opt_zoomOpts.key||"shift";this.key_=this.key_.toLowerCase();this.borderWidths_=getBorderWidths(this.map_.getDiv());this.veilDiv_=[];for(i=0;i<4;i++){this.veilDiv_[i]=$new("div");this.veilDiv_[i].onselectstart=function(){return false};setVals(this.veilDiv_[i].style,{backgroundColor:"gray",opacity:0.25,cursor:"crosshair"});setVals(this.veilDiv_[i].style,opt_zoomOpts.paneStyle);setVals(this.veilDiv_[i].style,opt_zoomOpts.veilStyle);setVals(this.veilDiv_[i].style,{position:"absolute",overflow:"hidden",zIndex:10001,display:"none"});if(this.key_==="shift"){this.veilDiv_[i].style.MozUserSelect="none"}setOpacity(this.veilDiv_[i]);if(this.veilDiv_[i].style.backgroundColor==="transparent"){this.veilDiv_[i].style.backgroundColor="white";setOpacity(this.veilDiv_[i],0)}this.map_.getDiv().appendChild(this.veilDiv_[i])}this.visualEnabled_=opt_zoomOpts.visualEnabled||false;this.visualPosition_=opt_zoomOpts.visualPosition||google.maps.ControlPosition.LEFT;this.visualPositionOffset_=opt_zoomOpts.visualPositionOffset||new google.maps.Size(35,0);this.visualPositionIndex_=opt_zoomOpts.visualPositionIndex||null;this.visualSprite_=opt_zoomOpts.visualSprite||"http://maps.gstatic.com/mapfiles/ftr/controls/dragzoom_btn.png";this.visualSize_=opt_zoomOpts.visualSize||new google.maps.Size(20,20);this.visualTips_=opt_zoomOpts.visualTips||{};this.visualTips_.off=this.visualTips_.off||"Turn on drag zoom mode";this.visualTips_.on=this.visualTips_.on||"Turn off drag zoom mode";this.boxDiv_=$new("div");setVals(this.boxDiv_.style,{border:"4px solid #736AFF"});setVals(this.boxDiv_.style,opt_zoomOpts.boxStyle);setVals(this.boxDiv_.style,{position:"absolute",display:"none"});setOpacity(this.boxDiv_);this.map_.getDiv().appendChild(this.boxDiv_);this.boxBorderWidths_=getBorderWidths(this.boxDiv_);this.listeners_=[google.maps.event.addDomListener(document,"keydown",function(e){me.onKeyDown_(e)}),google.maps.event.addDomListener(document,"keyup",function(e){me.onKeyUp_(e)}),google.maps.event.addDomListener(this.veilDiv_[0],"mousedown",function(e){me.onMouseDown_(e)}),google.maps.event.addDomListener(document,"mousedown",function(e){me.onMouseDownDocument_(e)}),google.maps.event.addDomListener(document,"mousemove",function(e){me.onMouseMove_(e)}),google.maps.event.addDomListener(document,"mouseup",function(e){me.onMouseUp_(e)}),google.maps.event.addDomListener(window,"scroll",getScrollValue)];this.hotKeyDown_=false;this.mouseDown_=false;this.dragging_=false;this.startPt_=null;this.endPt_=null;this.mapWidth_=null;this.mapHeight_=null;this.mousePosn_=null;this.mapPosn_=null;if(this.visualEnabled_){this.initControl_(this.map_,this.visualPositionOffset_);if(this.visualPositionIndex_!==null){this.buttonDiv_.index=this.visualPositionIndex_}this.map_.controls[this.visualPosition_].push(this.buttonDiv_);this.controlIndex_=this.map_.controls[this.visualPosition_].length-1}};DragZoom.prototype.initControl_=function(map,offset){var me=this;this.buttonDiv_=$new("div");this.buttonDiv_.style.height=this.visualSize_.height+"px";this.buttonDiv_.style.width=this.visualSize_.width+"px";this.buttonDiv_.style.background="transparent url("+this.visualSprite_+") no-repeat -40px 0";this.buttonDiv_.title=this.visualTips_.off;this.buttonDiv_.onclick=function(e){me.hotKeyDown_=!me.hotKeyDown_;if(me.hotKeyDown_){me.buttonDiv_.style.backgroundPosition=-(me.visualSize_.height*0)+"px 0";me.buttonDiv_.title=me.visualTips_.on;google.maps.event.trigger(me,"activate")}else{me.buttonDiv_.style.backgroundPosition=-(me.visualSize_.height*2)+"px 0";me.buttonDiv_.title=me.visualTips_.off;google.maps.event.trigger(me,"deactivate")}me.onMouseMove_(e)};this.buttonDiv_.onmouseover=function(){me.buttonDiv_.style.backgroundPosition=-(me.visualSize_.height*1)+"px 0"};this.buttonDiv_.onmouseout=function(){if(me.hotKeyDown_){me.buttonDiv_.style.backgroundPosition=-(me.visualSize_.height*0)+"px 0";me.buttonDiv_.title=me.visualTips_.on}else{me.buttonDiv_.style.backgroundPosition=-(me.visualSize_.height*2)+"px 0";me.buttonDiv_.title=me.visualTips_.off}};this.buttonDiv_.ondragstart=function(){return false};setVals(this.buttonDiv_.style,{zIndex:10002,cursor:"pointer",marginTop:offset.height+"px",marginLeft:offset.width+"px"});map.getDiv().appendChild(this.buttonDiv_);return};DragZoom.prototype.isHotKeyDown_=function(e){var isHot;e=e||window.event;isHot=(e.shiftKey&&this.key_==="shift")||(e.altKey&&this.key_==="alt")||(e.ctrlKey&&this.key_==="ctrl");if(!isHot){switch(e.keyCode){case 16:if(this.key_==="shift"){isHot=true}break;case 17:if(this.key_==="ctrl"){isHot=true}break;case 18:if(this.key_==="alt"){isHot=true}break}}return isHot};DragZoom.prototype.isMouseOnMap_=function(){var mousePosn=this.mousePosn_;if(mousePosn){var mapPosn=this.mapPosn_;var mapDiv=this.map_.getDiv();return mousePosn.left>mapPosn.left&&mousePosn.left<(mapPosn.left+mapDiv.offsetWidth)&&mousePosn.top>mapPosn.top&&mousePosn.top<(mapPosn.top+mapDiv.offsetHeight)}else{return false}};DragZoom.prototype.setVeilVisibility_=function(){var i;if(this.map_&&this.hotKeyDown_&&this.isMouseOnMap_()){var mapDiv=this.map_.getDiv();this.mapWidth_=mapDiv.offsetWidth-(this.borderWidths_.left+this.borderWidths_.right);this.mapHeight_=mapDiv.offsetHeight-(this.borderWidths_.top+this.borderWidths_.bottom);this.veilDiv_[0].style.left="0px";this.veilDiv_[0].style.top="0px";this.veilDiv_[0].style.width=this.mapWidth_+"px";this.veilDiv_[0].style.height=this.mapHeight_+"px";for(i=1;i<this.veilDiv_.length;i++){this.veilDiv_[i].style.width="0px";this.veilDiv_[i].style.height="0px"}for(i=0;i<this.veilDiv_.length;i++){this.veilDiv_[i].style.display="block"}}else{for(i=0;i<this.veilDiv_.length;i++){this.veilDiv_[i].style.display="none"}}};DragZoom.prototype.onKeyDown_=function(e){if(this.map_&&!this.hotKeyDown_&&this.isHotKeyDown_(e)){this.mapPosn_=getElementPosition(this.map_.getDiv());this.hotKeyDown_=true;this.setVeilVisibility_();google.maps.event.trigger(this,"activate")}if(this.visualEnabled_&&this.isHotKeyDown_(e)){this.buttonDiv_.style.display="none"}};DragZoom.prototype.getMousePoint_=function(e){var mousePosn=getMousePosition(e);var p=new google.maps.Point();p.x=mousePosn.left-this.mapPosn_.left-this.borderWidths_.left;p.y=mousePosn.top-this.mapPosn_.top-this.borderWidths_.top;p.x=Math.min(p.x,this.mapWidth_);p.y=Math.min(p.y,this.mapHeight_);p.x=Math.max(p.x,0);p.y=Math.max(p.y,0);return p};DragZoom.prototype.onMouseDown_=function(e){if(this.map_&&this.hotKeyDown_){this.mapPosn_=getElementPosition(this.map_.getDiv());this.dragging_=true;this.startPt_=this.endPt_=this.getMousePoint_(e);this.boxDiv_.style.width=this.boxDiv_.style.height="0px";var prj=this.prjov_.getProjection();var latlng=prj.fromContainerPixelToLatLng(this.startPt_);if(this.visualEnabled_){this.buttonDiv_.style.display="none"}google.maps.event.trigger(this,"dragstart",latlng)}};DragZoom.prototype.onMouseDownDocument_=function(e){this.mouseDown_=true};DragZoom.prototype.onMouseMove_=function(e){this.mousePosn_=getMousePosition(e);if(this.dragging_){this.endPt_=this.getMousePoint_(e);var left=Math.min(this.startPt_.x,this.endPt_.x);var top=Math.min(this.startPt_.y,this.endPt_.y);var width=Math.abs(this.startPt_.x-this.endPt_.x);var height=Math.abs(this.startPt_.y-this.endPt_.y);this.veilDiv_[0].style.top="0px";this.veilDiv_[0].style.left="0px";this.veilDiv_[0].style.width=left+"px";this.veilDiv_[0].style.height=this.mapHeight_+"px";this.veilDiv_[1].style.top="0px";this.veilDiv_[1].style.left=(left+width)+"px";this.veilDiv_[1].style.width=(this.mapWidth_-(left+width))+"px";this.veilDiv_[1].style.height=this.mapHeight_+"px";this.veilDiv_[2].style.top="0px";this.veilDiv_[2].style.left=left+"px";this.veilDiv_[2].style.width=width+"px";this.veilDiv_[2].style.height=top+"px";this.veilDiv_[3].style.top=(top+height)+"px";this.veilDiv_[3].style.left=left+"px";this.veilDiv_[3].style.width=width+"px";this.veilDiv_[3].style.height=(this.mapHeight_-(top+height))+"px";this.boxDiv_.style.top=top+"px";this.boxDiv_.style.left=left+"px";this.boxDiv_.style.width=(width-(this.boxBorderWidths_.left+this.boxBorderWidths_.right))+"px";this.boxDiv_.style.height=(height-(this.boxBorderWidths_.top+this.boxBorderWidths_.bottom))+"px";this.boxDiv_.style.display="block";google.maps.event.trigger(this,"drag",new google.maps.Point(left,top+height),new google.maps.Point(left+width,top),this.prjov_.getProjection())}else if(!this.mouseDown_){this.mapPosn_=getElementPosition(this.map_.getDiv());this.setVeilVisibility_()}};DragZoom.prototype.onMouseUp_=function(e){var z;var me=this;this.mouseDown_=false;if(this.dragging_){var left=Math.min(this.startPt_.x,this.endPt_.x);var top=Math.min(this.startPt_.y,this.endPt_.y);var width=Math.abs(this.startPt_.x-this.endPt_.x);var height=Math.abs(this.startPt_.y-this.endPt_.y);var kGoogleCenteringBug=true;if(kGoogleCenteringBug){left+=this.borderWidths_.left;top+=this.borderWidths_.top}var prj=this.prjov_.getProjection();var sw=prj.fromContainerPixelToLatLng(new google.maps.Point(left,top+height));var ne=prj.fromContainerPixelToLatLng(new google.maps.Point(left+width,top));var bnds=new google.maps.LatLngBounds(sw,ne);z=this.map_.getZoom();this.map_.fitBounds(bnds);if(this.map_.getZoom()<z){this.map_.setZoom(z)}var swPt=prj.fromLatLngToContainerPixel(sw);var nePt=prj.fromLatLngToContainerPixel(ne);if(kGoogleCenteringBug){swPt.x-=this.borderWidths_.left;swPt.y-=this.borderWidths_.top;nePt.x-=this.borderWidths_.left;nePt.y-=this.borderWidths_.top}this.boxDiv_.style.left=swPt.x+"px";this.boxDiv_.style.top=nePt.y+"px";this.boxDiv_.style.width=(Math.abs(nePt.x-swPt.x)-(this.boxBorderWidths_.left+this.boxBorderWidths_.right))+"px";this.boxDiv_.style.height=(Math.abs(nePt.y-swPt.y)-(this.boxBorderWidths_.top+this.boxBorderWidths_.bottom))+"px";setTimeout(function(){me.boxDiv_.style.display="none"},1000);this.dragging_=false;this.onMouseMove_(e);google.maps.event.trigger(this,"dragend",bnds);if(!this.isHotKeyDown_(e)){this.onKeyUp_(e)}}};DragZoom.prototype.onKeyUp_=function(e){var i;if(this.map_&&this.hotKeyDown_){this.hotKeyDown_=false;if(this.dragging_){this.boxDiv_.style.display="none";this.dragging_=false}for(i=0;i<this.veilDiv_.length;i++){this.veilDiv_[i].style.display="none"}if(this.visualEnabled_){this.buttonDiv_.style.backgroundPosition=-(this.visualSize_.height*2)+"px 0";this.buttonDiv_.title=this.visualTips_.off;this.buttonDiv_.style.display=""}google.maps.event.trigger(this,"deactivate")}};google.maps.Map.prototype.enableKeyDragZoom=function(opt_zoomOpts){this.dragZoom_=new DragZoom(this,opt_zoomOpts)};google.maps.Map.prototype.disableKeyDragZoom=function(){var i;var d=this.dragZoom_;if(d){for(i=0;i<this.listeners_.length;++i){google.maps.event.removeListener(d.listeners_[i])}this.getDiv().removeChild(d.boxDiv_);for(i=0;i<d.veilDiv_.length;i++){this.getDiv().removeChild(d.veilDiv_[i])}if(d.visualEnabled_){this.controls[d.visualPosition_].removeAt(d.controlIndex_)}d.prjov_.setMap(null);this.dragZoom_=null}};google.maps.Map.prototype.keyDragZoomEnabled=function(){return this.dragZoom_!==null};google.maps.Map.prototype.getDragZoomObject=function(){return this.dragZoom_}})();
////////////////////////////////////////////////////////////////////////////////////////
var MERCATOR_RANGE = 256;

var MAGIC_NUMBER=6356752.3142;

var MAGIC_NUMBER2=6378137;

var DEG2RAD=0.0174532922519943;
var PI=3.14159267;
function dd2MercMetersLng(p_lng) {
	return MAGIC_NUMBER*(p_lng*DEG2RAD);
} 
function dd2MercMetersLat(p_lat) {
	if (p_lat >= 85) p_lat=85;
	if (p_lat <= -85) p_lat=-85;
	return MAGIC_NUMBER*Math.log(Math.tan(((p_lat*DEG2RAD)+(PI/2)) /2));
}

function dd2MercMetersLat2(p_lat) {
	if (p_lat >= 85) p_lat=85;
	if (p_lat <= -85) p_lat=-85;
	return MAGIC_NUMBER2*Math.log(Math.tan((p_lat*DEG2RAD/2)+(PI/4)));
}
 
function bound(value, opt_min, opt_max) {
  if (opt_min != null) value = Math.max(value, opt_min);
  if (opt_max != null) value = Math.min(value, opt_max);
  return value;
}

 
function degreesToRadians(deg) {return deg * (Math.PI / 180);} 
function radiansToDegrees(rad) {return rad / (Math.PI / 180);}
 
 
function bound(value, opt_min, opt_max) {
  if (opt_min != null) value = Math.max(value, opt_min);
  if (opt_max != null) value = Math.min(value, opt_max);
  return value;
}
 
function degreesToRadians(deg) {return deg * (Math.PI / 180);} 
function radiansToDegrees(rad) {return rad / (Math.PI / 180);}
 
 
function MercatorProjection() {
  this.pixelOrigin_ = new google.maps.Point(
      MERCATOR_RANGE / 2, MERCATOR_RANGE / 2);
  this.pixelsPerLonDegree_ = MERCATOR_RANGE / 360;
  this.pixelsPerLonRadian_ = MERCATOR_RANGE / (2 * Math.PI);
};
 
MercatorProjection.prototype.fromLatLngToPoint = function(latLng, opt_point) {
  var me = this;
 
  var point = opt_point || new google.maps.Point(0, 0);
 
  var origin = me.pixelOrigin_;
  point.x = origin.x + latLng.lng() * me.pixelsPerLonDegree_;
  // NOTE(appleton): Truncating to 0.9999 effectively limits latitude to
  // 89.189.  This is about a third of a tile past the edge of the world tile.
  var siny = bound(Math.sin(degreesToRadians(latLng.lat())), -0.9999, 0.9999);
  point.y = origin.y + 0.5 * Math.log((1 + siny) / (1 - siny)) * -me.pixelsPerLonRadian_;
  return point;
};
 
MercatorProjection.prototype.fromDivPixelToLatLng = function(pixel, zoom) {
  var me = this;
  var origin = me.pixelOrigin_;
  var scale = Math.pow(2, zoom);
  var lng = (pixel.x / scale - origin.x) / me.pixelsPerLonDegree_;
  var latRadians = (pixel.y / scale - origin.y) / -me.pixelsPerLonRadian_;
  var lat = radiansToDegrees(2 * Math.atan(Math.exp(latRadians)) - Math.PI / 2);
  return new google.maps.LatLng(lat, lng);
};
 
MercatorProjection.prototype.fromDivPixelToSphericalMercator = function(pixel, zoom) {
  var me = this;
  var coord = me.fromDivPixelToLatLng(pixel, zoom);
  
  var r= 6378137.0;
  var x = r* degreesToRadians(coord.lng());
  var latRad = degreesToRadians(coord.lat());
  var y = (r/2) * Math.log((1+Math.sin(latRad))/ (1-Math.sin(latRad)));
 
  return new google.maps.Point(x,y);
};


var projectionMap = new MercatorProjection();
var minimoZoomMercator = 9;

CustomMapWms.prototype = new google.maps.OverlayView();
function CustomMapWms(idMapa, map, name, tiled, minZoom, maxZoom, myLayers, myFormat, myVersion, myTransparent, opacity,  myBaseUrl, isAttachedToButton, alternativeSrs){
	this.overlayView = google.maps.OverlayView.call(this);
	this.alternativeSrs = alternativeSrs || srs4326;
	this.isAttachedToButton = isAttachedToButton || false;
	this.map_ = map;
	this.idMapa = idMapa;
	var me = this;
	this.getTileUrl=function(coord,zoom) {
	    
	    if(!me.tiled)return;	    
		var lULP = new google.maps.Point(coord.x*256,(coord.y+1)*256);
		var lLRP = new google.maps.Point((coord.x+1)*256,coord.y*256);
		
		var lULg = projectionMap.fromDivPixelToLatLng(lULP, zoom);
		var lLRg  = projectionMap.fromDivPixelToLatLng(lLRP, zoom);
		//var lULg = projectionMap.fromDivPixelToSphericalMercator(lULP, zoom);
		//var lLRg  = projectionMap.fromDivPixelToSphericalMercator(lLRP, zoom);
		var lBbox=lULg.lng()+","+lULg.lat()+","+lLRg.lng()+","+lLRg.lat();
		//var lBbox=lULg.x+","+lULg.y+","+lLRg.x+","+lLRg.y;
		var url =   me.getMapUrl() + "&BBOX="+lBbox+"&WIDTH=256&HEIGHT=256";
		
		return url;
	};
	this.getUrl = function () {
	    var srs = (this.map_.mapZoom < minimoZoomMercator) ? this.alternativeSrs : srs4326;
	    var srsParamName = (this.myVersion == version130) ? "CRS" : "SRS";
	    //return this.myBaseURL + "&SERVICE=WMS&VERSION=" + this.myVersion + "&LAYERS=" + this.getMapQueryLayers + "&STYLES=" + this.myStyles + "&FORMAT=" + this.format + "&BGCOLOR=0xFFFFFF&TRANSPARENT=" + this.transparent + "&" + srsParamName + "=" + srs;
	    return this.myBaseURL + "&SERVICE=WMS&VERSION=" + this.myVersion + "&LAYERS=" + this.getMapQueryLayers + "&STYLES=" + this.myStyles + "&FORMAT=" + this.format + "&TRANSPARENT=" + this.transparent + "&" + srsParamName + "=" + srs;
	};
	this.getMapUrl=function(){return this.getUrl() + "&REQUEST=GetMap";};
	this.getFeatureInfo = function (point) {
	    //if (this.myVersion == version130) {
	    //    mapBbox = this.map_.mapSouthWest.lat() + "," + this.map_.mapSouthWest.lng() + "," + this.map_.mapNorthEast.lat() + "," + this.map_.mapNorthEast.lng();
	    //}
	    //else {
	    
        mapBbox = this.map_.mapSouthWest.lng() + "," + this.map_.mapSouthWest.lat() + "," + this.map_.mapNorthEast.lng() + "," + this.map_.mapNorthEast.lat();
	    
        //}
	    if (!this.prj) this.prj = this.getProjection();
	    var aux = this.prj.fromLatLngToContainerPixel(point);
	    var url = this.getUrl() + '&REQUEST=GetFeatureInfo&QUERY_LAYERS=' + this.getFeatureInfoQueryLayers + '&FEATURE_COUNT=10&INFO_FORMAT=text/html&BBOX=' + mapBbox + '&WIDTH=' + me.map_.anchoDeMapa + '&HEIGHT=' + me.map_.altoDeMapa + '&X=' + parseInt(aux.x) + '&Y=' + parseInt(aux.y);
	    return url;

	};
	this.getMapUrlBbox = function (width, height, southWest, northEast) {
	    var swLng = southWest.lng();
	    var swLat = southWest.lat();
	    var neLng = northEast.lng();
	    var neLat = northEast.lat();
	    if (this.map_.mapZoom < minimoZoomMercator && this.alternativeSrs != srs4326) {
	        swLng = dd2MercMetersLat2(southWest.lng());
	        swLat = dd2MercMetersLat2(southWest.lat());
	        neLng = dd2MercMetersLat2(northEast.lng());
	        neLat = dd2MercMetersLat2(northEast.lat());
	    }
	    //var bbox = (this.myVersion == version130) ? swLat + "," + swLng + "," + neLat + "," + neLng : swLng + "," + swLat + "," + neLng + "," + neLat;
	    var bbox = swLng + "," + swLat + "," + neLng + "," + neLat;
	    //var bbox = (this.map_.mapZoom < minimoZoomMercator && this.alternativeSrs != srs4326) ? dd2MercMetersLat2(southWest.lng()) + "," + dd2MercMetersLat2(southWest.lat()) + "," + dd2MercMetersLat2(northEast.lng()) + "," + dd2MercMetersLat2(northEast.lat()) : southWest.lng() + "," + southWest.lat() + "," + northEast.lng() + "," + northEast.lat();
	    return this.getMapUrl() + '&BBOX=' + bbox + '&WIDTH=' + width + '&HEIGHT=' + height;
	};
	this.mapIdle = function(forceRefresh){
		if(!this.tiled){
		    if(this.isAttachedToButton){
		        
		        if (this.map_.getMapTypeId()!= nombreCapaCatastro) {
		    	    if (this.div_ ){
		    	        this.setMapa(null);
					    //this.setMap(me.map_);
				    }
				}else this.setMapa(me.map_);
			}
			else {
			    this.refresh(forceRefresh);
			}
		}
	};
	
	//this.AddRemoveListeners(true);
	var me = this;
	this.tileSize = new google.maps.Size(256, 256);
	this.minZoom = minZoom;
	this.maxZoom = maxZoom;
	this.opacity = opacity;
	//this.isPng = myFormat.indexOf('png')>-1;
	this.myStyles = '';
	this.myLayers = [myLayers];
	this.myFormat = myFormat;
	this.myVersion = trim(myVersion);
	if (this.myVersion == '') this.myVersion = "1.1.1";
	this.transparent = myTransparent;
	this.myBaseURL = myBaseUrl;
	this.name = name;
	this.tiled = tiled;
	this.prj = this.getProjection();
	this.getMapQueryLayers = "";
	this.getFeatureInfoQueryLayers = "";
	this.updateQueryLayers();
	mapasWMSCargados.push(this);
	
	return this;
}
CustomMapWms.prototype.AddRemoveListeners = function(isAdd){
    var me = this;
    if(isAdd){
        if(this.idleListener!=null)return;
        this.idleListener = google.maps.event.addListener(this.map_, "idle", function() {return me.mapIdle(false);});
        
        if(this.isAttachedToButton)
	        this.maptypeid_changedListener = google.maps.event.addListener(this.map_, "maptypeid_changed", function() {me.mapIdle(true);});
    }
    else if(this.idleListener!=null){
        if(this.isAttachedToButton)return;
        google.maps.event.removeListener(this.idleListener);
        this.idleListener = null;
    }
};
CustomMapWms.prototype.setMapa = function(theMap, avoidAddRemoveListeners){
	if(this.tiled){
	    if(theMap==null){
	        if(this.tiledOverlayNumber && this.map_!=null) {
				this.map_.overlayMapTypes.removeAt(this.tiledOverlayNumber-1);
				this.tiledOverlayNumber = null;
				this.setMap(theMap);
			}
			else return;
		}
		else {
		    
		    if(this.tiledOverlayNumber==null){
		        this.tiledOverlayNumber = this.map_.overlayMapTypes.push(new google.maps.ImageMapType(this));
		       	this.setMap(theMap);
		       	
			}
		}
	}
	else {
	    
	    if(theMap==null){
	         mapasWMSCargados.splice(mapasWMSCargados.indexOf(this),1);
	    }
	    else if (this.getMap()==null){
	        
	        if(mapasWMSCargados.indexOf(this)<0)
	            mapasWMSCargados.push(this);
	    }
	    
	    
	    this.setMap(theMap);	    
	    
	    if(avoidAddRemoveListeners)return;
	    this.AddRemoveListeners(theMap!=null);	
    }
};

CustomMapWms.prototype.seEstaMostrandoElMapa = function(mapa){
	if(this.tiled) {
	    return (this.getMap()!=null) ;
    }
	else return this.getMap()== mapa;
};
CustomMapWms.prototype.updateQueryLayers = function(){
    var me = this;
	this.getMapQueryLayers = [];
	this.getFeatureInfoQueryLayers = [];
	this.isQueryable = false;
	this.isOpaque = false;
	this.minx = false;
	this.miny = false;
	this.maxx = false;
	this.maxy = false;
	this.layerSouthWest = false;
	this.layerNorthEast = false;
	
	for(var i=0;i<this.myLayers.length;i++){
		var layer = this.myLayers[i];
		this.getMapQueryLayers.push(layer.n);
		if(layer.q && layer.q=='1'){
			this.isQueryable = true;
			this.getFeatureInfoQueryLayers.push(layer.n);
		}
		if(layer.o && layer.o=='1'){
			this.isOpaque = true;
		}
		if(layer.Minx && layer.Minx!='' && (parseFloat(layer.Minx)<this.minx || !this.minx))this.minx = parseFloat(layer.Minx);
		if(layer.Miny && layer.Miny!='' && (parseFloat(layer.Miny)<this.miny || !this.miny))this.miny = parseFloat(layer.Miny);
		if(layer.Maxx && layer.Maxx!='' && (parseFloat(layer.Maxx)>this.maxx || !this.maxx))this.maxx = parseFloat(layer.Maxx);
		if(layer.Maxy && layer.Maxy!='' && (parseFloat(layer.Maxy)>this.maxy || !this.maxy))this.maxy = parseFloat(layer.Maxy);
	}

    if(this.minx && this.miny)this.layerSouthWest = new google.maps.LatLng(this.miny, this.minx);
    if(this.maxx && this.maxy)this.layerNorthEast = new google.maps.LatLng(this.maxy, this.maxx);
    
	this.UpdateTransparent();
	this.getMapQueryLayers = escape(this.getMapQueryLayers.join(","));
	this.getFeatureInfoQueryLayers = escape(this.getFeatureInfoQueryLayers.join(","));
	this.updateFormat();
};
CustomMapWms.prototype.UpdateTransparent= function (){
    this.transparent = this.isOpaque?"FALSE":"TRUE";
};

CustomMapWms.prototype.updateFormat = function(){
	this.format = "";
	for(var i=0;i<this.myFormat.length;i++){
		var format = this.myFormat[i];
		if(this.format==""  && format.indexOf("png")>-1 && !this.isOpaque)this.format = format;
		else if(this.format==""  && format.indexOf("jpeg")>-1 && this.isOpaque)this.format = format;
	}
	if(this.format=="")this.format = this.myFormat[0];
};
CustomMapWms.prototype.addLayer = function(layer){
	this.myLayers.push(layer);
	this.updateQueryLayers();
};

CustomMapWms.prototype.removeLayer = function(layer, avoidUpdateFormat){
	this.myLayers.splice(this.myLayers.indexOf(layer),1);
	this.updateQueryLayers(avoidUpdateFormat);
};
CustomMapWms.prototype.removeAllLayers = function(){
	this.myLayers = [];
	this.getMapQueryLayers = [];
	this.getFeatureInfoQueryLayers = [];
	this.isQueryable = false;
};
CustomMapWms.prototype.UpdateGetMapCounter = function(type){
    cs(rutaPrincipal + "recursos/mapas/UpdateGetMapCounter.aspx?idMapa=" + this.idMapa+"&type="+type);
};
CustomMapWms.prototype.refresh = function(force){
    var me = this;
    if(this.tiled || !this.div_){
        this.setMapa(null, true);
        this.setMapa(this.map_, true);
		return;
	}
    
	var thisBounds = new google.maps.LatLngBounds(this.southWest, this.northEast);
	// caso en que no actualizamos la imagen porque no se ma ha movido mucho.
	if(this.zoom && this.zoom == this.map_.mapZoom && !force && this.img_ && this.img_.src && thisBounds.contains(this.map_.mapBounds.getSouthWest()) && thisBounds.contains(this.map_.mapBounds.getNorthEast())){
		return;
	}
	
	this.swpx_ = this.prj.fromLatLngToDivPixel(this.map_.mapSouthWest);
	this.nepx_ = this.prj.fromLatLngToDivPixel(this.map_.mapNorthEast);
	
	this.swpx_.x -= this.map_.extensionMapa;
	this.swpx_.y += this.map_.extensionMapa;
	this.nepx_.x += this.map_.extensionMapa;
	this.nepx_.y -= this.map_.extensionMapa;
	
	if(this.layerSouthWest){
	    var southWestAux = this.prj.fromLatLngToDivPixel(this.layerSouthWest);
	    if(southWestAux.x> this.swpx_.x) this.swpx_.x =  southWestAux.x;
	    if(southWestAux.y< this.swpx_.y) this.swpx_.y =  southWestAux.y;
	}
	if(this.layerNorthEast){
	    var northEastAux = this.prj.fromLatLngToDivPixel(this.layerNorthEast);
	    if(northEastAux.x< this.nepx_.x) this.nepx_.x =  northEastAux.x;
	    if(northEastAux.y> this.nepx_.y) this.nepx_.y =  northEastAux.y;
	}
	
	this.southWest = this.prj.fromDivPixelToLatLng(this.swpx_);
	this.northEast = this.prj.fromDivPixelToLatLng(this.nepx_);	
	this.widthMapa = Math.round(this.nepx_.x - this.swpx_.x);
	this.heightMapa = Math.round(this.swpx_.y - this.nepx_.y);
	
	this.src = this.getMapUrlBbox(this.widthMapa, this.heightMapa, this.southWest, this.northEast);	
	var loader = new ImageLoader(this.src);
	
	loader.loadEvent = function(url, image){
		me.onLoadImage(url, image);
	};
		
	if(this.zoom!=this.map_.mapZoom){
		this.removeImg();
	}
	this.zoom = this.map_.mapZoom;
	
	if(this.map_.divLoadingMapaWms)
		MostrarLoadingMapa(this.map_);
	this.loading = true;
	
	
	loader.load();
};

CustomMapWms.prototype.setOpacity = function(opacity){
    this.opacity = opacity;
};

CustomMapWms.prototype.updateImageOpacity = function(opacity){
    if(opacity)this.setOpacity(opacity);
    if(this.opacity && this.img_){
       SetStyleOpacity(this.img_, this.opacity);
    }
};

CustomMapWms.prototype.removeImg = function(){
	if(this.img_){
		this.div_.removeChild(this.img_);
		this.img_=null;
	}
};

CustomMapWms.prototype.draw = function(){
    
};
CustomMapWms.prototype.onRemove = function(){
	if(this.tiled){
		this.setMapa(null);
		return;
	}
	this.div_.parentNode.removeChild(this.div_);
	this.div_ = null;
	if(this.loading){
		OcultarLoadingMapa(this.map_);
	}
	
	if(!this.isAttachedToButton){
		this.AddRemoveListeners(false);
	}
};
/*
CustomMapWms.prototype.esCapaEspecial = function(){
    return (this.name == nombreCapaCatastro || this.name== nombreCapaCatastroSatelite) && this.map_.getMapTypeId()!= nombreCapaCatastro;
};*/

CustomMapWms.prototype.onLoadImage = function(url, image){
	if(this.map_.divLoadingMapaWms)
		OcultarLoadingMapa(this.map_);
	this.loading = false;
	if(this.div_ && url==this.src){
	    
		this.removeImg();
		this.img_ = image;
		this.updateImageOpacity();
	    this.div_.appendChild(this.img_);
		this.setMapPosition();
		
		//this.UpdateGetMapCounter("M");
	}
};

CustomMapWms.prototype.setMapPosition = function(){
    if(!this.div_)return;
    var ajustePositionTopMapa = 0;
	var ajusteDeAlturaDeMapa = 0;
	if(this.map_.mapZoom<7){
	    var centerLat = parseInt(this.map_.mapCenter.lat());
	    ajustePositionTopMapa =  this.heightMapa * centerLat * 0.0006*(7-this.map_.mapZoom);
	    ajusteDeAlturaDeMapa = Math.abs(centerLat) * 0.06*(this.map_.mapZoom-7);
	}
	
	this.div_.style.top = (this.nepx_.y + ajustePositionTopMapa) + "px";
	this.div_.style.left = (this.swpx_.x) + "px";
	this.div_.style.width = this.img_.style.width = this.widthMapa + "px";
	this.div_.style.height = this.img_.style.height = this.heightMapa + ajusteDeAlturaDeMapa + "px";
};

CustomMapWms.prototype.onAdd = function()
{
	if(this.tiled){
		this.setMapa(this.map_);
		return;
	}
	var div = $new("div");
	div.style.position = "absolute" ;

	var img = new Image();
	img.style.border = "none";

	div.appendChild(img);
	this.div_ = div ;
	this.img_ = img;
	this.getPanes().overlayLayer.appendChild(div);
	if(!this.prj)this.prj = this.getProjection();
	this.refresh();	
	
};
///////////////////////////////////////////////////////////////////////////////////////////
function CustomMapTypeEmpty(name){
	var custommap = {
	  getTileUrl:function() {},
	  tileSize: new google.maps.Size(256, 256),
	  minZoom: 0,
	  maxZoom: 21,
	  name:name
	};
	return new google.maps.ImageMapType(custommap);
}

function CustomMapSatelite(name){
	var custommap = {
	  getTileUrl:function(coord,zoom)  {
		return "http://khm1.googleapis.com/kh?v=79&hl=es&x="+coord.x+"&y="+coord.y+"&z="+zoom;
	  },
	  tileSize: new google.maps.Size(256, 256),
	  minZoom: 0,
	  maxZoom: 21,
	  name:name
	};
	return new google.maps.ImageMapType(custommap);;
};


var ImageLoader = function(url){
  this.url = url;
  this.image = null;
  this.loadEvent = null;
};

ImageLoader.prototype = {
  load:function(){
    this.image = $new('img');
    var url = this.url;
    var image = this.image;
    var loadEvent = this.loadEvent;
    google.maps.event.addDomListener(this.image, 'load', function(e){
      if(loadEvent != null){
        loadEvent(url, image);
      }
    }, false);
    this.image.src = this.url;
  },
  getImage:function(){
    return this.image;
  }
};

/////////////////////////////////////////////////////////////////////////////////////
function AnadirControlLoadingMapa(texto, map){
	var divLoadingMapaWms = $new("div");
	divLoadingMapaWms.id = "divLoadingMapaWms";
	divLoadingMapaWms.innerHTML = texto + " ..";
	divLoadingMapaWms.style.display = "none";
	map.controls[google.maps.ControlPosition.TOP].push(divLoadingMapaWms);
	map.divLoadingMapaWms = divLoadingMapaWms;
	map.contadorMapasLoading = 0;
}
function MostrarLoadingMapa(map){
	map.contadorMapasLoading+=1;
	map.divLoadingMapaWms.style.display = "";
}
function OcultarLoadingMapa(map){
	map.contadorMapasLoading-=1;
	if(map.contadorMapasLoading<=0)
		map.divLoadingMapaWms.style.display = "none";
}


///////////////////////////////////////////////////////////////////////////
function CargarAnchoYAltoDeMapa(mapa){
    if(!mapa || mapa=='undefined')return;
    if(esExplorer){mapa.anchoDeMapa= mapa.getDiv().style.pixelWidth;mapa.altoDeMapa = mapa.getDiv().style.pixelHeight;}	
	else {mapa.anchoDeMapa = parseInt(getComputedStyle(mapa.getDiv(),null).getPropertyValue('width'));mapa.altoDeMapa = parseInt(getComputedStyle(mapa.getDiv(),null).getPropertyValue('height'));}
	mapa.extensionMapa = CalcularExtensionMapa(mapa);
}
function CalcularExtensionMapa(mapa){
    if(mapa.anularExtension)return 0;
    var minimo = 40;
    var maximo = 150;
    var superficieMapa = Math.round(mapa.anchoDeMapa*mapa.altoDeMapa/4000);
    var extension = 250-(superficieMapa);
    extension =  (extension<minimo)? minimo : (extension>maximo)? maximo: extension;
    return Math.round(extension);
}

////////////////////////////////////////////////////////////////////////
var csRecursos = true; 
var csBuscar = true; 
var csCoordenadas = true; 
var csPanoramio = true;
var csMapas=true; 
var csRegistro=true; 
var csVirtualEarth=true; 
var csPGOUs = true;
var cs3d = true;
var csPagar = true;
var csMedir = true;
var csFavoritos = true;
var csCompartir = true;
var csDual = true;
var csRuta = true;
var csPerfil = true;
var csImportar = true;
var csInmuebles = true;
//var csTienda = true;
var csEncuesta = true;
var csMapInfo = true;
var csCalendar = true;
var csUsuario = true;
var csInformes = true;
var csInfo = true;

var s1 = rutaScripts+ 'recursos.js?' + versionParam; 
var s3 = rutaScripts+ 'buscar.js?'+ versionParam;
var s4 = rutaScripts+ 'jscoord-1.1.1.js?' + versionParam;
var s8 = rutaScripts+ 'mapas.js?'+ versionParam;
var s9 = rutaScripts+ 'registro.js?' + versionParam;
var s13 = rutaScripts+ 'gearth.js?' + versionParam;
var s14 = rutaScripts+ 'pagar.js?' + versionParam;
var s15 = rutaScripts+ 'medir.js?'+ versionParam;
var s16 = rutaScripts+ 'favoritos.js?' + versionParam;
var s17 = rutaScripts+ 'compartir.js?' + versionParam;
var s18 = rutaScripts+ 'dual.js?' + versionParam;
var s19 = rutaScripts+ 'ruta.js?' + versionParam;
var s20 = rutaScripts+ 'perfil.js?' + versionParam;
var s21 = rutaScripts+ 'importar.js?' + versionParam;
var s22 = rutaScripts+ 'inmuebles.js?' + versionParam;
//var s23 = rutaScripts+ 'tienda.js?' + versionParam;
var s24 = rutaScripts+ 'encuesta.js?' + versionParam;
var s25 = rutaScripts+ 'mapinfo.js?' + versionParam;
var s26 = rutaScripts+ 'calendar/js/datepicker.js?' + versionParam;
var s27 = rutaScripts+ 'usuario.js?' + versionParam;
var s28 = rutaScripts+ 'informes.js?' + versionParam;
var s29 = rutaScripts+ 'info.js?' + versionParam;


var c15 = rutaCss + "medir.css?" +versionParam;
var c16 = rutaCss + "favoritos.css?" +versionParam;
var c20 = rutaCss + "perfil.css?" +versionParam;
var c22 = rutaCss + "inmuebles.css?" +versionParam;
//var c23 = rutaCss + "tienda.css?" +versionParam;
var c26 = rutaScripts + "calendar/css/datepicker.css?" +versionParam;
var c28 = rutaCss + "informes.css?" +versionParam;
var c29 = rutaCss + "info.css?" +versionParam;

function _recursos(fn){csRecursos? csRecursos = cs(s1, fn) : fn();}
function _buscar(fn){csBuscar? csBuscar = cs(s3, fn) : fn();}
function _convertirCoordenadas(fn){csCoordenadas? csCoordenadas = cs(s4, fn) : fn();}
function _mapas(fn){csMapas? csMapas = cs(s8, fn) :  fn();}
function _registro(fn){csRegistro? csRegistro = cs(s9, fn) : fn();}
function _mostrar3d(fn){cs3d? cs3d = cs(s13, fn) : fn();}
function _pagar(fn){csPagar? csPagar = cs(s14, fn) : fn();}
function _medir(fn){csMedir? csMedir = cssjs(c15, s15, fn) : fn();}
function _perfil(fn){csPerfil? csPerfil = cssjs(c20, s20, fn) : fn();}
function _favoritos(fn){csFavoritos? csFavoritos = cssjs(c16, s16, fn) : fn();}
function _compartir(fn){csCompartir? csCompartir= cs(s17, fn) : fn();}
function _dual(fn){csDual? csDual= cs(s18, fn) : fn();}
function _ruta(fn){csRuta? csRuta= cs(s19, fn) : fn();}
function _importar(fn){csImportar? csImportar= cs(s21, fn) : fn();}
function _inmuebles(fn){csInmuebles? csInmuebles= cssjs(c22, s22, fn) : fn();}
//function _tienda(fn){csTienda? csTienda= cssjs(c23, s23, fn) : fn();}
function _encuesta(fn){csEncuesta? csEncuesta= cs(s24, fn) : fn();}
function _mapinfo(fn){csMapInfo? csMapInfo= cs(s25, fn) : fn();}
function _calendar(fn){csCalendar? csCalendar = cssjs(c26, s26, fn,'{"lang":"es"}') : fn();}
function _usuario(fn){csUsuario? csUsuario= cs(s27, fn) : fn();}
function _informes(fn){csInformes? csInformes=cssjs(c28, s28, fn) : fn();}
function _info(fn){csInfo? csInfo= cssjs(c29, s29, fn) : fn();}


////////////////////////////////////////////////////////////////////////////////////////
function cs(scriptUrl, callback,innerJs){
	e = $new("script");
	e.id = 'addedScript';
	e.lang = 'javascript';
	e.type ='text/javascript'; 
	e.charset='utf-8';
	e.content='application/x-javascript; charset=utf-8'; 
	/*e.accept = 'application/json';
	e.X-Request = 'JSON';*/
	var callbacExecuted = false;
	function ExecuteCallBack(){ 
	    if(!callbacExecuted){
	        callbacExecuted = true;
	        callback();
        }
	}
	if(callback){
	    e.onload = function(){ExecuteCallBack()};
	    e.onreadystatechange= function () {if (this.readyState == 'loaded' || this.readyState == 'complete') ExecuteCallBack();};
		
	}
	e.src = scriptUrl;
	if(innerJs && !esExplorer )e.innerHTML = innerJs;
	document.getElementsByTagName("head")[0].appendChild(e);
}

function cssjs(cssUrl, jsUrl, callback, innerJs){
	e = $new("link",{'rel':'stylesheet', 'type':'text/css'});
	e.href = cssUrl;
	if(callback){
	    setTimeout(function cssOnload() {
	        if (e.sheet) {
	            try {
	                // if (esExplorer && e.sheet.cssRules) e.sheet.cssRules.length;

	                cs(jsUrl, callback, innerJs);

	            } catch (ex) { return setTimeout(cssOnload, 30); }
	        }
	        else {
	            //if (e.styleSheet && e.styleSheet != 'undefined' && e.styleSheet.rules && e.styleSheet.rules.length > 0) {
	            if (e.styleSheet && e.styleSheet != 'undefined'){
	                cs(jsUrl, callback, innerJs);
	            }
	            else return setTimeout(cssOnload, 30);

	        }
	    });             
	}
	document.getElementsByTagName("head")[0].appendChild(e);	
}


function XmlToJson(url, callback){
	var url = rutaPrincipal+"recursos/varios/XmlToJson.aspx?theurl="+escape(url);
	if(callback)url +="&callback="+callback;
	cs(url);
}

function GetHtml(url, callback){
	var url = rutaPrincipal+"recursos/varios/GetHtml.aspx?theurl="+escape(url);
	if(callback)url+="&callback="+callback;
	cs(url);
	
}
////////////////////////////////////////////////////////////////////////////////////////
function ControlVista(theMap, callbackFail) {
	this.map_ = theMap;
	this.callbacPajaroFail = callbackFail;
	this.containerVista = $new("div");
	this.showing = false;
	var me = this;
	google.maps.event.addListener(me.map_, "maptypeid_changed", function() {me.UpdateVista ();});	
	google.maps.event.addListener(me.map_, "resize", function() {me.UpdateVista ();});	
	this.map_.controls[google.maps.ControlPosition.TOP_LEFT].push(this.containerVista);
	return this;
};

ControlVista.prototype.UpdateVista = function(){
	if(this.map_.mapTypeActual==mvar.nombreCapaVista){
	    this.map_.setOptions({navigationControl:false});
		this.containerVista.style.width = this.map_.anchoDeMapa + "px";
		this.containerVista.style.height = this.map_.altoDeMapa + "px";
		this.containerVista.style.display = "block";
		var latitud = this.map_.mapCenter.lat();
		var longitud = this.map_.mapCenter.lng();
		var ruta = rutaPrincipal+'recursos/varios/virtualearth.html?&v='+version+'&lat='+latitud+'&lng='+longitud+'&height='+this.map_.altoDeMapa+'&width='+this.map_.anchoDeMapa+'&callbackparent=CallBackChangeVistaPajaro&callbackparentfail='+this.callbacPajaroFail;
		//var texto = (esNetscape)?'<object type="text/html" data="'+ ruta +'" style="width:100%;height:100%;border:none;overflow:hidden;padding:0px;margin:0px"></object>':'<div><iframe id="frameVirtualEarth" src="'+ruta+'" style="width:'+ this.map_.anchoDeMapa  +'px;height:'+ this.map_.altoDeMapa +'px;border:none;" frameborder=0 marginheight=0 marginwidth=0 scrolling=no></iframe></div>';
		var texto = '<div style="width:'+ this.map_.anchoDeMapa  +'px;height:'+ this.map_.altoDeMapa +'px;"><iframe id="frameVirtualEarth" src="'+ruta+'" style="width:'+ this.map_.anchoDeMapa  +'px;height:'+ this.map_.altoDeMapa +'px;border:none;" frameborder=0 marginheight=0 marginwidth=0 scrolling=no></iframe></div>';
		this.containerVista.innerHTML=texto;
		this.showing = true;
	}
	else if(this.showing){
		this.containerVista.style.display = "none";
		this.map_.setOptions({navigationControl:true});
		this.showing = false;
	}
};
ControlVista.prototype.CallBackChangeVistaPajaro = function(lat, lng, zoom){
	lat=lat.toFixed(6);
	lng=lng.toFixed(6);
	if(zoom==1)zoom=18;
	else if(zoom==2)zoom=19;
	this.map_.setCenter(new google.maps.LatLng(lat, lng));
	this.map_.setZoom(zoom);
};

function CallBackChangeVistaPajaro(lat, lng, zoom){
	controlVista.CallBackChangeVistaPajaro(lat, lng, zoom);
};

// CONTROL COORDENADAS ////////////////////////////////////////////////////////////////////////////////////
function ControlCoordenadas(map, textoCentro, textoMouse, titleCentro , titleSistemaCoordenadasAux) {
	var me = this;

	this.textCookieCoordenateSystem = "goolzoom_coordinatesistem";
	this.textCookieCoordinateMouse = "goolzoom_coordinatemouse";
    
	this.coordenadasDelCentro = false;
	this.sistemaDeCoordenadas = 1;
	this.titleCentro = titleCentro;
	this.textoMouse = textoMouse;
	this.textoCentro = textoCentro;
	
	var container = $new("div"); 
	container.id = "containercoordenadas";
	if(esExplorer)container.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="'+directorioImagenes+'black50.png", sizingMethod="scale")';
	else container.style.backgroundImage = 'url('+directorioImagenes+'black50.png)';
	this.container = container;
	
	var coordenadasCambioCentroMouse = $new("div");
	coordenadasCambioCentroMouse.id = "coordenadasCambioCentroMouse";
	coordenadasCambioCentroMouse.title = titleCentro;
	this.coordenadasCambioCentroMouse = coordenadasCambioCentroMouse;
	google.maps.event.addDomListener(coordenadasCambioCentroMouse, "click", function(){
		me.CambiarCoordenadasCentroMouse();
	});
	
	
	var textoCoordenadas = $new("div");
	textoCoordenadas.id = "textoCoordenadas";
	this.textoCoordenadas = textoCoordenadas;
	
	var imagenCambiarSistemaCoordenadas = $new("div");
	imagenCambiarSistemaCoordenadas.id = "imagenCambiarSistemaCoordenadas";
	imagenCambiarSistemaCoordenadas.title = titleSistemaCoordenadasAux;
	google.maps.event.addDomListener(imagenCambiarSistemaCoordenadas, "click", function(){
		me.CambiarSistemaDeCoordenadas();
	});
	
	container.appendChild(coordenadasCambioCentroMouse);
	container.appendChild(textoCoordenadas);
	container.appendChild(imagenCambiarSistemaCoordenadas);
	
	//this.CambiarCoordenadasCentroMouse();

	var coordinateSistem = readCookie(this.textCookieCoordenateSystem);
	var coordinateMouse = readCookie(this.textCookieCoordinateMouse);
	if (coordinateSistem) this.sistemaDeCoordenadas = parseInt(coordinateSistem);
	if (coordinateMouse == "true") this.coordenadasDelCentro = true;
	this.CambiarCoordenadasCentroMouse();	
	return this;
};

ControlCoordenadas.prototype.setMap = function(map){
	map.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(this.container);
	this.UpdateCoordenadas();
};

ControlCoordenadas.prototype.CambiarSistemaDeCoordenadas = function(){
	this.sistemaDeCoordenadas+=1;
	if(this.sistemaDeCoordenadas==4)this.sistemaDeCoordenadas=1;
	createCookie(this.textCookieCoordenateSystem,this.sistemaDeCoordenadas, 365);
	this.UpdateCoordenadas();
};

ControlCoordenadas.prototype.CambiarCoordenadasCentroMouse = function () {
    var me = this;
    if (this.listener) {
        google.maps.event.removeListener(this.listener);
    }

    if (!this.coordenadasDelCentro) {
        this.coordenadasCambioCentroMouse.innerHTML = this.textoCentro;
        this.listener = google.maps.event.addListener(map, "idle", function () {
            me.UpdateCoordenadas();
        });
    }
    else {
        this.coordenadasCambioCentroMouse.innerHTML = this.textoMouse;
        this.listener = google.maps.event.addListener(map, "mousemove", function (point) {
            me.UpdateCoordenadas(point);
        });
    }

    this.coordenadasDelCentro = !this.coordenadasDelCentro;
    
    createCookie(this.textCookieCoordinateMouse, !this.coordenadasDelCentro, 365);
    me.UpdateCoordenadas();

};

ControlCoordenadas.prototype.UpdateCoordenadas = function(pointAux){
		var point = (pointAux)?pointAux.latLng: map.getCenter();
		var me = this;
		if(this.sistemaDeCoordenadas==1){
			me.textoCoordenadas.innerHTML =point.lat().toFixed(6) + ', ' + point.lng().toFixed(6);
			}
		else if (this.sistemaDeCoordenadas==2){
			_convertirCoordenadas(function(){
				me.textoCoordenadas.innerHTML =convertDecimalToMin(point.lat(),point.lng());
			});	
		}
		else if (this.sistemaDeCoordenadas==3){
			_convertirCoordenadas(function(){
				var ll = new LatLng(point.lat(),point.lng());
				var utm = ll.toUTMRef().toString();
				utm = utm.split(" ");
				me.textoCoordenadas.innerHTML =Math.floor(utm[1]) + ", "+Math.floor(utm[2]) + ", " +utm[0];
			});
		}
};


//CONTROL MEDIR /////////////////////////////////////////////////////////////////////
var midiendo = false;
var perfilando = false;
// OUTPUT CARGANDO //////////////////////////////////////////////////////////////////////////
var outputCargando;
function mostrarOutputCargando(mensaje){
	outputCargando = $new("div");
	outputCargando.id = "outputCargando";
	outputCargando.innerHTML = '<div><table border=0 cellpadding=5 cellspacing=0 width=10 id="tablaCargando"><tr valign=middle><td nowrap ><font style="font-size:16px;letter-spacing:0.1em;"><div id="textoBuscando" style="vertical-align:middle;padding:7px"><b>'+mensaje+'</b></div></font></td><td valing="middle">'+imgCargando+'</td></tr></table></div>';
	var anchoTipobj = 150;
	var altoTipobj = 45;
	
	outputCargando.style.left = (map.anchoDeMapa/2 - anchoTipobj/2)+ parseInt($("map").style.left) + "px";
	outputCargando.style.top = (map.altoDeMapa/2 - altoTipobj/2)+ 50 +"px";	
	document.getElementsByTagName("body").item(0).appendChild(outputCargando);
}
function ocultarOutputCargando(){document.getElementsByTagName("body").item(0).removeChild(outputCargando);}

// TRATAR PARAMETROS /////////////////////////////////////////////////////////////////////////////////
var lat = 0;
var lng = 0;
var north;
var east;
var zone;
var zoom = 0;
var dir = ''; 
var fc = '';
var ref='';
var ma = '';
var omc ='';
var comoimagen;
var ma = '';
var urlFichaCatastral='';
var referenciaCatastralMarcada = '';
var maptype = 0;
var openmarker = '';
var idl = ''; // idlayer
var idgr = ''; // idgrupo
var transparent = '';
var markerposition = '';
var idPedido = '';

function TratarParametros(){
	var query = location.search.substring(1);
	var pairs = query.split("&");
	for (var i=0; i<pairs.length; i++) {
		var pos = pairs[i].indexOf("=");
		var argname = pairs[i].substring(0,pos).toLowerCase();
		var value = pairs[i].substring(pos+1).toLowerCase();
		if      (argname == "lat") {lat = parseFloat(value);}
		else if (argname == "lng") {lng = parseFloat(value);}
		else if (argname == "north") {north = parseFloat(value);}
		else if (argname == "east") {east = parseFloat(value);}		
		else if (argname == "zone") {zone = parseFloat(value);}
		else if (argname == "zoom") {zoom = parseInt(value);}
		else if (argname == "dir"){dir = unescape(value);}
		else if (argname == "ref"){ref = unescape(value);}
		else if (argname == "fc") {fechaCartografia =value;}
		//else if (argname == "omc") {overviewMapControl = value==1;}
		else if (argname == "type") { maptype = value;}
		else if (argname == "marker") { markerposition = value;}
		else if (argname == "om") { openmarker = value;}
		else if (argname == "acc") { acc = value;}
		else if (argname == "comoimagen") { comoimagen = value;}
		else if (argname == "rcm") { referenciaCatastralMarcada = value;}
		else if (argname == "ma") { ma = unescape(pairs[i].substring(pos+1));}
		else if (argname == "idl") { idl = parseInt(value);}
		else if (argname == "idgr") { idgr = value.toLowerCase();}
		else if (argname == "idpedido") { idPedido = value;}
		else if (argname == "transparent") { transparent = value;}
		else if (argname == "urlfc") {urlFichaCatastral = value;urlFichaCatastral=urlFichaCatastral.replace(/!/g,"&");}
	}
}
// FUNCIONES AYUDA////////////////////////////////////////////////////////////////////////////////////
if(!Array.indexOf){Array.prototype.indexOf = function(obj){for(var i=0; i<this.length; i++){if(this[i]==obj){return i;}}return -1;};};

function setStyle(objId, style, value) {
   objId.style[style] = value;
}
/*
function getStyle(el, cssprop){
 if (el.currentStyle) //IE
  return el.currentStyle[cssprop]
 else if (document.defaultView && document.defaultView.getComputedStyle) //Firefox
  return document.defaultView.getComputedStyle(el, "")[cssprop]
 else //try and get inline style
  return el.style[cssprop]
}
*/

function SupportInputType(inputType){
    var element = $new("input", {'type':inputType});
    return element.type!="text";
    
}
function getStyle(el, prop) {
  if (document.defaultView && document.defaultView.getComputedStyle) {
    return document.defaultView.getComputedStyle(el, null)[prop];
  } else if (el.currentStyle) {
    return el.currentStyle[prop];
  } else {
    return el.style[prop];
  }
}

var setVals = function (obj, vals) {
    if (obj && vals) {
      for (var x in vals) {
        if (vals.hasOwnProperty(x)) {
          obj[x] = vals[x];
        }
      }
    }
   return obj;
};


function hasClass(ele,cls) {
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
 
function addClass(ele,cls) {
	if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}
 
function removeClass(ele,cls) {
	if (hasClass(ele,cls)) {
    	var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		ele.className=ele.className.replace(reg,' ');
	}
}

function $(value){return document.getElementById(value);}
function $new(value, options){
    var element = document.createElement(value);
    if(options){
        for (var option in options){
            element.setAttribute(option, options[option]);
            if(option=='class')element.setAttribute("className", options[option]);
        }
    }
    return element;
}
function GetDateString(){return new Date().getTime();}
function trim(cadena){return (!cadena || cadena=='')? '' : cadena.replace(/^\s*|\s*$/g,"");}
function ReplaceAll(text, busca, reemplaza){while (text.toString().indexOf(busca) != -1){text = text.toString().replace(busca,reemplaza);}return text;}
function IsNumeric(sText){var ValidChars = "0123456789";var IsNumber=true;var Char;for (i = 0; i < sText.length && IsNumber == true; i++)if (ValidChars.indexOf(sText.charAt(i)) == -1) IsNumber = false;return IsNumber;}
function tratarUrl(url){return url.split(decodeURI('%C3%91')).join("%D1");}
function ValidarUrl(url) {var v = new RegExp();v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");return v.test(url);} 
function checkEmail(email) {if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)){return (true);}}
function isUrl(s) { var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/; return regexp.test(s); }
function RandonNumber(lowerRange, upperRange) { return Math.floor(Math.random() * (upperRange - (lowerRange - 1))) + lowerRange; }
function SetBrowserTitle(title) { document.title = title + " - Goolzoom"; }

function SetStyleOpacity(obj, opacity){
    if ( typeof(obj.style.MozOpacity)   == 'string' ) {obj.style.MozOpacity   = opacity; }
    else if ( typeof(obj.style.filter)       == 'string' ) {obj.style.filter       = 'alpha(opacity:'+ opacity*100 + ')'; }
    else if ( typeof(obj.style.KHTMLOpacity) == 'string' ) {obj.style.KHTMLOpacity = opacity; }
	else if ( typeof(obj.style.opacity)      == 'string' ) {obj.style.opacity      = opacity; }
}

function RemoveAllChildNodes(element){
    if (element.hasChildNodes() )
	{
		while ( element.childNodes.length >= 1 )
		{
			element.removeChild( element.firstChild );       
		} 
	}
	return element;
}
function currentMapTypeNumber(){
	var type=-1; 
	for(var i=0;i<map.getMapTypes().length;i++){
		if(map.getMapTypes()[i]==map.getCurrentMapType()) type=i;
	} 
	return type;
} 
function mapTypePorNombreMapa(nombreMapa){return nombreMapa;}
function BorrarMarkerEInfoWindow(){
	referenciaCatastralMarcada='';
	if(infowindow)infowindow.close();
	if(marker)marker.setMap(null);	
	infowindow=null;
	marker=null;
	for(var i=0; i<listaMarkersAux.length; i++){
		listaMarkersAux[i].setMap(null);
		}
	listaMarkersAux= [];
	}
function truebody(){return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body}
function getElementsByName_iefix(tag, name) {
     var elem = document.getElementsByTagName(tag);
     var arr = new Array();
     for(i = 0,iarr = 0; i < elem.length; i++) {
          att = elem[i].getAttribute("name");
          if(att == name) {
               arr[iarr] = elem[i];
               iarr++;
          }
     }
     return arr;
}
function disableSelection(target){
	if (typeof target.onselectstart!="undefined") //IE route
		target.onselectstart=function(){return false};
	else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
		target.style.MozUserSelect="none";
	else //All other route (ie: Opera)
		target.onmousedown=function(){return false};
	//target.style.cursor = "default"
}
 function findTotalOffset(obj) {
      var ol = ot = 0;
      if (obj.offsetParent) {
        do {
          ol += obj.offsetLeft;
          ot += obj.offsetTop;
        }while (obj = obj.offsetParent);
      }
      return {left : ol, top : ot};
    }

function DownloadFile(url){
    var iframe = $new("iframe");
    iframe.src = url;
    iframe.setAttribute("frameborder", "0");
    var body = document.getElementsByTagName("body")[0];
    body.appendChild(iframe);
    //setTimeout(function(){body.removeChild(iframe);},500);
    iframe.style.display="none";
}
// COOKIES /////////////////////////////////////////////////
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


