
//Objeto Mapa
var oMap;
//Objeto Geo - Para localizaciones de direcciones
var oGeo;

//Arreglo con los puntos encontrados de una consulta
var aPoints;

//Para debug
//var oConsole = console;

//ICONOS
/*Iconos que varian su tamaño (Zoom nivel pais)*/
var iconA;
var iconB;
var iconC;
var iconD;
var iconE;

/*Iconos que diferencias los diferentes tipos*/
/*var iconAZUL;*/
var iconNARANJA;
var iconVERDE;

/*Iconos para los resultados de la busqueda*/
var iconStart;
var iconEnd;

var iControl;

//Objeto de poligono
var oPoly;
//Objeto de dirección
var oGdir;

//Objeto que contiene la busqueda del como llegar
var oAddress;

var iCurrentZoom;



/**DEBUG**/
var oConsole = new Object();
if(jQuery.browser.msie==false)
{
  if(window.console && window.console.firebug) oConsole.log = window.console.log;
}
else {
  oConsole.log = window.alert
    }
/**END_DEBUG**/

function JS_loadIcons()
{
  /*Iconos que varian su tamaño (Zoom nivel pais)*/
  iconA = new GIcon();
  iconA.image = "img/iconos/" + iconoCOMIENZO + "18.png";
  iconA.shadow = "img/mm_20_shadow.png";
  iconA.shadowSize = new GSize(22, 22);
  iconA.iconSize = new GSize(18, 18);
  iconA.iconAnchor = new GPoint(6, 20);
  iconA.infoWindowAnchor = new GPoint(5, 1);
			
  iconB = new GIcon();
  iconB.image = "img/iconos/" + iconoCOMIENZO + "22.png";
  iconB.shadow = "img/mm_20_shadow.png";
  iconB.shadowSize = new GSize(22, 20);
  iconB.iconSize = new GSize(22, 22);
  iconB.iconAnchor = new GPoint(6, 20);
  iconB.infoWindowAnchor = new GPoint(5, 1);
	
  iconC = new GIcon();
  iconC.image = "img/iconos/" + iconoCOMIENZO + "24.png";
  iconC.shadow = "img/mm_20_shadow.png";
  iconC.shadowSize = new GSize(22, 20);
  iconC.iconSize = new GSize(24, 24);
  iconC.iconAnchor = new GPoint(6, 20);
  iconC.infoWindowAnchor = new GPoint(5, 1);
	
  iconD = new GIcon();
  iconD.image = "img/iconos/" + iconoCOMIENZO + "28.png";
  iconD.shadow = "img/mm_20_shadow.png";
  iconD.shadowSize = new GSize(22, 20);
  iconD.iconSize = new GSize(28, 28);
  iconD.iconAnchor = new GPoint(6, 20);
  iconD.infoWindowAnchor = new GPoint(5, 1);
	
  iconE = new GIcon();
  iconE.image = "img/iconos/" + iconoCOMIENZO + "32.png";
  iconE.shadow = "img/mm_20_shadow.png";
  iconE.shadowSize = new GSize(22, 20);
  iconE.iconSize = new GSize(32, 32);
  iconE.iconAnchor = new GPoint(6, 20);
  iconE.infoWindowAnchor = new GPoint(5, 1);


  /*Iconos que diferencias los diferentes tipos*/
  iconNARANJA = new GIcon();
  iconNARANJA.image = "img/iconos/naranja20.png";
  iconNARANJA.shadow = "img/mm_20_shadow.png";
  iconNARANJA.iconSize = new GSize(20, 20);
  iconNARANJA.shadowSize = new GSize(22, 20);
  iconNARANJA.iconAnchor = new GPoint(6, 20);
  iconNARANJA.infoWindowAnchor = new GPoint(5, 1);

  iconAZUL = new GIcon();
  iconAZUL.image = "img/iconos/azul20.png";
  iconAZUL.shadow = "img/mm_20_shadow.png";
  iconAZUL.iconSize = new GSize(20, 20);
  iconAZUL.shadowSize = new GSize(22, 20);
  iconAZUL.iconAnchor = new GPoint(6, 20);
  iconAZUL.infoWindowAnchor = new GPoint(5, 1);

  iconVERDE = new GIcon();
  iconVERDE.image = "img/iconos/verde20.png";
  iconVERDE.shadow = "img/mm_20_shadow.png";
  iconVERDE.iconSize = new GSize(20, 20);
  iconVERDE.shadowSize = new GSize(22, 20);
  iconVERDE.iconAnchor = new GPoint(6, 20);
  iconVERDE.infoWindowAnchor = new GPoint(5, 1);
	
	
  iconStart = new GIcon();
  iconStart.image = "img/star.png";
  iconStart.shadow = "img/mm_20_shadow.png";
  iconStart.iconSize = new GSize(20, 34);
  iconStart.shadowSize = new GSize(22, 20);
  iconStart.iconAnchor = new GPoint(6, 20);
  iconStart.infoWindowAnchor = new GPoint(5, 1);
			
  iconEnd = new GIcon();
  iconEnd.image = "img/end.png";
  iconEnd.shadow = "img/mm_20_shadow.png";
  iconEnd.iconSize = new GSize(20, 34);
  iconEnd.shadowSize = new GSize(22, 20);
  iconEnd.iconAnchor = new GPoint(6, 20);
  iconEnd.infoWindowAnchor = new GPoint(5, 1);

	
}


