var mapa;
var gris;
var max_bounds;
var centro;
var pathCoordinates;

window.addEvent('domready', function () {

    myChain = new Chain();

    myChain.chain (
        iniciar_mapa(),
        cargar_usuarios()        
    );
        
});

function TileToQuadKey ( x, y, zoom){
    var quad = "";
    for (var i = zoom; i > 0; i--) {
        var mask = 1 << (i - 1);
        var cell = 0;
        if ((x & mask) != 0)
            cell++;
        if ((y & mask) != 0)
            cell += 2;
        quad += cell;
    }
    return quad;
}

var madrid = new google.maps.ImageMapType({
    getTileUrl: function(coord, zoom) {
        return "http://www.mapearmadrid.net/tiles/" + TileToQuadKey(coord.x,coord.y,zoom) + ".png";
    },
    tileSize: new google.maps.Size(256, 256),
    isPng: true,
    maxZoom: 14,
    name: 'Madrid',
    alt: 'Mapear Madrid'
});

function iniciar_mapa ()
{
    //var latlng = new google.maps.LatLng(40.577837312687215, -3.7968861890625005); // Punto calculado para centrar el mapa
    var latlng = new google.maps.LatLng(40.5402771166058, -3.4590565992187505); // Punto calculado para centrar el mapa
    centro = latlng;
    
    var myOptions = {
      zoom: 9,
      center: latlng,
      mapTypeControl: false,
      scaleControl: false,
      disableDoubleClickZoom: false,
      draggable: true,
      scrollwheel: false
    };

    mapa = new google.maps.Map(document.getElementById("mapa"), myOptions);
    mapa.setMapTypeId('madrid');
    mapa.mapTypes.set('madrid', madrid);

    google.maps.event.addListener(mapa, 'zoom_changed', function() {
        if (mapa.getZoom() > 11) mapa.setZoom(11);
        if (mapa.getZoom() < 9) mapa.setZoom(9);
    });

    google.maps.event.addListener(mapa, 'tilesloaded', function(e) {
        google.maps.event.clearListeners(mapa, 'tilesloaded');
        mostrar_mapa();
        $('mapa').setStyle('background-color', '#E6E6E6');
    });

}

function mostrar_mapa ()
{
    $('over_mapa').fade('out');
}

function cargar_usuarios ()
{
    usuarios.each(function (u) {
        var latlng = new google.maps.LatLng(u.lat, u.lng);
        add_marker(u.nombre, latlng, u.tipo, u.id);
    });
}

function buscar_direccion (direccion, nombre, tipo)
{
    var geo = new google.maps.Geocoder();
    geo.geocode( { 'address': direccion }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var posicion;
            results.each(function (res) {
                posicion = res.geometry.location;
            });
            add_marker(nombre, posicion, tipo);
        } 
      });
}


function add_marker (nombre, posicion, tipo, id)
{
    var image = base_url + 'img/marker_'+ tipo.toLowerCase() +'.png';
    var marker = new google.maps.Marker({
        position: posicion,
        map: mapa,
        title: nombre,
        icon: image        
    });

    // Agregamos el nombre y el tipo de usuario a la ventana
    // y reamos el evento click en el marker para abrirla
    var contentString = '<p class="usuario '+tipo.toLowerCase()+'"><a href="http://www.mapearmadrid.net/usuario/'+id+'/" title="'+nombre+'">'+nombre+'</a></p>';
    google.maps.event.addListener(marker, 'click', function(e) {
      var infoBox = new InfoBox( { latlng: marker.getPosition(), map: mapa, content: contentString });
    });
}

