var provincias_by_name = [];
var provincias = [];
var localidades = [];
var oficinas = [];
var oficinas_visibles = [];
var marcas_visibles = [true,true,true,true,true];
var bounds;
var cachedbounds;
var oldzoom;
var dontupdate = false;

var currentsel = -1;
var currentobject = null;

	function filterPanelsByBrand(brand) {
		for (var i = 0; i< oficinas_visibles.length; i++) {
			var object = document.getElementById("celda"+i);
			if (brand == 0 ) {
				object.style.display = "block";
			} else 	if (oficinas_visibles[i].object.tipo == (brand)) {
				object.style.display = "block";
			} else {
				object.style.display = "none";
			}
		}
		
	}
	
	function selectOficina(oficina) {
		for (var i = 0; i< oficinas_visibles.length; i++) {
			if (oficina == oficinas_visibles[i].object) {
				showWindow(i);
				break;
			}
		}
	}
	function showSidebar() {
		var object = document.getElementById("directions");
		object.style.display = "none";
		object = document.getElementById("side_bar");
		object.style.display = "block";
		
	}
	function recorrido() {
		var aux = "from: "+encontrados[seleccionado].address+" to: "+currentobject.direccion+","+currentobject.cp+",Spain";
		//GLog.write(aux);
		var object = document.getElementById("side_bar");
		object.style.display = "none";
		object = document.getElementById("directions");
		object.style.display = "block";
		
		gdir.load(aux,{preserveViewport:true});
	}

	function hilightPanel(i) {
		if (currentsel !=-1) {
			 document.getElementById("panel"+currentsel).style.background = "";
		}
		var object = document.getElementById("panel"+i);
		object.style.background = "#EEEEEE";
	}
	function showWindow(i) {
		
		oficinas_visibles[i].object.marker.openInfoWindow(oficinas_visibles[i].object.getInfoWindow());
		hilightPanel(i);
		currentsel = i;
		currentobject = oficinas_visibles[i].object;
		dontupdate = true;
	}

	function InfoWindowClosed() {
		if (currentsel !=-1) {
			 document.getElementById("panel"+currentsel).style.background = "";
			 currentobject = null;
			 currentsel = -1;
		}
		//GLog.write("closed");
	}
	
	function dragEnd() {
	}	
		
	function showVisible(bounds,zoomlevel) {
	if (encontrados != null && seleccionado != -1) {
		
		map.addOverlay(encontrados[seleccionado].marker);
		
	}
	
	if (zoomlevel >=8) {
		
	/*	if (!((zoomlevel < 12 && oldzoom >=12) || (zoomlevel>=12 && oldzoom < 12))) {
		if (cachedbounds != null) {
			if (cachedbounds.containsBounds(bounds)) {
				return;
			}
		}
		}
		
		cachedbounds = new GLatLngBounds();
		var sw = bounds.getSouthWest();
		var ne = bounds.getNorthEast();
		var w = Math.abs(sw.lng()-ne.lng());
		var h = Math.abs(sw.lat()-ne.lat());
		var size = map.getSize();
		var dw = (w*100)/size.width;
		var dh = (h*100)/size.height;
		//GLog.write(bounds+w+":"+h);
		var lat;
		var lng;
		if (sw.lng() < 0) {
			lng = sw.lng() -dw;
		} else {
			lng = sw.lng() +dw;
		}
		lat = sw.lat() - dh
		var p = new GLatLng(lat,lng);
		cachedbounds.extend(p);
		
		if (ne.lng() < 0) {
			lng = ne.lng() +dw;
		} else {
			lng = ne.lng() -dw;
		}
		lat = ne.lat() + dh;
		p = new GLatLng(lat,lng);
		cachedbounds.extend(p);
		//GLog.write(cachedbounds+bounds);
		*/
		oldzoom = zoomlevel;
		
		oficinas_visibles = [];
		marcas_visibles = [false,false,false,false,false];
		for (var i =0; i<provincias.length; i++) {
			provincias[i].checkBounds(bounds,zoomlevel);
		}
		
		aux = "<table width='100%'><tbody>";
		//GLog.write( cbstatus);
		currentsel = -1;
		//GLog.write( encontrados[seleccionado].address);
		for (var i = 0; i<oficinas_visibles.length; i++) {
			
			var current = oficinas_visibles[i];
			//GLog.write( current.object.nombre);
			if (!bounds.contains(current.object.point)) {
				continue;
			}
			
			if (i == 0) {
				if (encontrados == null  ) {
					
					aux += "<tr><td colspan='2'><div class='hdr'>Oficinas Visibles</td></tr>";
				} else if (current.object instanceof oficina) {
					
					// aux += "<tr><td colspan='2'><div class='hdr'>Oficinas más cercanas a:<br/>"+encontrados[seleccionado].address+"</div></td></tr>";
					aux += "<tr><td colspan='2'><div class='marcas'>";
					
					var l_marcas = "<a href='javascript:filterPanelsByBrand(0);' class='marcas'>Todo el grupo - </a>";
					
					for (var z=0 ; z < marcas.length; z++) {
						if (marcas_visibles[z] == true) {
							l_marcas+= "<a href='javascript:filterPanelsByBrand("+(z+1)+");' class='marcas'>";
							l_marcas+= marcas[z];
							l_marcas+="</a>";
							l_marcas+= ' - ';
							
						}
						
					}
					if (l_marcas.length > 3) {
						l_marcas = l_marcas.substring(0,l_marcas.length-3);
					}
					aux +=l_marcas+"</div></td></tr><tr><td colspan='2'><div class='tdlista'>Se han encontrado <b>"+oficinas_visibles.length+"</b> oficinas</div></td></tr>";
					
				} else {
					aux += "<tr><td colspan='2'><div class='hdr'>Localidades más cercanas a:<br/>"+encontrados[seleccionado].address+"</div></td></tr>";
					aux += "<tr><td colspan='2'><div class='marcas'>";
					
					var l_marcas = "";
					for (var z=0 ; z < marcas.length; z++) {
						if (cbstatus[z] == true) {
							l_marcas+= marcas[z];
							l_marcas+= ' - ';
							
						}
						
					}
					if (l_marcas.length > 3) {
						l_marcas = l_marcas.substring(0,l_marcas.length-3);
					}
					aux +=l_marcas+"</div></td></tr>";
				}
			}
			
			
			
			var iconname = icons_markers[current.object.tipo-1] +(i+1)+".png";
			
			if (oficinas_visibles.length > 99) {
				iconname = icons_markers[current.object.tipo-1]+".png";
			}
			current.object.getMarker().setImage("icons/numbers/"+iconname);
			aux += "<tr id ='celda"+i+"'><td valign='top' class='tdlista' width='24px' ><img src='icons/numbers/o"+iconname+"' ></td><td id='panel"+i+"' valign='top' class='tdlista'><div class ='hdrlista'>";
			aux += "<a  href='javascript:showWindow("+i+");'>";
			if (current.object instanceof oficina) {
				
			aux += current.object.oficina+" - ";
			}
			aux += current.object.nombre;
			aux += "</a>";
			aux += "</div>";
			if (current.object instanceof oficina) {
				aux += current.object.direccion+"<br/>";
				aux += '<div class="marca">'+marcas[current.object.tipo-1]+"</div>";
			} else {
				//aux += "Una localidad con muchas oficinas";
			}
			
			
			//</tr></td>";
			//aux += "<tr><td >";
			//GLog.write(current.object.nombre);
			var dist = current.distancia;
			if (dist > 1000) {
				dist = Math.round(dist /100)/10;
				aux += "A "+dist + " km.";
			} else {
				dist = Math.round(dist);
				aux += "A "+dist + " m.";
			}
			aux += "</td></tr>";
			if (current.object == currentobject) {
				currentsel = i;
			}
		}
		aux += "</tbody></table>";
		document.getElementById("side_bar").innerHTML = aux;
		if (currentsel != -1) {
			hilightPanel(currentsel);
		}
	
	}
      }


	function insert(array,i,v)
	{
		if(i>=0 ){
			var a=array.slice();
			
			b=a.splice(i,a.length);
			
			a[i]=v;
			
			return a.concat(b);
		}
		
	}
      
      function distancia(p,num) {
      	this.object = p;
	this.distancia = num;
	this.toString = function() {
		return this.object.nombre +":"+this.distancia;
	}
      }
      function sortArray(object) {
	      	var d = encontrados[seleccionado].marker.getPoint().distanceFrom(object.point);
		var dist = new distancia(object,d);
		
		var j=0;
		for (j = 0; j<oficinas_visibles.length; j++) {
			if (d <oficinas_visibles[j].distancia) {
				break;
			}
		}
		if (oficinas_visibles.length ==0) {
			oficinas_visibles[0] = dist;
		} else 	if (j == oficinas_visibles.length) {
			oficinas_visibles[oficinas_visibles.length] = dist;
		} else {
			//GLog.write("Insert at "+ j+" "+object.nombre);
			oficinas_visibles = insert(oficinas_visibles,j,dist);
		}
		
	
      }

      
 function buscarMasCercana(placemark) {
	  var p = placemark.Point.coordinates;
	  var punto = new GLatLng(p[1],p[0]);
      	var pcercanas = [];
	//GLog.write("Buscando");
      	for (var i =0; i<provincias.length; i++) {
		var checkthis = false;
		for (var j = 0; j<5; j++) {
			if (cbstatus[j] && provincias[i].counts[j] != 0) {
				checkthis = true;
			}
		}
		if (checkthis) {
		var d = punto.distanceFrom(provincias[i].point);
		var dist = new distancia(provincias[i],d);
		//////$GLog.write(provincias[i].nombre+":"+d);
		var j=0;
		for (j = 0; j<pcercanas.length; j++) {
			if (d < pcercanas[j].distancia) {
				break;
			}
		}
		//////$GLog.write(j+":"+pcercanas.length);
		if (pcercanas.length ==0) {
			pcercanas[0] = dist;
		} else 	if (j == pcercanas.length) {
			pcercanas[pcercanas.length] = dist;
		} else {
		
		//	////$GLog.write(provincias[i].nombre+":"+j);
			pcercanas = insert(pcercanas,j,dist);
		}
		}
	
	}
	
	var lcercanas = pcercanas[0].object.masCercana(punto);
	for (var j = 0; j<  5 ; j++) {
		////$GLog.write(lcercanas[j].object.nombre+":"+lcercanas[j].distancia);
	}
	var ocercanas = lcercanas[0].object.masCercana(punto);
	for (var j = 0; j< ocercanas.length; j++) {
		////$GLog.write(ocercanas[j].object.nombre+":"+ocercanas[j].distancia);
	}
	if (placemark.AddressDetails.Accuracy == 4 && placemark.address.toLowerCase().indexOf(lcercanas[0].object.nombre.toLowerCase())!=-1 ) {
		lcercanas[0].object.display();	
	} else {
	//GLog.write(ocercanas[0].object.nombre+":"+lcercanas[0].distancia);
	var x1 = punto.lat() - ocercanas[0].object.point.lat();
	var y1 = punto.lng() - ocercanas[0].object.point.lng();
	var point2 = new GLatLng(punto.lat()+x1,punto.lng()+y1);
	var newbounds = new  GLatLngBounds();
	newbounds.extend(ocercanas[0].object.point);
	newbounds.extend(point2);
	map.setCenter(newbounds.getCenter(),map.getBoundsZoomLevel(newbounds));
      	}
      }