// A function to create the marker and set up the event window
function JS_createMarker(oPoint, oValues) 
{
  var oMarker = new GMarker(oPoint, oValues.icon);
  
  oMap.addOverlay(oMarker);
	
  oMarker.values = oValues;
		
  //Evento que muestra una ventana cuando se hace click
  GEvent.addListener(oMarker, "click", function() 
  {	
    //oMarker.openInfoWindowHtml(oValues.html);
    JS_Bubble(oValues.id);
	
  });
  
  return oMarker;
}

function JS_clearMap()
{
  oMap.clearOverlays();
}
		

function JS_drawMap(oCenterPoint, iMapZoom)
{
  oMap.addControl(new GLargeMapControl());
  oMap.addControl(new GMapTypeControl());
	  
  oMap.addMapType(G_NORMAL_MAP);
  oMap.addMapType(G_SATELLITE_MAP);
  oMap.addMapType(G_HYBRID_MAP);
	  
  //oMap.setCenter(new GLatLng( 43.907787,-79.359741), 9);
  oMap.setCenter(new GLatLng(oCenterPoint.lat, oCenterPoint.long), iMapZoom);
	
}

function JS_openWindow(sLink) {
  window.open(sLink,"Window","width=500,height=400,scrollbars=yes")
}

function JS_myClick(i, iZoom) 
{
  oMap.setCenter(aPoints[i].getPoint(), iZoom);
  //Significa que estamos refiriendos a ir a un punto
  {
    setTimeout("JS_Bubble("+ i +")", 1000);
  }
}

function JS_showInfoPoints()
{
  //Mostramos los checkboxs
  jQuery('#tabFiltro a:eq(0)').show();
  jQuery('#tabFiltro a:eq(0)').css({
    'display':'block'
  });
	
  jQuery('#tabFiltro .checks').show();
	
  //y los seteamos a todos como que si estan seleccionados
  jQuery('.checks input:checkbox').attr('checked', 'checked');
	
  //mostramos la info de los puntos
  jQuery('#tabPuntos a:eq(0)').show();
  jQuery('#tabPuntos a:eq(0)').css({
    'display':'block'
  });
  jQuery('#tabPuntos div').show();
	
  //escondemos el de info y hacemos activo al tab de los puntos
  //ocultamos los resultados de los puntos
  jQuery('#tabInfo a:eq(0)').hide();
  //jQuery('#tabInfo div').hide();
	
  JS_activarTab(1);
	
  //Limpiamos el SideBar
  JS_sideBarClear();
}

function JS_goToProvincia(iIdProvincia) 
{
  //Eventos
  jQuery("#provincia_id option[value='" + iIdProvincia + "']").attr('selected', 'selected');
  //jQuery("#provincia_id").trigger("change");
  //Centramos el punto
	
  JS_getPointProvincia(iIdProvincia);
	
  //Agregamos los puntos sobre el mapa
  JS_showInfoPoints();
  JS_getPointsByProvincia(iIdProvincia);
}

