Array.prototype.findIndex = function(v){ for (var i=0; i < this.length; i++) { if (this[i] == v) { return i; } } return false; };
var IMAGES = ["purple", "yellow", "blue", "white", "green", "red", "black", "orange", "gray", "brown" ];
var NAMES = [];
var TYPES = [];
var ICONS = [];
var G_ACCURACY = ["Unknown location", "Country level accuracy", "Region level accuracy", "Sub-region level accuracy", "Town level accuracy", "Postal code level accuracy", "Street level accuracy", "Intersection level accuracy", "Address level accuracy"];
var G_RESPONSE = {500:"A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.",602:"No corresponding geographic location could be found for the specified address. This may be due to the fact that the address is relatively new, or it may be incorrect.",603:"The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons."};
var G_ACC_ZOOM = [5,5,7,9,11,13,15,16,16];
/*var lg = new Image();        
lg.src = '/images/legend.gif';*/



function createMarker(place) {
  var point = new GLatLng(place.lat, place.lng);
  var marker = new GMarker(point, {title:place.address, icon:ICONS[place.icon]});
  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(place.html);
  });
  return marker;
}
function permalinkShow(h) { 
  $("#ltdp")[0].value = $("#permalink")[0].href;
  h.w.show().find("input:first:visible:enabled")[0].focus();
}