function provincia(p) {
      	
      	this.localidades = [];
	this.nombre = p.getAttribute("nombre");
	var lat = parseFloat(p.getAttribute("lat"));
        var lng = parseFloat(p.getAttribute("long"));
        this.point = new GLatLng(lat,lng);
	this.bounds = null;
	this.count = 0;
	this.counts = [0,0,0,0,0];
	this.side_bar_html=null;
	provincias_by_name[this.nombre] = this;
	
	
	
		
	this.getBounds = function() {
		if (this.bounds == null) {
			this.bounds = new GLatLngBounds();
			this.bounds.extend(this.point);
			////$GLog.write("Bounds:");
			for (var key in this.localidades) {
					this.bounds.extend(this.localidades[key].getPoint());
			}
		
		}
		return this.bounds;
	}
	this.getText = function() {
		if (this.side_bar_html == null) {
			var text = '<a href="javascript:displayAll()">'+"TODO</a><br/>";
			text += '<a href="javascript:displayProvincia('+this.nombre+')">'+this.nombre+"</a>";
		
			//var text = '<table width="100%"><tbody><tr><td><a href="javascript:displayAll()">'+"TODO</a></td></tr>";
			//text += '<tr><td><a href="javascript:displayProvincia('+this.nombre+')">'+this.nombre+"</a></td></tr>";
			//var text = '<table width="100%"><tbody><tr><td><a href="javascript:displayAll()">'+"TODO</a></td></tr>";
			//text += '<tr><td><a href="javascript:displayProvincia('+this.nombre+')">'+this.nombre+"</a></td></tr></tbody></table>";
			var line = 0;
			for (var i = 0; i< 5; i++) {
				var header = false;
				text += '<table id="'+table_id[i]+'" border="0" width="100%" ><tbody>';
				for (var key in this.localidades) {
					//GLog.write(i+":"+key+":"+this.localidades[key].cuentas[i]);
					if (this.localidades[key].cuentas[i] != 0){
					if (header == false) {
						text+= headers[i];
						header = true;
						
					}
			//	
			
				 
				//////$GLog.write("<a href='javascript:display('"); //'this.nombre'","'+key+')">');
				var aux = "'"+this.nombre+"','"+key+"'";
				//////$GLog.write('<a href="javascript:display(' + aux + ')">');
				text += '<tr><td class="'+tdstyle[line%2]+'"><a href="javascript:displayLocalidad(' + aux + ')">'+this.localidades[key].nombre+"<br/>"+this.localidades[key].cuentas[i]+"oficinas </a></td></tr>";
				line++;
				}
			}
			text += '</tbody></table>';
			}
			//text += '</tbody></table>'
			this.side_bar_html = text;
		}
		return this.side_bar_html;
	}
		
	this.addLocalidad = function(localidad) {
		
			//////$GLog.write("add:"+localidad.nombre);
		
		
		this.localidades[localidad.nombre] = localidad;
		localidad.setProvincia(this);
		//this.bounds.extend(localidad.getPoint());
		this.count++;
	}
	
	this.getCount = function() {
		return this.count;
	}
	
	this.getPoint = function() {
		return this.point;
	}
	
	this.getMarker = function() {
		if (this.marker == null) {
			this.marker = createMarker(this.point,this.nombre,this.nombre,this.nombre+":"+this.count,0);
			var prov = this;
			GEvent.addListener(this.marker, "click", function() {
				////$GLog.write("Prov  click");
				////$GLog.write(prov.nombre);
				prov.display();
			});
		}
		return this.marker;
	}
	
	this.display = function() {
		
		zoomlevel = map.getBoundsZoomLevel(this.getBounds());
		if (zoomlevel < 7)
			zoomlevel = 7;
		if (zoomlevel > 12)
			zoomlevel = 12;
		if (this.count <2 ) {
			map.setCenter(this.point,8);
			//map.setZoom(map.getBoundsZoomLevel(12));
		} else {
			
			map.setCenter(this.getBounds().getCenter(),zoomlevel);
			//map.setZoom(map.getBoundsZoomLevel(this.bounds));
		}
		document.getElementById("side_bar").innerHTML = this.getText();
		checkBrands();
		
		
	}
	this.masCercana = function(punto) {
		lcercanas = [];
		
		for (var key in this.localidades) {
			var loc = this.localidades[key];
			var check = false;
			for (var i = 0; i<5; i++) {
				if (loc.cuentas[i] != 0 && cbstatus[i]) {
					check = true;
				}
			}
			if (check) {
			var d = punto.distanceFrom(loc.point);
			var dist = new distancia(loc,d);
			//////$GLog.write(provincias[i].nombre+":"+d);
			var j=0;
			for (j = 0; j<lcercanas.length; j++) {
				if (d < lcercanas[j].distancia) {
					break;
				}
			}
		//////$GLog.write(j+":"+pcercanas.length);
			if (lcercanas.length ==0) {
				lcercanas[0] = dist;
			} else 	if (j == lcercanas.length) {
				lcercanas[lcercanas.length] = dist;
			} else {
		
		//	////$GLog.write(provincias[i].nombre+":"+j);
				lcercanas = insert(lcercanas,j,dist);
			}
			}
		}
		
		return (lcercanas);
	}
	
	this.checkBounds = function(bounds,zoomlevel) {
		if (this.getBounds().intersects(bounds)) {
		
			if (zoomlevel < 8) {
				for (var i = 0; i< 5; i++) {
					if (cbstatus[i] && this.counts[i] != 0) {
						map.addOverlay(this.getMarker());
						break;
					}
				}
				
			} else {
				for (var key in this.localidades) {

					var loc = this.localidades[key];
					for (var i = 0; i< 5; i++) {
						if (cbstatus[i] && loc.cuentas[i] != 0) {
							loc.checkBounds(bounds,zoomlevel);
							break;
						}
					}
					
				}
		
			}
			if (this.bounds.containsBounds(bounds)) {
				return true;
			}
		}
		return false;
	}
	
      }
      
      function localidad2(nombre) {
      	
      	this.localidades = [];
	this.nombre = nombre;
	this.provincia = null;
	this.tipo = 1;
	this.tipos = [];
	this.tipos[0] = [];
	this.tipos[1] = [];
	this.tipos[2] = [];
	this.tipos[3] = [];
	this.tipos[4] = [];
	this.cuentas = [0,0,0,0,0];
	
	//this.prov = parseInt(p.getAttribute("provincia"));
	var lat = 0; //parseFloat(p.getAttribute("lat"));
        var lng = 0; //parseFloat(p.getAttribute("lng"));
	//this.numofi = 0; //parseInt(p.getAttribute("oficinas"));
        this.point = null; //new GLatLng(lat,lng);
	this.marker = null;
	//////$GLog.write(this.nombre);
	this.bounds = new GLatLngBounds();
	this.count = 0;
	this.side_bar_html=null;
	this.html = null;
	
	/*/this.marker = createMarker(this.point,this.nombre,this.nombre,this.nombre+":"+this.numofi);
	
	var loc = this;
	GEvent.addListener(this.marker, "click", function() {
		////$GLog.write("loc  click");
		////$GLog.write(loc.nombre);
		loc.display();
	});
	*/
		


	this.getInfoWindow = function() {
		if (this.html == null) {
		this.html = "<table><tbody><tr><td class='hdr'>"+this.nombre+
	"</td></tr>";
	for (var i = 0; i<5; i++) {
		if (this.cuentas[i] != 0) {
			this.html += "<tr><td>"+marcas[i]+":"+this.cuentas[i]+" oficinas.</td></tr>";
		}
	}
	
	this.html += "</tbody></table>";
		}
		return this.html;
	}
	
	this.getText = function() {
		if (this.side_bar_html == null) {
			var text = '<a href="javascript:displayAll()">'+"TODO</a><br/>";
			text +='<a href="javascript:displayProvincia(' +"'"+ this.provincia.nombre+"'" + ')">'+this.provincia.nombre+"</a><br/>";
			text += '<a href="javascript:displayLocalidad(' +"'"+ this.provincia.nombre+"','"+this.nombre+"'" + ')">'+this.nombre+"</a><br/>";
			var line = 0;
			for (var i = 0; i < 5; i++) {
				var header = false;
				text += '<table id="'+table_id[i]+'" border="0" width="100%"><tbody>';
				for (var key in this.tipos[i]) {
					if (header == false) {
						text+= headers[i];
						header = true;
						
					}
			//	text += this.localidades[key].nombre+"<br>"+this.localidades[key].point+"<br>";
					var aux = "'"+this.provincia.nombre+"','"+this.nombre+"','"+key+"'";
			//	////$GLog.write('<a href="javascript:display(' + aux + ')">');
					text += '<tr><td class="'+tdstyle[line%2]+'"><a href="javascript:displayOficina(' + aux + ')">'+this.tipos[i][key].nombre+"<br/>"+this.tipos[i][key].oficina+"<br/></a></td></tr>";
					line++;
				
				
				}
				
			}
			text += '</tbody></table>';
			this.side_bar_html = text;
		}
		return this.side_bar_html;
	}
	
	this.getBounds = function() {
		return this.bounds;
	}
	
	this.setProvincia = function(provincia) {
		this.provincia = provincia;
	}
	
	this.addLocalidad = function(localidad) {
		
		this.count ++;
		this.localidades[localidad.oficina] = localidad;
		this.tipos[localidad.tipo-1][localidad.oficina] = localidad;
		this.cuentas[localidad.tipo-1]++;
		//GLog.write(this.cuentas[localidad.tipo-1]+":"+localidad.nombre+":"+localidad.tipo);
		this.bounds.extend(localidad.getPoint());
		this.point = this.bounds.getCenter();
		this.provincia.counts[localidad.tipo-1]++;
	}
	
	this.getPoint = function() {
		return this.point;
	}
	
	this.getMarker = function() {
		////$GLog.write(this.nombre+" "+this.count);
		if (this.marker == null) {
			this.marker = createMarker(this.point,this.nombre,this.nombre,this.nombre+":"+this.count,1);
			var loc = this;
			GEvent.addListener(this.marker, "click", function() {
			////$GLog.write("loc  click");
			////$GLog.write(loc.nombre);
			loc.display();
			});
		}
		return this.marker;
	}
	this.display = function() {
		////$GLog.write(this.count);
		////$GLog.write(this.bounds);
		if (this.count < 2) {
			map.setCenter(this.point,15);
			//map.setZoom(15);
		} else {
			map.setCenter(this.getBounds().getCenter(),map.getBoundsZoomLevel(this.getBounds()));
			//map.setZoom(map.getBoundsZoomLevel(this.bounds));
		}
		//document.getElementById("side_bar").innerHTML = this.getText();
		//checkBrands();
	}
	this.masCercana = function(punto) {
		lcercanas = [];
		
		for (var key in this.localidades) {
			var loc = this.localidades[key];
			var check = false;
			for (var i = 0; i<5; i++) {
				if ( cbstatus[loc.tipo-1]) {
					check = true;
				}
			}
			if (check) {
			var d = punto.distanceFrom(loc.point);
			var dist = new distancia(loc,d);
		
			var j=0;
			for (j = 0; j<lcercanas.length; j++) {
				if (d < lcercanas[j].distancia) {
					break;
				}
			}
		
			if (lcercanas.length ==0) {
				lcercanas[0] = dist;
			} else 	if (j == lcercanas.length) {
				lcercanas[lcercanas.length] = dist;
			} else {
		
		
				lcercanas = insert(lcercanas,j,dist);
			}
			}
		}
		
		return (lcercanas);
	}
	this.checkBounds = function(bounds,zoomlevel) {
		//GLog.write(bounds+this.getBounds());
		if (this.getBounds().intersects(bounds)) {
			
			if (zoomlevel < 8) {
				//GLog.write("Add Overlay");
				map.addOverlay(this.getMarker());
				//GLog.write("Add Overlay OUT");
				if (encontrados != null && seleccionado !=-1) {
					sortArray(this);
						
				}
			} else {
				for (var key in this.localidades) {
					var loc = this.localidades[key];
					loc.checkBounds(bounds,zoomlevel);
				}
		
			}
			if (this.bounds.containsBounds(bounds)) {
				return true;
			}
		}
		return false;
	}
      }
      
      
      
      function oficina(p) {
      	
      	
	this.nombre = p.getAttribute("nombre");
	
	var lat = parseFloat(p.getAttribute("lat"));
        var lng = parseFloat(p.getAttribute("lng"));
	
	this.oficina = p.getAttribute("numero");
        this.point = new GLatLng(lat,lng);
	this.bounds = new GLatLngBounds();
	this.tipo = parseInt( p.getAttribute("tipo"));
	this.direccion = p.getAttribute("direccion");
	this.telefono = p.getAttribute("telefono");
	this.fax = p.getAttribute("fax");
	this.director = p.getAttribute("director");
	this.cp = p.getAttribute("cp");
	
	//this.html = "<table><tbody><tr><td class='hdr' >Oficina:"+this.oficina+"</td></tr><tr><td>"+this.nombre+
	this.html = "<table><tbody><tr><td><table class='trcabeceraiw' width='100%'><tbody><tr ><td>"+ 
	"<div class='tdlista'>Oficina: "+this.oficina+"<br>"+this.nombre+"</div>"+
	"</td><td align='right' >"+"<img src='"+logos[this.tipo-1]+"' alt=''>"+
	"</td></tr></tbody></table></tr><tr><td class='tdlista'>"+
	"<table><tbody><tr><td valign='top' class='tdlista'>"+
	this.direccion+","+p.getAttribute("cp")+"&nbsp;"+p.getAttribute("poblacion")+
	"<br>"+
	"tel: "+this.telefono+"<br>fax: "+this.fax+
	"</td><td>"+
	// "<img src='base_image.jpg' alt=''>"+
	"</td></tr></tbody></table>"+
	"</td></tr>"+
	"</td></tr><tr><td class='tdlista'>"+
	"<a href='javascript:recorrido();'>Cómo llegar</a>"+
	"</td></tr></tbody></table>";
	//alert(this.html);
	
		
	this.getBounds = function() {
		return this.bounds;
	}
		
	
	
	this.getPoint = function() {
		return this.point;
	}
	
	this.getInfoWindow = function() {
		return this.html;
	}
	
	this.getMarker = function() {
		if (this.marker == null) {
			this.marker = createMarker(this.point,this.nombre,this.html,"Oficina "+this.oficina+":"+this.nombre,this.tipo);
			var ofi = this;
			GEvent.addListener(this.marker, "click", function() {
				selectOficina(ofi);	
				
			});
		}
		return this.marker;
	}
	this.display = function() {
		map.setCenter(this.point);
		map.setZoom(15);
	}
	this.checkBounds = function(bounds,zoomlevel) {
		if (bounds.contains(this.point)) {
			//GLog.write(this.nombre);
			if (cbstatus[this.tipo-1] ) {
				if (this != currentobject) {
					map.addOverlay(this.getMarker());
				}	
			
				if (encontrados != null && seleccionado != -1) {
					sortArray(this);
		
				} else {
					var dist = new distancia(this,0);
					oficinas_visibles[oficinas_visibles.length] = dist;
					
				}
				marcas_visibles[this.tipo-1] = true;
			}
			
		}
	}
	
      }
      function createMarker(point,name,html,tooltip,i) {
      	
        var marker = new GMarker(point,{ title: tooltip,icon : icons[i]});
	//var marker = new GMarker(point,{ title: tooltip});
	
        return marker;
      }
      
      function loadData() {
	      //GLog.write("loadData");
	      var request = GXmlHttp.create();
      
	      request.open("GET", "provincias.xml", true);
	      om.Set('<b>Cargando...</b>');
	      request.onreadystatechange = function() {
	      	      if (request.readyState == 4) {
			      var xmlDoc = request.responseXML;
			      //GLog.write("provincias");
			      var markers = xmlDoc.documentElement.getElementsByTagName("provincia");
			      bounds = new GLatLngBounds();
			      //GLog.write("loaded");
          
			      for (var i = 0; i < markers.length; i++) {
				      p = new provincia(markers[i]);
				      codigo = markers[i].getAttribute("codigo");
				      c = parseInt(codigo,10)-1;
				      provincias[c] = p;
				      if (c != 34 && c!=37) {
					      bounds.extend(p.getPoint());
					      //GLog.write(p.nombre+bounds);
				      }
	    
           		      }
	 
        
	var work = [];
	om.Set('<b>Cargando...</b>');
	markers = xmlDoc.documentElement.getElementsByTagName("oficina");
	
	var l = 0;
	for (var i = 0; i < markers.length; i++) {
	   	var poblacion = markers[i].getAttribute("poblacion");
		var cp = markers[i].getAttribute("cp");
		var localidad = work[poblacion+cp.substring(0,2)];
		
		if (localidad == null) {
			localidad = new localidad2(poblacion);
			work[poblacion+cp.substring(0,2)] = localidad;
			
			var j = parseInt(cp.substring(0,2),10)-1;
			//////$GLog.write(j);
			provincias[j].addLocalidad(localidad);
			localidades[l++] = localidad;
						
		}
		//////$GLog.write(poblacion);
		ofi = new oficina(markers[i]);
		oficinas[i] = ofi;
		// omarkers[i] = ofi.getMarker();
		localidad.addLocalidad(ofi);
		
	}
	//$GLog.write("Provincias");
	var k = 0;
	side_bar_html ='<table width="100%"><tbody>';
	for (var i = 0; i<provincias.length ; i++) {
		if(provincias[i] != null) {
		//////$GLog.write(provincias[i].nombre);
			if (provincias[i].getCount() != 0) {
		//		pmarkers[k++] = provincias[i].getMarker();
				
			}
		var aux ="";	
		if (provincias[i].counts[0] != 0) {	
		   aux += "<span class ='sabadell'>BS:"+provincias[i].counts[0]+" </span>";
		}
		if (provincias[i].counts[1] != 0) {	
		   aux += "<span class ='solbank'>SB:"+provincias[i].counts[1]+" </span>";
		}
		if (provincias[i].counts[2] != 0) {	
		   aux += "<span class ='bancourquijo'>BU:"+provincias[i].counts[2]+" ";
		}
		if (provincias[i].counts[3] != 0) {	
		   aux += "<span class ='bancoherrero'>BH:"+provincias[i].counts[3]+" ";
		}
		if (provincias[i].counts[4] != 0) {	
		   aux += "<span class ='activobank'>AB:"+provincias[i].counts[4]+" ";
		}
		side_bar_html += '<tr><td class="'+tdstyle[i%2]+'"><a href="javascript:displayProvincia('+"'"+provincias[i].nombre+"'"+')">'+provincias[i].nombre+"<br/>"+aux+"</a><br/></td></tr>";
		//////$GLog.write( '<a href="javascript:displayProvincia('+'"'+provincias[i].nombre+'"'+'")>'+provincias[i].nombre+":"+provincias[i].getCount()+" oficinas."+"</a><br/>");
		}
		
		
	}
	
	
	createMap();
	GEvent.addListener(map, "moveend", MapMoved);
	GEvent.addListener(map.getInfoWindow(),"closeclick",InfoWindowClosed);
	GEvent.addListener(map.getInfoWindow(),"dragend",dragEnd);
	var query = new PageQuery(location.search);
	
	if (query.getLength() != 0) {
	
		var lat = parseFloat(unescape(query.getValue("lat")));
		var lng = parseFloat(unescape(query.getValue("lng")));
		var zoom = parseInt(unescape(query.getValue("zoom")));
		var x0 = query.getValue("x0");
		var y0 = query.getValue("y0");
		var address = query.getValue("address");
		
		if (x0 != false && y0 != false && address != false ){
			var point = new GLatLng(parseFloat(y0),parseFloat(x0));
			var pl = new MPlacemark();
			pl.Point = point;
			pl.address = unescape(address);
			encontrados = [];
			encontrados[0] = pl;
			seleccionado = 0;
			pl.marker = new GMarker(point,{ title:address ,icon : flechaIcon});
		}
		
		map.setCenter(new GLatLng(lat,lng),zoom);
		
	} else {
		map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds));
	}

	//GLog.write(bounds.getCenter()+bounds);
	   
	   init2();
	//GLog.write(map.getCenter());   
	  
        }
      }
      request.send(null);
    }
    function MPlacemark() {
	    return this;
    }
    
    function createMap() {
	 map = new GMap2(document.getElementById("map"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	var ovcontrol = new GOverviewMapControl(new GSize(100,100)); 
	map.addControl(ovcontrol);
	gdir=new GDirections(map, document.getElementById("directions"));
	
	GEvent.addListener(gdir, "error", function() {
        var code = gdir.getStatus().code;
        var reason="Code "+code;
        if (reasons[code]) {
          reason = reasons[code]
        } 

        alert("Failed to obtain directions, "+reason);
       });
       
    }
