//google.load("jquery", '1.2.6');
//google.load("maps", "2.x", {"callback" : mapLoaded});

if(document.getElementById("map"))
google.load("maps", "2.x");


function mapLoaded()
{
    //here you can be sure that maps api has loaded
    //and you can now proceed to render the map on page
    /*if (GBrowserIsCompatible())
    {
        var map = new GMap2(document.getElementById("map_canvas"));
        map.setMapType(G_SATELLITE_MAP);
        map.setCenter(new GLatLng(28.631466106808542, 77.07853317260742), 5);
    }*/
}

jQuery(function(){
    if(document.getElementById("map")){
        var map = new GMap2(document.getElementById('map'));
        var burnsvilleMN = new GLatLng(44.797916, -93.278046);
    //    map.setCenter(burnsvilleMN, 8);
        map.setUIToDefault();
        var bounds = new GLatLngBounds();
        var geo = new GClientGeocoder();
        
        var reasons=[];
        reasons[G_GEO_SUCCESS]            = "Success";
        reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address";
        reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address.";
        reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address";
        reasons[G_GEO_BAD_KEY]            = "Bad API Key";
        reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries";
        reasons[G_GEO_SERVER_ERROR]       = "Server error";
        
        
    // initial load points
    jQuery.getJSON($site_url+"/wp-content/plugins/dm-markers/map-service.php?action=listpoints", function(json) {
        if (json.Locations.length > 0) {
            for (i=0; i<json.Locations.length; i++) {
                var location = json.Locations[i];
                addLocation(location);
            }
            zoomToBounds();
        }
    });
    
    jQuery("#add-point").submit(function(){
        geoEncode();
        return false;
    });
    
    function savePoint(geocode) {
        var data = jQuery("#add-point :input").serializeArray();
        data[data.length] = { name: "lng", value: geocode[0] };
        data[data.length] = { name: "lat", value: geocode[1] };
        for(var e=0; e<data.length; e++){  /* var_dump(data[e]); */        }
        jQuery.post(jQuery("#add-point").attr('action'), data, function(json){
//            var_dump(json.data);
            jQuery("#add-point .error").fadeOut();
            if (json.status == "fail") {
                jQuery("#add-point .error").html(json.message).fadeIn();
            }
            if (json.status == "success") {
                jQuery("#add-point :input[name!=action]").val("");
                var location = json.data;
                addLocation(location);
                zoomToBounds();
            }
        }, "json");
    }
    
    function geoEncode() {
        var address = jQuery("#add-point input[name=address]").val();
        geo.getLocations(address, function (result){
            if (result.Status.code == G_GEO_SUCCESS) {
                geocode = result.Placemark[0].Point.coordinates;
                savePoint(geocode);
            } else {
                var reason="Code "+result.Status.code;
                if (reasons[result.Status.code]) {
                    reason = reasons[result.Status.code]
                }
                jQuery("#add-point .error").html(reason).fadeIn();
                geocode = false;
            }
        });
    }
    
    // Creates a marker whose info window displays the letter corresponding
    // to the given index.
    function createMarker(point, html) {
      var marker = new GMarker(point, markerOptions);
      
      GEvent.addListener(marker, "click", function() {
//        marker.openInfoWindowHtml("Marker <b>" + letter + "</b>");
//        map.openInfoWindowHtml(point, document.createTextNode("Hello, world"));
        marker.openInfoWindowHtml(html);
      });
      return marker;
    }
    
    function addLocation(location) {
        var point = new GLatLng(location.lat, location.lng);
        var marker = new GMarker(point);
        map.addOverlay(marker);
        bounds.extend(marker.getPoint());
        
//        jQuery("<li />").html(location.name).click(function(){ showMessage(marker, location.name);  }).appendTo("#list");
        
        GEvent.addListener(marker, "click", function(){
//                            var_dump(location)
                        // showMessage(this, location.name); 
                           marker.openInfoWindowHtml("<strong>"+location.name+"</strong><br />"+location.address+"<br />"+location.state+" "+location.zip);
        });
        
        closeForm();
    }
    
    function zoomToBounds() {
        map.setCenter(bounds.getCenter());
        map.setZoom(map.getBoundsZoomLevel(bounds)-1);
    }

    jQuery("#message").appendTo( map.getPane(G_MAP_FLOAT_SHADOW_PANE) );
    
    function openForm(){
        jQuery('#add-point').show().animate({
                width: '344px',
                 height: '320px'
          }, 500, function() {
            jQuery('#dm-Marker-wrapper #show_map_frm').hide();
            jQuery('#add-point .b_maximize').hide();
            jQuery('#add-point .b_minimize').show();
          });
    }
    function closeForm(){
        jQuery('#add-point').animate({
                width: '0px',
                height: '0px'
          }, 500, function() {
            jQuery('#add-point').hide();
            jQuery('#add-point .b_maximize').show();
            jQuery('#dm-Marker-wrapper #show_map_frm').show();
          });
    }
    jQuery('#dm-Marker-wrapper #show_map_frm').click(function() {     openForm();       });
    jQuery('#add-point .b_maximize').click(function() {     openForm();       });
    jQuery('#add-point .b_minimize').click(function() {     closeForm();      });
    
    function showMessage(marker, text){
        var markerOffset = map.fromLatLngToDivPixel(marker.getPoint());
        jQuery("#message").hide().fadeIn().css({ top:markerOffset.y, left:markerOffset.x }).html(text);
    }    

    }
    
});
