var map;
var geo= new GClientGeocoder();

var gdir;
var encontrados = null;
var seleccionado = -1;
var tdstyle = ["tdOdd","tdEven"];


var reasons=[];
      reasons[G_GEO_SUCCESS]            = "Success";
      reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
      reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
      reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
      reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
      reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
      reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
      reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
      reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
      reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";
      
 var baseIcon = new GIcon();
          baseIcon.iconSize=new GSize(32,29);
          //baseIcon.shadowSize=new GSize(56,32);
	  baseIcon.transparent = '';
          baseIcon.iconAnchor=new GPoint(16,29);
          baseIcon.infoWindowAnchor=new GPoint(16,0);
	  
var flechaIcon = new GIcon(G_DEFAULT_ICON,"arrow.png");	  
 	flechaIcon.iconSize=new GSize(39,34);
	
	

   /*       
      var bsicon = new GIcon(baseIcon, "markerbs.png"); //, null, "http://maps.google.com/mapfiles/kml/pal5/icon14s.png");
      var bhicon = new GIcon(baseIcon, "markerbh.png"); //, null, "http://maps.google.com/mapfiles/kml/pal5/icon14s.png");
      var sbicon = new GIcon(baseIcon, "markersb.png"); //, null, "http://maps.google.com/mapfiles/kml/pal5/icon14s.png");
      var abicon = new GIcon(baseIcon, "markerab.png"); //, null, "http://maps.google.com/mapfiles/kml/pal5/icon14s.png");
      var buicon = new GIcon(baseIcon, "markerbu.png"); //, null, "http://maps.google.com/mapfiles/kml/pal5/icon14s.png");
      */
      
      var bsicon = new GIcon(G_DEFAULT_ICON, "icons/bs.png"); //, null, "http://maps.google.com/mapfiles/kml/pal5/icon14s.png");
      bsicon.iconSize = new GSize(20,36);
      var bhicon = new GIcon(bsicon, "icons/bs.png"); //, null, "http://maps.google.com/mapfiles/kml/pal5/icon14s.png");
      var sbicon = new GIcon(bsicon, "icons/bs.png"); //, null, "http://maps.google.com/mapfiles/kml/pal5/icon14s.png");
      var abicon = new GIcon(bsicon, "icons/bs.png"); //, null, "http://maps.google.com/mapfiles/kml/pal5/icon14s.png");
      var buicon = new GIcon(bsicon, "icons/bs.png"); //, null, "http://maps.google.com/mapfiles/kml/pal5/icon14s.png");
      
      var lupaicon = new GIcon(baseIcon, "lupa.png"); //, null, "http://maps.google.com/mapfiles/kml/pal5/icon14s.png");
      var icons = [lupaicon,bsicon,sbicon,buicon,bhicon,abicon];
      var logos = ["SabadellAtlantico40.png","SolBank40.png","BancoUrquijo40.png","BancoHerrero40.png","ActivoBank40.png"];
      var icons_markers = ["bs","sb","bu","bh","ab"];
      
      var BS = 0;
      var SB = 1;
      var BU = 2;
      var BH = 3;
      var AB = 4;
      
      
      var marcas = ["SabadellAtlantico","Solbank","BancoUrquijo","BancoHerrero","Activobank"];
var cbstatus = [true,true,true,true,true]; //[false,false,false,false,false]; //