function JS_goToLocalidad(iIdLocalidad, iIdProvincia)
{
  //Centramos el punto
  JS_getPointLocalidad(iIdLocalidad);
	
  //Agregamos los puntos sobre el mapa
  JS_showInfoPoints();
  JS_getPointsByLocalidad(iIdLocalidad);
  //JS_getZipCodesByLocalidad(iIdLocalidad);
}

function JS_getZipCodesByLocalidad(iIdLocalidad)
{
  jQuery.ajax({
    type: "POST",
    url: "ajax/common_mapas.php",
    data: "sFuncion=getZipCodesByLocalidad&iIdLocalidad="+iIdLocalidad,
    dataType: "json",
    success: function(points){
			JS_cargarZips(points);
    }
  });
}

var aZips = null;
function JS_cargarZips(points){

	var select = document.getElementById('codigo_postal');
	select.options.length = 0;
	addOption(select, 'Seleccione un Código Postal', 0);

  aZips = new Array();
  for (var x in points){
		var tmp = points[x];
		addOption(select, tmp.zip, tmp.id);
		aZips[tmp.id] = tmp;
	}
}

function addOption(selectBox, Text, Value){

	if(typeof(selectBox) != 'object'){
		selectBox = document.getElementById(selectBox);
	}

	try {
		selectBox.add(new Option(Text,Value),null);
	} catch(ex){
		selectBox.add(new Option(Text,Value));
	}
}

function addOptions(ElementId, oJsonData, bDisable){
	selectBox = document.getElementById(ElementId);

	var oOption;
	for(var iKey in oJsonData){
		oOption = new Option(oJsonData[iKey].text,oJsonData[iKey].value);
		if(oJsonData[iKey].selected) { oOption.selected = true; }

		try {
			//FF & W3C Compilant
			selectBox.add(oOption,null);
		} catch(ex) {
			//IE
			selectBox.add(oOption);
		}
	}

	if(bDisable=='1'){
		selectBox.disabled = true;
	}
}

function JS_goToPostal(iId)
{

	if(aZips == null){
		return false;
	}

	if(parseInt(iId) == 0){
		return false;
	}

	data = aZips[iId];
	if(data.length == 0){
		return false;
	}

	coords = data.coordenadas.split(',');
	iLat = parseFloat(coords[0]);
	iLng = parseFloat(coords[1]);

	zoomActual = oMap.getZoom();
	if(zoomActual > 14){
		zoomActual = 14;
	}
  oMap.setCenter(new GLatLng(iLat, iLong), zoomActual);

	return true;
}

function JS_goToPoint(iLat, iLong) 
{
  //Primero centramos el punto
  oMap.setCenter(new GLatLng(iLat, iLong), 16);
	
  //Agregamos los puntos sobre el mapa
  JS_showInfoPoints();
	
  var bounds = oMap.getBounds();
  var southWest = bounds.getSouthWest();
  var northEast = bounds.getNorthEast();
	
  var fLatMin = southWest.lat();
  var fLatMax = northEast.lat();
	
  var fLongMin = southWest.lng();
  var fLongMax = northEast.lng();
				
  JS_getPointInPoint(fLatMin,fLatMax,fLongMin,fLongMax);
}

//Pone el selector de provincia en su seleccionar provincia
function JS_initProvincia() 
{
  jQuery("#provincia_id option:eq(0)").attr('selected', 'selected');
  jQuery("#provincia_id").trigger("change");
}

function JS_initLocalidad() 
{
  jQuery("#localidad_id option:eq(0)").attr('selected', 'selected');
  jQuery("#localidad_id").trigger("change");
}

