var map;
var locations;

$(document).ready(function() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
        map.addControl(new GSmallMapControl());
        map.setCenter(new GLatLng(0, 0), 13);
        $.get('/developments.json', processLocations);
    }
});

$(window).unload(GUnload());

function processLocations(content) {
    eval("locations = " + content);
    $(locations).each(function(index, element) {
        if (element.current == '1') {
			if (element.design_build == '1') {
				myIcon = new GIcon(G_DEFAULT_ICON);
				myIcon.image = "/media/main/pin.png";
			} else {
				myIcon = new GIcon(G_DEFAULT_ICON);
				myIcon.image = "/media/main/marker.png";
			}
        } else {
            myIcon = new GIcon(G_DEFAULT_ICON);
        }
        var marker = new GMarker(new GLatLng(element.latitude, element.longitude), {title: element.development_title, icon: myIcon});
        map.addOverlay(marker);
        html = '<h3>' + element.development_title + '</h3>';
        //if (element.properties_count > 1) html += element.properties_count + ' properties available';
        //else if (element.properties_count == 1) html += element.properties_count + ' property available';
        //else html += element.development_zero_title;
        html += element.development_desc;
        //if (element.properties_start_price != '0') html += ' starting from &pound;' + element.properties_start_price;
        html += '<br /><br /><a href="/development/' + element.development_id + '">Find out more</a>';
        element.html = html;
        GEvent.addListener(marker, 'click', function() {
            marker.openInfoWindowHtml(element.html);       
        });
        $('#development' + element.development_id).click(function () {
            moveMapTo(index);
            marker.openInfoWindowHtml(element.html);
            return false;
        });
    });
    zoomShowAll();
}

function moveMapTo(index) {
    map.panTo(new GLatLng(locations[index].latitude, locations[index].longitude), 5);
}

function zoomShowAll() {
    bounds = new GLatLngBounds();
    map.setCenter(new GLatLng(0,0),0);
    $(locations).each(function(index, element) {
        bounds.extend(new GLatLng(locations[index].latitude, locations[index].longitude));
    });
    map.setZoom(map.getBoundsZoomLevel(bounds));
    var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
    var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
    map.setCenter(new GLatLng(clat,clng));
}