function jqmShow(h) { 
  $("#tool")[0].selectedIndex = 0;                                                              
  $("#tool").trigger('change');
  $(".M").hide().jqmHide(); 
  h.w.css('opacity',0.92).show().find("input:enabled:visible:first")[0].focus(); 
}
function jqmHide(h) { 
  h.w.hide(0, function() { console.error(h); if(h.o) h.o.remove(); }); 
}
$(function(){  
  /*xajax_loadProvinces();*/
  $('.def').def();
  $('#divSearch')
    .jqm({trigger:'#linkSearch',
          overlay: 0,
       closeClass:'X',
           onShow: jqmShow,
           onHide: jqmHide });
  $('#divAddress')
    .jqm({trigger:'#linkAddress',
          overlay: 0,
       closeClass:'X',
           onShow: jqmShow,
           onHide: jqmHide });

  $('#divGoto')
    .jqm({trigger:'#linkGoto',
          overlay: 0,
       closeClass:'X',
           onShow: jqmShow,
           onHide: jqmHide });

  $('#divRef')
    .jqm({trigger:'#linkRef',
          overlay: 0,
       closeClass:'X',
           onShow: jqmShow,
           onHide: jqmHide });
           
  $('#divPp')
    .jqm({trigger:'#linkPp',
          overlay: 0,
       closeClass:'X',
           onShow: jqmShow,
           onHide: jqmHide });
  
  $('#divShare')
    .jqm({trigger:'#permalink',
          overlay: 0,
     /*overlayClass: 'divShareOverlay',*/
       closeClass:'X',
           onShow: permalinkShow,
           onHide: jqmHide });           
           
  $('#linkPp').one('click', function(){ 
    var ppDP = $("#ppDefaultPro")[0].value;
    var ppDM = $("#ppDefaultMun")[0].value;
    if(ppDP && ppDM) {
       xajax_loadPpProvinces(ppDP, ppDM);
    } else {
       xajax_loadPpProvinces();
    }
  });
  
  $('#t_welcome').bind('click', function(){ $(".M").hide().jqmHide(); });    
  
  $('img.X').bind('click', function() {  $(".M").hide().jqmHide(); });
    $("#frm .handle img").bind('click',
	  function(){
	  	if(5 == parseInt($("div#frm").css("width"))) {
	  		$("div#form").show();
            $("div#frm").css({ width: "160px" });
            $("#handlebar")[0].src = hf.src; 
	  	} else {
            $(".M").hide().jqmHide(); 
			$("div#frm").css({ width: "5px" });
            $("#handlebar")[0].src = hu.src;
            $("div#form").hide();
		}
	  }
	);
	$("#lgn .handle img").bind('click',
	  function(){
		if(0 == parseInt($("#lgn").css("left"))) {
	  	  $("#lgn").css({ left: "-133px" });
	  	  $("#lgnbar")[0].src = hf.src;
	  	} else {
	  	  $("#lgn").css({ left: "0" });
	  	  $("#lgnbar")[0].src = hu.src;
		}  
	  }
	);
	$("form#frmSearch").bind('submit', function(){
      var q = this.q.value;
      if(!q) return;
      
      resetAdvancedPermalink();
      document.permalink.q = q;
      document.permalink.updated(); 
      
      $("div#result").empty();
      $("<p>Please wait...</p>").appendTo("div#result");
      document.geocoder.getLocations(this.q.value+', spain', showLocationWrapperSearch);
      return false;
    });
    $("form#frmAddress").bind('submit', function(){
      var q = this.addStreet.value + ', ' + this.addTown.value + ', ' + this.addProv.value;
      if(!q) return;
      
      resetAdvancedPermalink();     
      document.permalink.addStreet = this.addStreet.value;
      document.permalink.addTown = this.addTown.value;
      document.permalink.addProv = this.addProv.value;
      document.permalink.updated(); 
      
      $("div#addresult").empty();
      $("<p>Please wait...</p>").appendTo("div#addresult");
      document.geocoder.getLocations(q+', spain', showLocationWrapperAddress);
      return false;
    });
    $("form#frmGoto").bind('submit', function(){
      if('' == this.goLat.value || '' == this.goLng.value) return;
      document.map.clearOverlays();
      var nuLat = Math.floor(parseFloat(this.goLat.value)*1e5)/1e5;
      var nuLng = Math.floor(parseFloat(this.goLng.value)*1e5)/1e5;
      resetAdvancedPermalink();     
      document.permalink.goLat = nuLat;
      document.permalink.goLng = nuLng;
      document.permalink.updated(); 
      var point = new GLatLng(nuLat, nuLng);
      document.map.setCenter(point);
      var marker = new GMarker(point, {title:('Lat/Lng:'+nuLat+','+nuLng),clickable:false,draggable:false});
      document.map.addOverlay(marker);
      return false;
    });  
    $("form#frmRef").bind('submit', function(){
      if('' == this.ref.value) return;
      
      resetAdvancedPermalink();
      document.permalink.ref = this.ref.value;
      document.permalink.updated(); 
      
      if(!this.refBtn.disabled) { 
        if(this.refTrigger.value) {
          xajax_findCadastralReference(this.ref.value, true);
          this.refTrigger.value = '';
        } else {
          xajax_findCadastralReference(this.ref.value);
        }
        $("#refBtn", this).html('Please wait...');
        this.refBtn.disabled = true;
      }
      return false;
    });   
    $("form#frmPp").bind('submit', function(){
      if('' == this.ppPro.value || '' == this.ppMun.value) return;
      
      resetAdvancedPermalink();     
      document.permalink.ppPro = this.ppPro.value;
      document.permalink.ppMun = this.ppMun.value;
      document.permalink.ppPo = this.ppPo.value;
      document.permalink.ppPa = this.ppPa.value;
      document.permalink.updated(); 
    
      if(!this.ppBtn.disabled) { 
        if(this.ppTrigger.value) {
          xajax_findPp(this.ppPro.value, this.ppMun.value, this.ppPo.value, this.ppPa.value, true);
          this.ppTrigger.value = '';
        } else {
          xajax_findPp(this.ppPro.value, this.ppMun.value, this.ppPo.value, this.ppPa.value);
        }
        $("#ppBtn", this).html('Please wait...');
        this.ppBtn.disabled = true;
      }
      return false;
    });   
});
function showCadastralOnMap(c,t) {
  $("#refBtn").html('Locate on Map!')[0].disabled = false;
  if(!c) {
    $("#divRef span.info").html('Cadastral Reference not found, please try again.');
  } else {
    $("#divRef span.info").html('<br /><p>'+c.xtr+'<br />Cadastral Information: <a href="'+c.url+'&TB_iframe=true&height=420&width=760" class="thickbox">'+c.ref+'</a></p>');
    tb_init('a.thickbox');
    var point = new GLatLng(c.lat, c.lng);
    var marker = new GMarker(point, {title:c.xtr,clickable:false,draggable:false});
    document.map.setCenter(point, 16);
    document.map.addOverlay(marker);
    if(t)$("#divRef a.thickbox").trigger('click');
  }           
                                              
}
function showPpOnMap(c,t) {
  $("#ppBtn").html('Locate on Map!')[0].disabled = false;
  if(!c) {
    $("#divPp span.info").html('Cadastral Reference not found, please try again.');
  } else {
    $("#divPp span.info").html('<br /><p>'+c.xtr+'<br />Cadastral Information: <a href="'+c.url+'&TB_iframe=true&height=420&width=760" class="thickbox">'+c.ref+'</a></p>');
    var point = new GLatLng(c.lat, c.lng);
    var marker = new GMarker(point, {title:c.xtr,clickable:false,draggable:false});
    document.map.setCenter(point, 16);
    document.map.addOverlay(marker);
    tb_init('a.thickbox');
    if(t)$("#divPp a.thickbox").trigger('click'); 
  }           
}
function GLoad() {
      if (GBrowserIsCompatible()) {
        document.permalink = new PermalinkBuilder();
        var WMS_CATASTRO="http://ovc.catastro.meh.es/Cartografia/WMS/ServidorWMS.aspx?";
        var WMS_SIGPAC="http://wms.mapa.es/wms/wms.aspx?";
        var G_OPAQUE_CATASTRO = createWMSSpec(WMS_CATASTRO, "Catastro", "Catastro", "catastro", "default", "image/png", "1.1.1", "0xFFFFFF", "FALSE", 9, 20, "EPSG:4326");
        var G_TRANSPARENT_CATASTRO = createWMSSpec(WMS_CATASTRO, "Catastro", "Catastro", "catastro", "default", "image/png", "1.1.1", "0xFFFFFF", "TRUE", 9, 20, "EPSG:4326");
        var G_MAP_CATASTRO = createWMSOverlaySpec(G_NORMAL_MAP, G_TRANSPARENT_CATASTRO, "Catastro*", "Catastro*");
        var G_SATELLITE_CATASTRO = createWMSOverlaySpec(G_SATELLITE_MAP, G_TRANSPARENT_CATASTRO, "Catastro+", "Catastro+");
        
        GMap2.prototype.layers = [];
        GMap2.prototype.setPoints = function(layer, points) {
            this.layers[layer] = points;
            this.showLayer(layer);
        }
        GMap2.prototype.clearPoints = function(layer) {
            this.layers[layer] = null;
        }
        GMap2.prototype.showLayer = function(layer) {
            var a=this.layers[layer];
            for (i=0;i<a.length;i++) {
              map.addOverlay(a[i]);
            }
        }
        GMap2.prototype.hideLayer = function(layer) {
            var a=this.layers[layer];
            for (i=0;i<a.length;i++) {
              map.removeOverlay(a[i]);
            }
        }
        var map = new GMap2(document.getElementById("gmap"), {draggableCursor: 'pointer', draggingCursor: 'pointer'});
        CustomGetTileUrl=function(p,z){
        var x=p.x;
        var y=p.y;
        z = 17 - z;
        return "http://www.andalucia-direct.com/googletiles/demo/tile_"+x+"_"+y+"_"+z+".jpg";
      }
        
      var satlayers = G_HYBRID_MAP.getTileLayers();
      var satlayer = satlayers[0];
      var roadlayer = satlayers[1];

      var maplayers = G_NORMAL_MAP.getTileLayers();
      var maplayer = maplayers[0];
      var tilelayers = [new GTileLayer(new GCopyrightCollection("Shaded Relief &copy; maps.data-spain.com"),5,9)];
        tilelayers[0].getTileUrl = CustomGetTileUrl;
        tilelayers[0].getCopyright = function(a,b) {
        return {prefix:"Shaded Relief &copy; ", copyrightTexts:["maps.data-spain.com"]};
      }
      var custommap = new GMapType(tilelayers, G_SATELLITE_MAP.getProjection(), "Relief");
//        map.addMapType(custommap);

      var tilelayers = [new GTileLayer(new GCopyrightCollection("Shaded Relief &copy; data-spain.com"),5,9), roadlayer];
        tilelayers[0].getTileUrl = CustomGetTileUrl;
        tilelayers[0].getCopyright = function(a,b) {
        return {prefix:"Shaded Relief &copy; ", copyrightTexts:["maps.data-spain.com"]};
      }
      var custommap2 = new GMapType(tilelayers, G_SATELLITE_MAP.getProjection(), "Relief+",{minResolution:0,maxResolution:9});
//        map.addMapType(custommap2);
        
        NaturalGetTileUrl=function(p,z){
        var x=p.x;
        var y=p.y;
        z = 17 - z;
        return "http://www.andalucia-direct.com/googletiles/natural/tile_"+x+"_"+y+"_"+z+".jpg";
      }
        
         var tilelayers = [new GTileLayer(new GCopyrightCollection("Natural Earth - Tom Patterson - shadedrelief.com"),5,7)];
      tilelayers[0].getTileUrl = NaturalGetTileUrl;
      tilelayers[0].getCopyright = function(a,b) {
        return {prefix:"Natural Earth - ", copyrightTexts:["Tom Patterson - shadedrelief.com"]};
      }
      document.natural = new GMapType(tilelayers, G_SATELLITE_MAP.getProjection(), "Natural");
      //map.addMapType(document.natural);

      var tilelayers = [new GTileLayer(new GCopyrightCollection("Natural Earth - Tom Patterson - shadedrelief.com"),5,7), roadlayer];
      tilelayers[0].getTileUrl = NaturalGetTileUrl;
      tilelayers[0].getCopyright = function(a,b) {
        return {prefix:"Natural Earth - ", copyrightTexts:["Tom Patterson - shadedrelief.com"]};
      }
      document.naturalplus = new GMapType(tilelayers, G_SATELLITE_MAP.getProjection(), "Natural+",{minResolution:0,maxResolution:7});
      //map.addMapType(document.naturalplus);        
        
        getMsveDirection = function(x, y)
      {
        if (x == 1){
          if (y == 1){
            return '3';
          } else if (y == 0){
            return '1';
          }
        } else if (x == 0) {
          if (y == 1){
            return '2';
          } else if (y == 0){
            return '0';
          }
        }
        return '';
      }
      getMsveString = function(x, y, z)
      {
         var rx, x, ry, y;
         var s = '';
         for(var i = 17; i > z; i--){
            rx = x % 2;
            x = Math.floor(x / 2);
            ry = y % 2;
            y = Math.floor(y / 2);
            s = getMsveDirection(rx, ry) + s;
         }
         return s;
      }
      getMsveServer = function(x, y, z)
      {
         var rx, x, ry, y;
         var s = '';
         for(var i = 17; i > z; i--){
            rx = x % 2;
            x = Math.floor(x / 2);
            ry = y % 2;
            y = Math.floor(y / 2);
            s = getMsveDirection(rx, ry);
         }
         return s;
      }
      CustomGetTileUrl=function(p,z){
        var x=p.x;
        var y=p.y;
        z = 17 - z;
        var s=getMsveString(x,y,z);
        var v=getMsveServer(x,y,z);
        return 'http://r'+v+'.ortho.tiles.virtualearth.net/tiles/r'+s+'.png?g=1';
      }
      var msvelayer = new GTileLayer(new GCopyrightCollection("(c) 2006 Microsoft Corporation"),5,17);
      msvelayer.getTileUrl = CustomGetTileUrl;
      msvelayer.getCopyright = function(a,b) {
        return {prefix:"", copyrightTexts:["&copy; 2006 Microsoft Corporation &copy; 2006 NAVTEQ"]};
      }
      var msvelayers = [msvelayer];
      document.vemap = new GMapType(msvelayers, G_SATELLITE_MAP.getProjection(), "VE");
      
      document.normalmap = new GMapType([maplayer], G_NORMAL_MAP.getProjection(), "Map",{minResolution:5,maxResolution:17});
      map.removeMapType(G_NORMAL_MAP);      
      map.addMapType(document.normalmap);
      NAMES.push('Map');
      TYPES.push(document.normalmap);
     
      document.satmap = new GMapType([satlayer], G_SATELLITE_MAP.getProjection(), "Satellite",{minResolution:5,maxResolution:18});
      map.removeMapType(G_SATELLITE_MAP);
      map.addMapType(document.satmap);
      NAMES.push('Satellite');
      TYPES.push(document.satmap);
     
      document.hybridmap = new GMapType([satlayer, roadlayer], G_SATELLITE_MAP.getProjection(), "Hybrid",{minResolution:5,maxResolution:17});
      map.removeMapType(G_HYBRID_MAP);
      map.addMapType(document.hybridmap);
      NAMES.push('Hybrid');
      TYPES.push(document.hybridmap);
     
      map.addMapType(document.vemap);
      NAMES.push('VE');
      TYPES.push(document.vemap);
     
      var catastro_opaque_layer = createWMSTileLayer(WMS_CATASTRO, "Catastro", "Catastro", "catastro", "default", "image/png", "1.1.1", "0xFFFFFF", "FALSE", 9, 21, "EPSG:4326");
      var catastro_transparent_layer = createWMSTileLayer(WMS_CATASTRO, "Catastro", "Catastro", "catastro", "default", "image/png", "1.1.1", "0xFFFFFF", "TRUE", 9, 21, "EPSG:4326");
      
      var sigpac_ortho_opaque_layer = createWMSTileLayer(WMS_SIGPAC, "Sigpac", "Sigpac", "ORTOFOTOS", "default", "image/jpeg", "1.1.1", "0xFFFFFF", "FALSE", 9, 21, "EPSG:4230");
      
      document.sigpac = new GMapType([sigpac_ortho_opaque_layer], G_SATELLITE_MAP.getProjection(), "Sigpac",{minResolution:14,maxResolution:21});
      map.addMapType(document.sigpac);
      NAMES.push('Sigpac');
      TYPES.push(document.sigpac);

      document.catastro = new GMapType([catastro_opaque_layer], G_SATELLITE_MAP.getProjection(), "Cadastral",{minResolution:9,maxResolution:21});
      map.addMapType(document.catastro);
      NAMES.push('Cadastral');
      TYPES.push(document.catastro);

      document.mapplus = new GMapType([maplayer, catastro_transparent_layer], G_SATELLITE_MAP.getProjection(), "Map+",{minResolution:9,maxResolution:17});
      map.addMapType(document.mapplus);
      NAMES.push('Map+');
      TYPES.push(document.mapplus);
      
      document.satplus = new GMapType([satlayer, catastro_transparent_layer], G_SATELLITE_MAP.getProjection(), "Satellite+",{minResolution:9,maxResolution:18});
      map.addMapType(document.satplus);
      NAMES.push('Satellite+');
      TYPES.push(document.satplus);
      
      document.hybplus = new GMapType([satlayer, roadlayer, catastro_transparent_layer], G_SATELLITE_MAP.getProjection(), "Hybrid+",{minResolution:9,maxResolution:17});
      map.addMapType(document.hybplus);
      NAMES.push('Hybrid+');
      TYPES.push(document.hybplus);
      
      document.veplus = new GMapType([msvelayer, catastro_transparent_layer], G_SATELLITE_MAP.getProjection(), "VE+",{minResolution:9,maxResolution:17});
      map.addMapType(document.veplus);
      NAMES.push('VE+');
      TYPES.push(document.veplus);
      
      document.sigpacplus = new GMapType([sigpac_ortho_opaque_layer, catastro_transparent_layer], G_SATELLITE_MAP.getProjection(), "Sigpac+",{minResolution:14,maxResolution:21});
      map.addMapType(document.sigpacplus);
      NAMES.push('Sigpac+');
      TYPES.push(document.sigpacplus);  
//      map.addMapType(G_OPAQUE_CATASTRO);
//      map.addMapType(G_MAP_CATASTRO);
//      map.addMapType(G_SATELLITE_CATASTRO);
	  map.addControl(new GScaleControl());
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      map.addControl(new DragZoomControl({},{buttonHTML:"<img src='/images/dz.gif' />",buttonStartingStyle:{width:'16px',height:'16px',padding:0,margin:0,position:'absolute',border:'1px solid #000'},buttonZoomingHTML:"<img src='/images/dza.gif' />",overlayRemoveTime:10000},{}));
	  map.enableDoubleClickZoom();
	  map.enableContinuousZoom();
	  
    	map.addControl(new GOverviewMapControl(new GSize(160,160)));
    	document.permalink.updated = function() {
          $("#permalink").attr('href', 'http://www.maps.data-spain.com/cadastral/'+this.getParams());
        }
        GEvent.addListener(map, 'moveend', function() {
          var center = document.map.getCenter();
          document.permalink.lat = (Math.floor(center.lat()*1e5)/1e5);
          document.permalink.lng = (Math.floor(center.lng()*1e5)/1e5);
          document.permalink.updated();
        });
        
        GEvent.addListener(map, 'zoomend', function(oldLevel, newLevel) {
          document.permalink.zoom = newLevel;
          document.permalink.updated();
        });
        
        GEvent.addListener(map, 'maptypechanged', function(oldLevel, newLevel) {
          var type = document.map.getCurrentMapType();
          var name = type.getName();
          document.permalink.type = NAMES.findIndex(name);
          document.permalink.updated();
        });
        
		var lstner1 = GEvent.addListener(map, 'mousemove', function(latlng){
		  $("#llbox").html('Lat/Lng: '+Math.round(latlng.lat()*100000)/100000+','+Math.round(latlng.lng()*100000)/100000);
        });
		var lstner2 = GEvent.addListener(map, 'maptypechanged', function(){
		  var mt = document.map.getCurrentMapType();
		  var mn = mt.getName();
		  if(/Cadastral/.test(mn)) {
			    /*$("#legend img")[0].src = lg.src;*/
            $("#lgn").css({display:"block"});
 		  } else {
            $("#lgn").css({display:"none"});
		  }
        });
         
      var lstner4 = GEvent.addListener(map, "moveend", function() {
        var C = document.map.getCenter();
        var curLat = C.lat();
        var curLng = C.lng();
        var minLat = 26.275447;
        var minLng = -18.409876;
        var maxLat = 44.85536;
        var maxLng = 5.22598;
        var needFix = false;
        if (curLat < minLat) {curLat = minLat; needFix = true;}
        if (curLat > maxLat) {curLat = maxLat; needFix = true;}
        if (curLng < minLng) {curLng = minLng; needFix = true;}
        if (curLng > maxLng) {curLng = maxLng; needFix = true;}
        if(needFix) {
        	map.setCenter(new GLatLng(curLat,curLng));
        }
      });
  
      for(var i in IMAGES){
	  var icon = new GIcon();
      icon.iconSize = new GSize(12, 20);
      icon.shadowSize = new GSize(22, 20);
      icon.iconAnchor = new GPoint(6, 20);
      icon.infoWindowAnchor = new GPoint(5, 1);
  	  icon.image = "http://labs.google.com/ridefinder/images/mm_20_"+IMAGES[i]+".png";
  	  icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
      ICONS[IMAGES[i]] = icon;
    }
	for(var counter = 0;counter < 25; counter++) {
	  var letter = String.fromCharCode("ABCDEFGHIJKLMNOPQRSTUVWXYZ".charCodeAt(counter));
      var icon = new GIcon(G_DEFAULT_ICON, "http://www.google.com/mapfiles/marker" + letter + ".png");
      icon.printImage = "http://maps.google.com/mapfiles/marker"+letter+"ie.gif"
      icon.mozPrintImage = "http://maps.google.com/mapfiles/marker"+letter+"ff.gif"	
      ICONS[letter] = icon;
	}
    var icon = new GIcon(G_DEFAULT_ICON, "http://www.google.com/mapfiles/dd-start.png");
    icon.printImage = "http://www.google.com/mapfiles/dd-startie.gif"
    icon.mozPrintImage = "http://www.google.com/mapfiles/dd-startff.gif"    
    ICONS['start'] = icon;
    var icon = new GIcon(G_DEFAULT_ICON, "http://www.google.com/mapfiles/dd-end.png");
    icon.printImage = "http://www.google.com/mapfiles/dd-endie.gif"
    icon.mozPrintImage = "http://www.google.com/mapfiles/dd-endff.gif"    
    ICONS['end'] = icon;
    document.searchN = 0;
    return map;
    }
 }
 function showPlaces(places, div){
    document.map.clearOverlays();
    document.map.clearPoints('current');
    $("div#"+div).empty();
    $("<ul id=\"list\"></ul>").prependTo("div#"+div);
    document.markers = new Array();
    document.markerhtmls = new Array();
	var counter=0;
    for(var i in places) {
	  var letter = String.fromCharCode("ABCDEFGHIJKLMNOPQRSTUVWXYZ".charCodeAt(counter));
	  counter++;
      var place = places[i];
	  if(place.Point) {
      var c = place.Point.coordinates;
	  place.lat = c[1];
	  place.lng = c[0];
	  place.icon = letter;
	  var p = new GLatLng(c[1],c[0]);
	  var a = place.AddressDetails.Accuracy;
	  var d = place.address;
	  var e = place.id;
	  if(8 > a) {
	       document.markerhtmls[i] = '<div id="mInfo">'+d+'<br />'+c[1]+', '+c[0]+'<br />'+G_ACCURACY[a]+'</div>';
		   place.html = '<div id="mInfo">'+d+'<br />'+c[1]+', '+c[0]+'<br />'+G_ACCURACY[a]+'</div>';
		   $("<li><a href=\"javascript:document.map.setCenter(new GLatLng("+c[1]+","+c[0]+"), "+G_ACC_ZOOM[a]+");showInfo("+i+");\" title=\""+d+"\">"+d+"</a></li>").appendTo("ul#list");
      }  else {
		   document.markerhtmls[i] = '<div id="mInfo">'+d+'<br /><span id="'+e+'">Please wait...</span></div>';
	       place.html = '<div id="mInfo">'+d+'<br /><span id="'+e+'">Please wait...</span></div>';
		   $("<li><img src=\"http://www.google.com/mapfiles/marker" + letter + ".png\" /><span><a href=\"javascript:document.map.setCenter(new GLatLng("+c[1]+","+c[0]+"), "+G_ACC_ZOOM[a]+");getFeatureInfo(new GLatLng("+c[1]+","+c[0]+", '"+e+"');showInfo("+i+");\" title=\""+d+"\">"+d+"</a></span></li>").appendTo("ul#list");
	  }
 	  document.markers[i] = createMarker(place);
	  }
  	}
  	$("<div class=\"clear\"></div>").appendTo("div#"+div);
    $("#list img").pngfix();
  	document.map.setPoints('current', document.markers);
}
function showInfo(i) {
  document.markers[i].openInfoWindowHtml(document.markerhtmls[i]);
}
function toggleForm() {
  if($("#frmSearch").is(":visible")) {
    $("#frmSearch").hide('slow', function(){
       $("#frmSearch *").hide();
       $("#frmAdvancedSearch *").show(); 
       $("#frmAdvancedSearch").show('slow');
    });
  } else {
    $("#frmAdvancedSearch").hide('slow', function(){
      $("#frmAdvancedSearch *").hide();
      $("#frmSearch *").show();
      $("#frmSearch").show('slow');
    });
  }
}
function loadProvinces(pros){
  var result = TrimPath.processDOMTemplate("provincias_jst", {pros:pros});
  $("#pro").empty().unbind('change').bind('change', function(){ getMunicipios(this.value); }).html(result);
}
function loadPpProvinces(pros, i){
  var result = TrimPath.processDOMTemplate("provincias_jst", {pros:pros});
  if($("#ppPro").html(result).unbind('change').bind('change', function(){ getPpMunicipios(this.value); }) && i) {
    if($.browser.msie && $.browser.version <= 6) {
       window.setTimeout('$("#ppPro")[0].selectedIndex = '+i+';', 1000); 
    } else {
       $("#ppPro")[0].selectedIndex = i;
    }
  } else {
    $("#ppPro")[0].selectedIndex = 0;
  }
}
function getMunicipios(pro) {
  if(!pro) {
    $("#mun").empty().html('<option>Please select a province</option>');
    return;
  }
  if((undefined != document.municipios) && (undefined != document.municipios[pro])) {
    $("#mun").empty().unbind('change').bind('change', function(){ getVias(this.form.pro.value, this.value); }).html(document.municipios[pro]);
  } else {
    xajax_loadMunicipals(pro);  
  }
}
function getPpMunicipios(pro) {
  if(!pro) {
    $("#ppMun").html('<option>Municipal Area</option>');
    return;
  }
  if((undefined != document.municipios) && (undefined != document.municipios[pro])) {
    $("#ppMun").html(document.municipios[pro]);
  } else {
    $("#ppMun").html('<option>Please wait...</option>');
    xajax_loadPpMunicipals(pro);  
  }
}
function loadMunicipals(pro, muns){
  var result = TrimPath.processDOMTemplate("municipios_jst", {muns:muns});
  $("#mun").empty().unbind('change').bind('change', function(){ getVias(this.form.pro.value, this.value); }).html(result);
  if(undefined == document.municipios) document.municipios = new Array;
  document.municipios[pro] = result;
}
function loadPpMunicipals(pro, muns, i){
  var result = TrimPath.processDOMTemplate("municipios_jst", {muns:muns});
  if($("#ppMun").html(result) && i) { 
    if($.browser.msie && $.browser.version <= 6) {
       window.setTimeout('$("#ppMun")[0].selectedIndex = '+i+';', 1000); 
       window.setTimeout('$("#ppBtn").trigger("click");', 1500); 
    } else {
       $("#ppMun")[0].selectedIndex = i;
       $("#ppBtn").trigger("click");
    }  
  } else {
    $("#ppMun")[0].selectedIndex = 0;
  }
  if(undefined == document.municipios) document.municipios = new Array;
  document.municipios[pro] = result;
}
function getVias(pro, mun) {
  if(!mun) {
	$("#str").empty().html('<option>Please select a municipal</option>');
	return;
  }
  if((undefined != document.vias) && (undefined != document.vias[pro]) && (undefined != document.vias[pro][mun])) {
	$("#str").empty().html(document.vias[pro][mun]);
  } else {
	xajax_loadStreets(pro, mun);  
  }
}