function JS_Bubble(i)
{
  //Si es un grupo
  if (typeof aPoints[i].values.html != 'undefined')
  {
    aPoints[i].openInfoWindowHtml((aPoints[i].values.html));;
  }else
  {
    oHtmlForm = jQuery('#info-bubble-hidden');
    oHtmlForm.find('.imagen').attr("src", aPoints[i].values.icon.image);
    oHtmlForm.find('.nombre p').html(aPoints[i].values.nombre);
    oHtmlForm.find('.direccion').html(aPoints[i].values.direccion);
    oHtmlForm.find('.localidad').html('('+ aPoints[i].values.cp+') '+aPoints[i].values.localidad);
    oHtmlForm.find('.direccion').html(aPoints[i].values.direccion);
    oHtmlForm.find('.provincia').html(aPoints[i].values.provincia);
    //oHtmlForm.find('.telefono').html(aPoints[i].values.telefono);
    /*oHtmlForm.find('.ir_a_punto').attr('href' , 'javascript:JS_goToPoint('+ aPoints[i].getPoint().lat() +', ' + aPoints[i].getPoint().lng() + ')');*/
    if(oMap.getZoom()<14)
    {
      oHtmlForm.find('.ir_a_localidad').attr('href' , 'javascript:JS_goToLocalidad(' + aPoints[i].values.id_localidad + ', ' + aPoints[i].values.id_provincia+ ')').show();
    }else
    {
      oHtmlForm.find('.ir_a_localidad').hide();
    }
		

    oHtmlForm.find('#frm-como-llegar_punto').val(aPoints[i].getPoint().lat()+','+ aPoints[i].getPoint().lng());
		
    aPoints[i].openInfoWindowHtml(oHtmlForm.html());
  //Muestra un mapita con un zoom de la zona
  //aPoints[i].MapBlowup((aPoints[i].getPoint()));
  }
}

function JS_togglePoints(sType)
{
  for(var i=0; i < aPoints.length; i++)
  {
    if(sType == aPoints[i].values.type)
    {
      if(aPoints[i].isHidden()){
        aPoints[i].show();
      }else{
        aPoints[i].hide();
      }
    }
  }
}
 

function JS_getPointsByCountry()
{
  jQuery.ajax({
    type: "POST",
    url: "ajax/common_mapas.php",
    data: "sFuncion=getPointsByCountry",
    dataType: "json",
    success: function(points){
      JS_drawPointsGroup(points);
    }
  });
}

function JS_getPointsByProvincia(iIdProvincia)
{

  log('entro JS_getPointsByProvincia');

  jQuery.ajax({
    type: "POST",
    url: "ajax/common_mapas.php",
    data: "sFuncion=getPointsByProvincia&iIdProvincia="+iIdProvincia,
    dataType: "json",
    success: function(points){

      log('success JS_getPointsByProvincia');

      //dibujamos en el mapa
      JS_drawPoints(points);
    },
		error: function(o, status, error){
			log(error);
		}
  });
}

function JS_getPointsByLocalidad(iIdLocalidad)
{
  jQuery.ajax({
    type: "POST",
    url: "ajax/common_mapas.php",
    data: "sFuncion=getPointsByLocalidad&iIdLocalidad="+iIdLocalidad,
    dataType: "json",
    success: function(points){
      //dibujamos en el mapa
      JS_drawPoints(points);
    }
  });
}

function JS_getPointsByCoordinates(fLatMin,fLatMax,fLongMin,fLongMax)
{
  jQuery.ajax({
    type: "POST",
    url: "ajax/common_mapas.php",
    data: "sFuncion=getPointsByCoordinates&fLatMin="+fLatMin+"&fLatMax="+fLatMax+"&fLongMin="+fLongMin+"&fLongMax="+fLongMax,
    dataType: "json",
    success: function(points){
      //dibujamos en el mapa
      JS_drawPoints(points);
    }
  });
}

function JS_getPointInPoint(fLatMin,fLatMax,fLongMin,fLongMax)
{
  jQuery.ajax({
    type: "POST",
    url: "ajax/common_mapas.php",
    data: "sFuncion=getPointsByCoordinates&fLatMin="+fLatMin+"&fLatMax="+fLatMax+"&fLongMin="+fLongMin+"&fLongMax="+fLongMax,
    dataType: "json",
    success: function(point){
      //dibujamos en el mapa
      JS_drawPoints(point);
    }
  });
}


function JS_getPointLocalidad(iIdLocalidad)
{
  jQuery.ajax({
    type: "POST",
    url: "ajax/common_mapas.php",
    data: "sFuncion=getPointLocalidad&iIdLocalidad=" + iIdLocalidad,
    dataType: "json",
    success: function(point){
      //dibujamos en el mapa
      JS_centerPoints(point, 14);
    }
  });
}

function JS_getPointProvincia(iIdProvincia)
{
  jQuery.ajax({
    type: "POST",
    url: "ajax/common_mapas.php",
    data: "sFuncion=getPointProvincia&iIdProvincia=" + iIdProvincia,
    dataType: "json",
    success: function(point){
      //dibujamos en el mapa
      JS_centerPoints(point, 10);
    }
  });
}


