/*  Javascript functions for the locations app.
*
*   Requires: Trapeze jQuery distribution
*
*   Zach Mathew - October 2009
*/

$.namespace("trapeze.Locations");

trapeze.Locations = $.Class.extend({
			 
    geocode_and_submit : function() {
	var form = this;
	var inputField = $(form).find('input[name=location]');
	var resultsField = $(form).find('input[name=geocode_results]');
	
	// If we can't find the fields, don't continue
	if(inputField.length < 1 || resultsField.length < 1) {
	    return false;
	}
	
	var geocoder = new GClientGeocoder();
	
	function geocode_callback(response) {
	    // Takes a geocoder.getLocations response and parses it into an array of matches
	    // and set the value of resultsField to a JSON string representation of the array.
	    var results = new Array();
	    if(response.Status.code == 200) {
		for(var i=0; i<response.Placemark.length; i++) {
		    place = response.Placemark[i];
		    results[i] = [place.address, [place.Point.coordinates[1], place.Point.coordinates[0]]];
		}
	    }
	    resultsField.val(JSON.stringify(results));
	    form.submit();
	}
	geocoder.getLocations(inputField.val(), geocode_callback);
	
	return false;
    },
    
    geocode_before_submit : function(formId) {
	$('#'+formId).submit(this.geocode_and_submit);
    },
    
    generate_map: function(divId, markers) {
        // Generates a dynamic google map in the given div, with the given markers
        if (GBrowserIsCompatible()) {
            var selected = $('#'+divId);
            if(selected.length < 1) {
                // If we can't find the div to put the map into, stop here
                return false;
            }
            
            var map = new GMap2(selected[0]);
            map.setUIToDefault(); // Default controls
            // Keeping bounds will help up zoom and center to the right positions.
            var bounds = new GLatLngBounds();
            
            for(i=0; i<markers.length; i++) {
                var marker = markers[i]
                var latlang = marker.getLatLng();
                bounds.extend(latlang);
                map.addOverlay(marker); // Add the marker
            }
            map.setCenter(bounds.getCenter());
            map.setZoom(map.getBoundsZoomLevel(bounds));
            return true;
        } else {
            return false;
        }
    },
    
    init : function() {}
});