/* Geo uploader mapping */
function initMap() {
    console.log('initMap');
    // Default map center to Toronto, Ontario, Canada
    var map = initGMap(43.7348,-79.4826);
    window.map = map;


    // We need to keep track of all the markers we add to the map to ensure we don't add duplicates in the mediaUpdater function
    var mapMarkers = new Hash ();

    var updateTimer = null;

    try {
        var mediaUpdater = function () {
            var params = {
                'vhost'  : selectedVHost,
                'filters' : {
 					'channel':'343',
                    'geoBoundaries' : [
                        map.getBounds().getNorthEast().lat(),
                        map.getBounds().getNorthEast().lng(),
                        map.getBounds().getSouthWest().lat(),
                        map.getBounds().getSouthWest().lng()
                    ]
                },
                'fields' : [ 'geo_longitude', 'geo_latitude', 'title' ]
            };


            jsonRequest('media.getFiles',params, function(result) {
                try {
                    for(var i=0; i<result.data.length; i++) {
                        var item = result.data[i];

                        if ( mapMarkers.get ( item.id ) )
                            continue;

                        if (item.geo_longitude && item.geo_latitude) {
                            var latlng = new GLatLng(item.geo_latitude,item.geo_longitude);
                            var marker = new GMarker(latlng);
                            marker.mediaInfo = item;
                            GEvent.addListener(marker,'click',function() {
                                this.openInfoWindowHtml('<div style="height: 130px; width: 140px; font-family:sans-serif;font-size:9px;text-transform:uppercase;background-color:white;"> ' + this.mediaInfo.title.escapeHTML() + '<p><img src="' + this.mediaInfo.thumbUrl + '/12" /><br /><a style="color:black;text-decoration:underline;" href="/article/' + this.mediaInfo.id + '?vid=' + selectedVHost + '">+ View</a></p></div>');
                            });

                            map.addOverlay(marker);

                            mapMarkers.set ( item.id, marker );
                        }
                    }
                } catch (ex) { console.log(ex); }
            },false,true);
        }

        // Only update media 3 seconds after a map movement has ended and cancel any other media updates that may be pending.
        GEvent.addListener ( map, 'moveend', function () {
            if ( updateTimer != null )
                clearTimeout ( updateTimer );

            setTimeout ( mediaUpdater, 3000 );
        } );

        mediaUpdater ();

    } catch (ex) { console.log(ex); }

}

function initGMap(lat,lng) {

    console.log('initGMap');
    /* Google maps initialization */

    window.map = new GMap2(document.getElementById("map_canvas"));
    var map = window.map;
    map.setMapType(G_SATELLITE_MAP);

    var latlng = new GLatLng(lat, lng);

    // Zoom level 4 will allow the majority of North America to appear in the map by default
    map.setCenter(latlng, 10);

    var zoomer = new GLargeMapControl();
    map.addControl(zoomer);

    var maptype = new GMapTypeControl(false);
    map.addControl(maptype);

    map.enableContinuousZoom();
    //map.enableGoogleBar();
    map.enableScrollWheelZoom();

    return map;

}

function selectLocation(map,latlng, center,zoom) {

  console.log('selectLocation');
  console.log(latlng);
  if (!zoom) zoom = 10;
  if (center) window.map.setCenter(latlng, zoom);
}



function searchAddress(searchString) {

   console.log('searchAddress');
   var geocoder = new GClientGeocoder();
   geocoder.getLatLng(searchString, function(point) { 

        if (point) {
            selectLocation(window.map, point, true);
        } else {
            Messenger.message(1,searchString + ' not found!');
        }

   });
}


function centreMap()
{
    var address = $('map-search').value;
    if (address.length > 0) {
        var geocoder = new GClientGeocoder();
        geocoder.getLatLng(address, function(point) {
            if (!point) {
                alert('Address "' + address + '" not found');
            } else {
                window.map.setCenter(point, 8);
            }
        });
    }
}



AppInit.addEvent(initMap);