function loadStreets(pro, mun, strs){
  var result = TrimPath.processDOMTemplate("vias_jst", {strs:strs});
  $("#str").empty().html(result);
  if(undefined == document.vias) document.vias = new Array;
  if(undefined == document.vias[pro]) document.vias[pro] = new Array;
  document.vias[pro][mun] = result;
}

function showParcel(html, ref, lat, lng){
  $("#mInfo").html(html);
  tb_init('a.thickbox');
}
function showCadastralInfo(html, ref, lat, lng, name, trigger){
    /*var marker = new GMarker(new GLatLng(lat, lng), {title:name});
    document.map.clearOverlays();
    document.map.addOverlay(marker);
    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml('<div id="mInfo">'+html+'</div>');
    });
    marker.openInfoWindowHtml('<div id="mInfo">'+html+'</div>');
    */
    $("#cdstrl").html(html);
    tb_init('a.thickbox');
    if(trigger) {
       $("#infodiv").highlightFade({start:'#0f0',end:'#cfc', speed:'slow', complete:function(){$("#cdstrl a").trigger('click');} });    } else {
       $("#infodiv").highlightFade({start:'#0f0',end:'#cfc', speed:'slow'});    
    }
}

function showFeatureInfo(html, id){
  $("#"+id).html(html);
  tb_init('a.thickbox');
}