function showBrands() {
	
	var aux = document.getElementById("brands").options[document.getElementById("brands").selectedIndex].value;
	GLog.write(aux);
	if (aux == "all") {
		cbstatus[BS] = cbstatus[BH] = cbstatus[SB] = cbstatus[AB] = cbstatus[BU] = true; 
	} 
	if (aux == "bs") {
		cbstatus[BS] = true; 
		cbstatus[BH] = cbstatus[SB] = cbstatus[AB] = cbstatus[BU] = false;
	}
	if (aux == "bh") {
		cbstatus[BH] = true; 
		cbstatus[BS] = cbstatus[SB] = cbstatus[AB] = cbstatus[BU] = false;
	}
	if (aux == "sb") {
		cbstatus[SB] = true; 
		cbstatus[BH] = cbstatus[BS] = cbstatus[AB] = cbstatus[BU] = false;
	}
	if (aux == "ab") {
		cbstatus[AB] = true; 
		cbstatus[BH] = cbstatus[SB] = cbstatus[BS] = cbstatus[BU] = false;
	}
	if (aux == "bu") {
		cbstatus[BU] = true; 
		cbstatus[BH] = cbstatus[SB] = cbstatus[BS] = cbstatus[AB] = false;
	}
	
}

 function show() {
	var zoomlevel = map.getZoom();
	if (cachedbounds == null || !cachedbounds.containsBounds(map.getBounds()) || !((zoomlevel < 12 && oldzoom >=12) || (zoomlevel>=12 && oldzoom < 12))) {
		//GLog.write("Calc bounds");
		//map.clearOverlays();
		for (var i = 0; i<oficinas_visibles.length; i++) {
			
			if (oficinas_visibles[i].object != currentobject) {
				map.removeOverlay(oficinas_visibles[i].object.getMarker());
				
			}
		}
		showVisible(map.getBounds(), zoomlevel);
	}
	om.Clear();
      }
      
      function MapMoved(source) {
      	//$GLog.write("Map Moved");
	
	om.Set('<b>Buscando visibles...</b>');
	window.setTimeout("show();",1);
	
      }

 function buscar(index) {
	      if (encontrados != null && index < encontrados.length) {
		      seleccionado = index;
		      currentsel = -1;
		     
		      //map.setCenter(pos,14);
		      buscarMasCercana(encontrados[index]);
	      }
      }

function showAddress( direccion) {
        var search;
	if (direccion == null) {
		search = document.getElementById("search").value;
		search += ",ES";
		
	} else
		search = direccion;
		
		if (encontrados != null && seleccionado !=-1) {
			map.clearOverlays();
		}
        // ====== Perform the Geocoding ======        
        geo.getLocations(search, function (result)
          { 
            // If that was successful
            if (result.Status.code == G_GEO_SUCCESS) {
              // How many resuts were found
	      
	      var aux = '<table style="width:100%"><tbody>';
              document.getElementById("side_bar").innerHTML = "Found " +result.Placemark.length +" results";
              // Loop through the results, placing markers
	      aux += '<tr><td class="hdr">'+'Resultados ' +'</td></tr>';
	      encontrados = result.Placemark;
              for (var i=0; i<result.Placemark.length; i++) {
                var p = result.Placemark[i].Point.coordinates;
                var marker = new GMarker(new GLatLng(p[1],p[0]),{ title:result.Placemark[i].address ,icon : flechaIcon});
		encontrados[i].marker = marker;
		aux += '<tr><td class="subhdr"><a href="javascript:buscar('+i+')">'+ result.Placemark[i].address +'</a></td></tr>';
                //document.getElementById("side_bar").innerHTML += "<br>"+(i+1)+": "+ result.Placemark[i].address + marker.getPoint();
                //map.addOverlay(marker);
		//currentplace = marker;
		//GLog.write(result.Placemark[i].address);
		//GLog.write(result.Placemark[i].AddressDetails.Accuracy);
              }
	      aux+= '</tbody></table>';
	      document.getElementById("side_bar").innerHTML = aux;
              // centre the map on the first result
	      if ( encontrados.length == 1) {
		      buscar(0);
	      }
            }
            // ====== Decode the error status ======
            else {
              var reason="Code "+result.Status.code;
              if (reasons[result.Status.code]) {
                reason = reasons[result.Status.code]
              } 
              alert('Could not find "'+search+ '" ' + reason);
            }
          }
        );
      }