function JS_centerPoints(point, iZoom)
{
  oCenterPoint = new Object();
	
  for (var x in point)
  {
    aCoordenadas = point[x].coordenadas.split(',');
    iLat = aCoordenadas[0];
    iLong = aCoordenadas[1];
		
    oCenterPoint.lat  = iLat;
    oCenterPoint.long = iLong;
  }
  oMap.setCenter(new GLatLng(oCenterPoint.lat, oCenterPoint.long), iZoom);
}

function JS_antesdeprovincia(i){
	JS_goToProvincia(i);
	$('#provincia_id').trigger('change');
}

function JS_drawPointsGroup(points)
{
  JS_clearMap();
  aPoints = new Array();
  var i=0;
  for (var x in points)
  {
    aCoordenadas = points[x].coordenadas.split(',');
    iLat = aCoordenadas[0];
    iLong = aCoordenadas[1];
    var oPoint = new GLatLng(iLat, iLong);
		
    var iCant = points[x].cant;
		
    var html = 'Puntos de Reciclado en  <strong>' + points[x].provincia + ':</strong> ';
    html +=iCant + '<br />';
    html += '<a href="javascript:JS_antesdeprovincia(' + points[x].provincia_id + ');">Ir a la provincia</a>';
		
    if(iCant<50)
    {
      icon = iconA;
    }else if(iCant<100)
    {
      icon = iconB;
    }else if(iCant<200)
    {
      icon = iconC;
    }else if(iCant<300)
    {
      icon = iconD;
    }else if(iCant>300)
    {
      icon = iconE;
    }
    //JS_createMarker(oPoint, html, icon, '');
    aPoints[i] = JS_createMarker(oPoint, {
      'id':i,
      'html': html,
      'group': 'true',
      'icon':icon
    });
    i++;
  }
}

function JS_drawPoints(points)
{
  JS_clearMap();

  log('entro JS_drawPoints');

  aPoints = new Array();
  var i=0;
  for (var x in points)
  {
    iLat = points[x].lats;
    iLong = points[x].longs;
    var oPoint = new GLatLng(iLat, iLong);
		
    var sCod = points[x].color;
    icon = eval(iconMOSTRAR);

    oData = {
      'id':i,
      'icon':icon,
      'group': 'false',
      'type': sCod,
      'nombre': points[x].nombre,
      'direccion':points[x].direccion,
      'id_localidad':points[x].id_localidad,
      'cp':points[x].cp,
      'localidad':points[x].localidad,
      'provincia':points[x].provincia,
      'id_provincia':points[x].id_provincia,
      'telefono':points[x].telefono
      }

    //aPoints[i] = JS_createMarker(oPoint, html, icon, sCod);
    aPoints[i] = JS_createMarker(oPoint, oData);
    
    //Creamos el contenido para el sidebar y lo agregamos
    sSideBarHtml = '<p>';
    sSideBarHtml += '<a href="javascript:JS_myClick(' + i + ', 14)"><strong>' + points[x].nombre + '</strong></a><br/ >';
    sSideBarHtml += points[x].direccion + '<br />';
    sSideBarHtml += points[x].localidad + ', ' + points[x].provincia;
    sSideBarHtml += '</p>';

    JS_sideBarAdd(sSideBarHtml);
    i++;
		
  }
	
  /*Dibujamos los puntos que indican dirección si es que estan seteados*/
  if(typeof oAddress.begin != 'undefined')
  {
    if(oMap.getZoom()>10)
    {
      createMarker2(oAddress.begin,0,iconStart);
      createMarker2(oAddress.end,0,iconEnd);
			
      if (oPoly) oMap.removeOverlay(oPoly);
      oPoly = oGdir.getPolyline();
      oMap.addOverlay(oPoly);
    }
  }
}

/*Funciones para el sidebar*/
function JS_sideBarClear()
{
  jQuery('#side_bar').html('');
}

function JS_sideBarAdd(sHtml)
{
  jQuery('#side_bar').append(sHtml);
}

