/**
 * Some util methods for the google maps frames inside the dooplan site.
 */

var initial_zoom = 14;
var mgr;
var NormalLayer = G_NORMAL_MAP.getTileLayers()[0];
var SatelliteLayer = G_SATELLITE_MAP.getTileLayers()[0];
var LabelsLayer = G_HYBRID_MAP.getTileLayers()[1];
var PhysicalLayer = G_PHYSICAL_MAP.getTileLayers()[0];
bounds = new GLatLngBounds( new GLatLng(-90, -180)
                          , new GLatLng(90, 180)
                           );
copyright = new GCopyright('Quedan reservados todos los derechos de explotación.'
                          , bounds
                          , 0
                          , "Copyright © 2008 Organic Advanced Company, S.L. " +
                            "<http://www.dooplan.com/>"
                           );
var copyrights = new GCopyrightCollection();
copyrights.addCopyright(copyright);

function createMarker(latitude, longitude, info, icon, value){
    point = new GLatLng(latitude,longitude);
    var options = {}
    if (icon){
        options = {icon:icon,zIndexProcess:function (marker,b){return 1000;}}
    }
    var m = new GMarker(point, options);
    //info = info+ "<br/> VAL: "+value;
    GEvent.addListener(m, "click", function() {
       m.openInfoWindowHtml(info);
    });
    return m;
}

function createDooplanMap(divId, latitude, longitude, zoom, view, markerData, heat, filter){

   if (GBrowserIsCompatible()) {
    var map = new GMap2(document.getElementById(divId));
    map.enableDoubleClickZoom();
    map.enableContinuousZoom();
    map.addControl(new GSmallMapControl());
    map.setCenter(new GLatLng(latitude,longitude), zoom, map.getMapTypes()[view]);


    heatmapGheat = heat;
    showMarkers = true;

    if (heatmapGheat){
        initGheatMap(map, filter);
    }
    if (showMarkers) {
        // preparing the manager for the markers, zoomable and permanents
        markers = []
        permanent_markers = []
        for (var i in markerData){
            if (markerData[i].icon) {
                // We are in an special iconed place, so add it to the permanent
                var icon = new GIcon();
                icon.image = markerData[i].icon;
                icon.shadow = MEDIA_URL+"_img/shadow-publiWrapper.png";
                icon.iconSize = new GSize(65.0, 80.0);
                icon.shadowSize = new GSize(106.0, 80.0);
                icon.iconAnchor = new GPoint(32.0, 40.0);
                icon.infoWindowAnchor = new GPoint(32.0, -1.0);

                m = createMarker(markerData[i].latitude, markerData[i].longitude, markerData[i].info, icon, markerData[i].value);
                permanent_markers.push(m);

            } else {
                m = createMarker(markerData[i].latitude, markerData[i].longitude, markerData[i].info, null, markerData[i].value);
                markers.push(m);
            }
        }
        if (!heat){
            initial_zoom = 0
        }
        mgr = new MarkerManager(map, {trackMarkers:false});
        mgr.addMarkers(markers, initial_zoom);
        mgr.refresh();
        permanent_mgr = new MarkerManager(map, {trackMarkers:false});
        permanent_mgr.addMarkers(permanent_markers, 0);
        permanent_mgr.refresh();
    }

    return map;
   }
}

function initGheatMap(map, filter_to_show){
    //addCustomMaps(map);
    map.removeMapType(G_HYBRID_MAP);
    map.addMapType(G_PHYSICAL_MAP);

    map.addControl(new GMapTypeControl());

    for (var filter in filterMetaData) {
        layer = createCustomLayer(filter)
        filterMetaData[filter].layer = layer
    }

    map.addOverlay(filterMetaData[filter_to_show].layer)

    /* Uncomment this code in case we want ajax reloading for the different week segmentations

    // Initialize listeners for the weeksegmentation buttons
    jQuery("#today, #tomorrow, #weekend").bind("click",function(){
        newMenu = jQuery(this)
        oldMenu = jQuery("#today, #tomorrow, #weekend").filter(".TextoResaltado")
        if (newMenu.attr("id") == oldMenu.attr("id")){
            return;
        }
        // gheat overlay
        map.clearOverlays()
        map.addOverlay(filterMetaData[newMenu.attr("id")].layer)

        // adding pinpoints to appear on the initial_zoom
        markers = getMarkersForFilter(newMenu.attr("id"));
        mgr.clearMarkers();
        mgr.addMarkers(markers, initial_zoom);
        mgr.refresh();

        // Change the clases to display the selected filter
        oldMenu.attr("class",filterMetaData[oldMenu.attr("id")].disabledClass)
        newMenu.attr("class",filterMetaData[newMenu.attr("id")].enabledClass)
    })
    jQuery().ajaxStart(function(){
        jQuery.blockUI({ css: {
                    border: 'none',
                    padding: '15px',
                    backgroundColor: '#000',
                    '-webkit-border-radius': '10px',
                    '-moz-border-radius': '10px',
                    opacity: '.5',
                    color: '#fff'

                },
                message: '<h1><img src="'+MEDIA_URL+'_img/loading.gif" /> Cargando...</h1>'
            })
    }
    ).ajaxStop(function(){
        jQuery.unblockUI();
    });*/

}

function getMarkersForFilter(filter){
    if (!filterMetaData[filter].markerData){
        // We have to fill the filter from the server with the corresponding data
        jQuery.ajax({
           type: "GET",
           url: filterMetaData[filter].url,
           async: false,
           dataType: "json",
           success: function(data, txt){
             filterMetaData[filter].markerData = data;
           }
         });
    }
    // Now we have to create the markers from the data

    markers = []
    markerData = filterMetaData[filter].markerData
    for (var i in markerData){
        m = createMarker(markerData[i].latitude,
                markerData[i].longitude,
                markerData[i].info,
                markerData[i].value);
        markers.push(m);
    }
    return markers;
}


function createCustomLayer(filter) {
    tilelayer = new GTileLayer(copyrights, null, null, {
        tileUrlTemplate:"/gheat/firetrans/"+filter+"/{Z}/{X},{Y}.png",
        isPng: true,
        opacity: 1
        })
    return new GTileLayerOverlay(tilelayer)
}