function showLocationWrapperSearch(point) {
  showLocation(point, 'result');
}
function showLocationWrapperAddress(point) {
  showLocation(point, 'addresult');
}
function showLocation(point, div){
  $("div#"+div).empty();
  var v = point.Status.code;    
  if(200 == v) {
     if(point.Placemark.length > 1) {
        var places = point.Placemark;
        showPlaces(places, div);
     } else {
        $("div#"+div).empty();
        var c = point.Placemark[0].Point.coordinates;
        var p = new GLatLng(c[1],c[0]);
        var a = point.Placemark[0].AddressDetails.Accuracy;
        var html = '<div id="mInfo">'+ point.Placemark[0].address+'<br />'+c[1]+', '+c[0]+'<br />'+G_ACCURACY[a]+'</div>';
        document.map.clearOverlays();
        document.map.setCenter(p, G_ACC_ZOOM[a]);
        var marker = new GMarker(p, {title:point.Placemark[0].address});
        document.map.addOverlay(marker);
        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml(html);
        });
        marker.openInfoWindowHtml(html);
     }
  } else {
    $("#"+div).html(point.name+'<br />'+G_RESPONSE[point.Status.code]);
  }
}
function getFeatureInfo(point, id){
    var bb = document.map.getBounds(); 
    var sw = bb.getSouthWest();
    var ne = bb.getNorthEast();
	var cp = document.map.getCurrentMapType().getProjection();
	bb = sw.x + ',' + sw.y + ','+ ne.x + ',' + ne.y;
	sw = cp.fromLatLngToPixel(sw , document.map.getZoom());
	ne = cp.fromLatLngToPixel(ne , document.map.getZoom());
	var px = cp.fromLatLngToPixel(point , document.map.getZoom());
	var wx = px.x - sw.x; 
	var wy = px.y - ne.y;
	var mz = document.map.getSize();
	var url = 'http://ovc.catastro.meh.es/Cartografia/WMS/ServidorWMS.aspx?REQUEST=GetFeatureInfo&VERSION=1.1.1&SRS=EPSG:4326&BBOX='+ bb +'&WIDTH='+ mz.width +'&HEIGHT='+ mz.height +'&QUERY_LAYERS=catastro&X='+wx+'&Y='+wy;
	$("#r").remove();
    xajax_getFeatureInfo(url, point.lat(), point.lng(), id);	

}
function getCatastro(overlay, point, name) { 
    name=undefined==name?point.lat()+', '+point.lng():name;         
    document.map.setCenter(point);
    var marker = new GMarker(point, {title:name});
    document.map.clearOverlays();
    document.map.addOverlay(marker);
    var html = '<div id="mInfo">'+name+'<br />Please wait...</div>';
    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(html);
    });
    marker.openInfoWindowHtml(html);
    var bb = document.map.getBounds(); 
    var sw = bb.getSouthWest();
    var ne = bb.getNorthEast();
	var cp = document.map.getCurrentMapType().getProjection();
	bb = sw.x + ',' + sw.y + ','+ ne.x + ',' + ne.y;
	sw = cp.fromLatLngToPixel(sw , document.map.getZoom());
	ne = cp.fromLatLngToPixel(ne , document.map.getZoom());
	var px = cp.fromLatLngToPixel(point , document.map.getZoom());
	var wx = px.x - sw.x; 
	var wy = px.y - ne.y;
	var mz = document.map.getSize();
	var url = 'http://ovc.catastro.meh.es/Cartografia/WMS/ServidorWMS.aspx?REQUEST=GetFeatureInfo&VERSION=1.1.1&SRS=EPSG:4326&BBOX='+ bb +'&WIDTH='+ mz.width +'&HEIGHT='+ mz.height +'&QUERY_LAYERS=catastro&X='+wx+'&Y='+wy;
	$("#r").remove();
	//$('<object id="r" data="'+url+'"></object>').bind('load', function(){console.error($(this).html());}).appendTo('body');
    xajax_getFeatures(url, point.lat(), point.lng(), name);	
}