function JS_showAddress(oObject)
{
  oObject = jQuery(oObject).parent();
	
  sAddr = oObject.find('.frm-como-llegar_addr').val();
  sPoint = oObject.find('#frm-como-llegar_punto').val();

  sInfoLastPoint = "";
  //EROSMER IBERICA, S.A., ALBACETE<br/>calle ALCALDE CONANGLA  Albacete<br/>ALBACETE, Albacete
	
  /*nombre"><img class="imagen" src="img/azul.png"><p>EL CORTE INGLES, S.A. CONQUISTADORES</p></div>
	<p class="direccion">Pza. Conquistadores, 1</p>  <p class="localidad">(06005) BADAJOZ</p>  
	<p class="provincia">Badajoz</p>  <p class="telefono"></p> */
  sInfoLastPoint += oObject.parent().find('.nombre p').html() + "<br />";
  sInfoLastPoint += oObject.parent().find('.direccion').html() + "<br />";
  sInfoLastPoint += oObject.parent().find('.localidad').html() + "<br />";
  sInfoLastPoint += oObject.parent().find('.provincia').html() + "<br />";
	
  JS_Address(sAddr, sPoint, sInfoLastPoint);
  JS_directions(sAddr, sPoint);
}

function JS_showPuntoLejano(oObject)
{
  oObject = jQuery(oObject).parent().parent();
  sLocalidad = oObject.find('#localidad_id option:selected').html();
  sProvincia = oObject.find('#provincia_id option:selected').html();
  sAddress = oObject.find('.direccion-text').val();

  JS_PuntoCercano(sAddress + ', ' + sLocalidad + ' ' + sProvincia);
}

/*
	sAddress: Dirección desde.
	iPointEnd: Punto hasta.
*/
function JS_Address(sAddress, sPointEnd, sInfo)
{
  //oConsole.log("a1");
  //Primer Punto
  oGeo.getLatLng(sAddress, function (point)
  {
    if (point) {
      oAddress.begin = point;
      createMarker2(point,0,iconStart);
    }
    else
    {
      var result=oGeo.getCache().get(sAddress);
      if (result)
      {
        var reason="Code "+result.Status.code;
        if (aReasons[result.Status.code])
        {
          reason = aReasons[result.Status.code]
        }
      }
      else {
        var reason = "";
      }
      alert('Could not find "'+sAddress+ '" ' + reason);
    }
  });
  //Segundo Punto
  oGeo.getLatLng(sPointEnd, function (point)
  {
    if (point)
    {
      oAddress.end = point;
      oAddress.end.info = sInfo;
      createMarker2(point,4,iconEnd);
      JS_activarTab(2);
    }
    else
    {
      var result=oGeo.getCache().get(sPointEnd);
      if (result)
      {
        var reason="Code "+result.Status.code;
        if (aReasons[result.Status.code])
        {
          reason = aReasons[result.Status.code]
        }
      }
      else
      {
        var reason = "";
      }
      alert('Could not find "'+sPointEnd+ '" ' + reason);
    }
  });
}

function JS_PuntoCercano(sAddress)
{
  //oConsole.log("a1");
  //Primer Punto
  oGeo.getLatLng(sAddress, function (point)
  {
    if (point) {
      oAddress.begin = point;
      createMarker2(point,0,iconStart);
      oMap.setCenter(point, 12);
    }
    else
    {
      var result=oGeo.getCache().get(sAddress);
      if (result)
      {
        var reason="Code "+result.Status.code;
        if (aReasons[result.Status.code])
        {
          reason = aReasons[result.Status.code]
        }
      }
      else {
        var reason = "";
      }
      alert('Could not find "'+sAddress+ '" ' + reason);
    }
  });
}

function createMarker2(point,i,icon) 
{
  var marker = new GMarker(point, {
    icon:icon
  });
  oMap.addOverlay(marker);
	
  //mostramos el contenedor de como llegar
  jQuery('#tabComoLlegar a:eq(0)').show();
  jQuery('#tabComoLlegar a:eq(0)').css({
    'display':'block'
  });
}

function JS_activarTab(idTab)
{
  jQuery("#sidebar_acordeon").accordion("activate", idTab);
}

function JS_directions(sAddress, sPointEnd)
{
  if (sAddress)
  {
    var a = sAddress;
  }else
  {
  //var a = side_bar[0].toUrlValue(6)
  }
        
  if (sPointEnd) {
    var b = sPointEnd;
  }
  else
  {
  //var b = side_bar[4].toUrlValue(6)
  }
		
  /*
		for (var i=3; i>0; i--) {
			if (active[i]) {
				b = side_bar[i].toUrlValue(6) +" to: "+b;
			}
		}*/

  iControl = 1;
  var a = "from: "+a + " to: " + b;
  oGdir.load(a, {
    getPolyline:true
  });
  return iControl;
}