function init() {
	
 if (GBrowserIsCompatible()) { 	
	 
	 om = new OverlayMessage(document.getElementById('map'));      
	 om.Set('<b>Cargando...</b>');
	 //var myArray=[1,2,3,4,5,6,7,8,9,10];
	 //var newArray=[];//delete one item at the 5th index.newArray = myArray.splice(5,1);document.writeln(myArray);  // outputs: 1,2,3,4,5,7,8,9,10document.writeln(newArray); // outputs 6//truncate the array at the 5th index.myArray=[1,2,3,4,5,6,7,8,9,10];newArray = myArray.splice(5);document.writeln(myArray);  // outputs: 1,2,3,4,5document.writeln(newArray); // outputs 6,7,8,9,10// do nothing at all.myArray=[1,2,3,4,5,6,7,8,9,10];newArray = myArray.splice();document.writeln(myArray);  // outputs: 1,2,3,4,5,6,7,8,9,10document.writeln(newArray); // outputs undefined// cut out the middle and insert 'blue', and 'green'myArray=[1,2,3,4,5,6,7,8,9,10];newArray = myArray.splice(1,8, 'blue', 'green');document.writeln(myArray);  // outputs: 1,blue,green,10document.writeln(newArray); // outputs 2,3,4,5,6,7,8,9// Insert without deleting.
	 /*myArray=[1,2,3,4,5,6,7,8,9,10];
	 GLog.write(myArray);
	 newArray = myArray.slice(6);
	 GLog.write(newArray);
	 GLog.write(myArray);
	 newArray = myArray.splice(1,myArray.length);
	 GLog.write(newArray); // outputs: 1,2,3,4,*,5,*,6,7,8,9,10
	 GLog.write(myArray);*/
	 
	 
	 window.setTimeout("loadData();",1);
	 //geo.setBaseCountryCode("ES");
	 
	 
	  
     //map = new GMap2(document.getElementById("map"));
     //map.setCenter(new GLatLng(40.4083333333333,-3.6875), 5);

    }
    
    // display a warning if the browser was not compatible
    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }
}
function init2() {
	var mapa = document.getElementById("map");
	var object2 = document.getElementById("side_bar");
	var direction = document.getElementById("directions");
	var maxheight = window.innerHeight * 0.8 *0.98;
	mapa.parentNode.style.maxHeight = Math.round(maxheight)+"px";
	object2.style.maxHeight = Math.round(maxheight)+"px";
	direction.style.offsetTop = object2.style.offsetTop+"px"; 
	direction.style.offsetLeft = object2.style.offsetLeft+"px";
	direction.style.offsetHeight = object2.style.offsetHeight+"px";
	direction.style.offsetWidth = object2.style.offsetWidth+"px";
	direction.style.maxHeight = Math.round(maxheight)+"px";
}

function getQueryString() {
	var aux = "";
	aux += "?lat="+map.getCenter().lat();
	aux += "&lng="+map.getCenter().lng();
	aux += "&zoom="+ map.getZoom();
	if (encontrados != null && seleccionado != -1) {
		 var p = encontrados[seleccionado].Point.coordinates;
		 aux += "&x0="+ p[0];
		 aux += "&y0="+ p[1];
		 aux += "&address="+encontrados[seleccionado].address;
		 
	}
	location = location.pathname + aux;
	
	return location;
}	

function PageQuery(q) {
if(q.length > 1) this.q = q.substring(1, q.length);
else this.q = null;
this.keyValuePairs = new Array();
if(q) {
for(var i=0; i < this.q.split("&").length; i++) {
this.keyValuePairs[i] = this.q.split("&")[i];
}
}
this.getKeyValuePairs = function() { return this.keyValuePairs; }
this.getValue = function(s) {
for(var j=0; j < this.keyValuePairs.length; j++) {
if(this.keyValuePairs[j].split("=")[0] == s)
return this.keyValuePairs[j].split("=")[1];
}
return false;
}
this.getParameters = function() {
var a = new Array(this.getLength());
for(var j=0; j < this.keyValuePairs.length; j++) {
a[j] = this.keyValuePairs[j].split("=")[0];
}
return a;
}
this.getLength = function() { return this.keyValuePairs.length; }
}