function log(txt){
  //console.log(txt);
  return true;
}



// ============ custom direction panel ===============
function customPanel(map,mapname,oGdir,div) {
  var html = "";
		
  // ===== local functions =====
		
  // === waypoint banner ===
  function waypoint(point, type, address) {
    var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
    html += '<table style="border: 1px solid silver; margin: 10px 0px; background-color: rgb(238, 238, 238); border-collapse: collapse; color: rgb(0, 0, 0);">';
    html += '  <tr style="cursor: pointer;" onclick='+target+'>';
    html += '    <td style="padding: 4px 15px 0px 5px; vertical-align: middle; width: 20px;">';
    html += '      <img src="img/' +type+ '.png">'
    //html += '      <img src="http://www.google.com/intl/en_ALL/mapfiles/icon-dd-' +type+ '-trans.png">'
    html += '    </td>';
    html += '    <td style="vertical-align: middle; width: 100%;">';
    html +=        address;
    html += '    </td>';
    html += '  </tr>';
    html += '</table>';
  }
		
  // === route distance ===
  function routeDistance(dist) {
    html += '<div style="text-align: right; padding-bottom: 0.3em;">' + dist + '</div>';
  }
		
  // === step detail ===
  function detail(point, num, description, dist) {
    var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
    html += '<table style="margin: 0px; padding: 0px; border-collapse: collapse;">';
    html += '  <tr style="cursor: pointer;" onclick='+target+'>';
    html += '    <td style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px; vertical-align: top; text-align: right;">';
    html += '      <a href="javascript:void(0)"> '+num+'. </a>';
    html += '    </td>';
    html += '    <td style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px; vertical-align: top; width: 100%;">';
    html +=        description;
    html += '    </td>';
    html += '    <td style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px 0.3em 0.5em; vertical-align: top; text-align: right;">';
    html +=        dist;
    html += '    </td>';
    html += '  </tr>';
    html += '</table>';
  }
		
		
		
  // === read through the GRoutes and GSteps ===
		
  for (var i=0; i<oGdir.getNumRoutes(); i++) {
    if (i==0) {
      var type="star";
    } else {
      var type="1x1";
    }
    var route = oGdir.getRoute(i);
    var geocode = route.getStartGeocode();
    var point = route.getStep(0).getLatLng();
    // === Waypoint at the start of each GRoute
    waypoint(point, type, geocode.address);
    routeDistance(route.getDistance().html+" (about "+route.getDuration().html+")");
		
    for (var j=0; j<route.getNumSteps(); j++) {
      var step = route.getStep(j);
      // === detail lines for each step ===
      detail(step.getLatLng(), j+1, step.getDescriptionHtml(), step.getDistance().html);
    }
  }
		
  // === the final destination waypoint ===
  var geocode = route.getEndGeocode();
  var point = route.getEndLatLng();
  if(typeof oAddress.end!='undefined')
  {
    //waypoint(point, "end","EROSMER IBERICA, S.A., ALBACETE<br/>calle ALCALDE CONANGLA  Albacete<br/>ALBACETE, Albacete");
    waypoint(point, "end",oAddress.end.info);
  }
		
				 
		
  // === drop the whole thing into the target div
  document.getElementById("contComoLlegar").innerHTML = html;
// div.innerHTML = html;
		
} // ============ end of customPanel function ===========


jQuery(document).ready(function()
{
  if (GBrowserIsCompatible())
  {
    oMap = new GMap2(document.getElementById("map"));
		
		
    jQuery("#provincia_id").change(function(){
      //JS_goToProvincia();
      iOption = jQuery(this).val();
      if(iOption!=0)
      {
        JS_goToProvincia(iOption);
      }
    });
		
    jQuery("#localidad_id").change(function(){
      iOption = jQuery(this).val();
      if(iOption!=0)
      {
        JS_goToLocalidad(iOption,0);
      }
		  
    });
		
    jQuery("#codigo_postal").change(function(){
      iOption = jQuery(this).val();
      if(iOption!=0)
      {
        JS_goToPostal(iOption);
      }
    });

		
		
    /*------DIRECCIONES--------*/
    iState = 0;
    iControl = 0;

    //Creamos el clinte de geolocalización
    oGeo = new GClientGeocoder(new GGeocodeCache());

    // ====== Array for decoding the failure codes ======
    var aReasons=[];
    aReasons[G_GEO_SUCCESS]            = "Peticion realizada con éxito";
    aReasons[G_GEO_MISSING_ADDRESS]    = "Dirección erronea: La dirección es inexistente o no tiene valor. ";
    aReasons[G_GEO_UNKNOWN_ADDRESS]    = "Dirección desconocida: La ubicación geográfica podría no ser encontrada.";
    aReasons[G_GEO_UNAVAILABLE_ADDRESS]= "Dirección No disponible: La codificación geográfica de la dirección dada no puede ser devuelto, debido a razones legales o contractuales.";
    aReasons[G_GEO_BAD_KEY]            = "Bad Key: La clave de la API es inválida o no coincide con el dominio para el que se origino.";
    aReasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: Se ha excedido la cantidad de consultas diarias para este sitio.";
    aReasons[G_GEO_SERVER_ERROR]       = "Error del servidor: La solicitud de códigos geográficos no podían ser procesados con éxito. ";
    aReasons[G_GEO_BAD_REQUEST]        = "La petición de direcciones no puede ser analizada con éxito. ";
    aReasons[G_GEO_MISSING_QUERY]      = "No se ha especificado la consulta en la entrada.";
    aReasons[G_GEO_UNKNOWN_DIRECTIONS] = "El objeto GDirections no pudo calcular las direcciones entre los puntos.";
		
    //Creamos el objeto de las direcciones y le decimos donde queremos que las agregue
    oGdir = new GDirections(null, document.getElementById("contComoLlegar"));

    //Eventos de la carga de las direcciones
    GEvent.addListener(oGdir,"error", function() {
      var code = oGdir.getStatus().code;
      var reason="Code "+code;
      if (aReasons[code]) {
        reason = "Code "+code +" : "+aReasons[code]
      }
      alert("Failed to obtain directions, "+reason);
    });
	
    GEvent.addListener(oGdir, "load", function() {
      if (oPoly) oMap.removeOverlay(oPoly);
      oPoly = oGdir.getPolyline();
      oMap.addOverlay(oPoly);
    });
		
		
		
		
    // ========== launch the custom Panel creator a millisecond after the GDirections finishes loading ==========
    // == The delay is required in case we rely on GDirections to perform the initial setCenter ==
    GEvent.addListener(oGdir,"load", function() {
      setTimeout('customPanel(oMap,"oMap",oGdir,document.getElementById("path"))', 1);
    });

		
		
		
		
    /*------END-DIRECCIONES--------*/
		
    //Forzamos a tener marcados todlos los checks del filtro
    jQuery('#tabFiltro .checks input:checkbox').attr('checked', 'checked')

    //Creamos el objeto q va a contener las direcciones
    oAddress = new Object();
		
    //Centramos el Primer Punto
    oCenterPoint = new Object();
		
		
    if(jQuery.browser.msie)
    {
      oCenterPoint.lat = 40.00;
      oCenterPoint.long = -4.482421875;
    }else
    {
      oCenterPoint.lat = 39.95953361677018;
      oCenterPoint.long = -4.482421875;
    }
		
		
		
    iMapZoom = 6;
		
    JS_loadIcons();
		
    JS_drawMap(oCenterPoint,iMapZoom);
		
    //mostramos el sidebar de informacion
    jQuery('#tabInfo a:eq(0)').show();
    jQuery('#tabInfo div').css({
      'height':'404px'
    });
    JS_activarTab(0);
		
    //ocultamos los checkboxs
    jQuery('#tabFiltro a:eq(0)').hide();
    jQuery('#tabFiltro .checks').hide();
		
    //ocultamos los resultados de los puntos
    jQuery('#tabPuntos a:eq(0)').hide();
    jQuery('#tabPuntos div').hide();
		
    //ocultamos el como llegar
    jQuery('#tabComoLlegar a:eq(0)').hide();
    jQuery('#tabComoLlegar div').hide();
    JS_getPointsByCountry();
  }
});

