// The map object
var map;

/**
 * Called when the page has loaded to initialize the map and search form
 */
 /*
function init() {
	var params = {
		'id' : 'mapDiv'
	};
    // create the map
    map = new GSMap(params);
    map.addControl(GSMap.MAP_CONTROL);
    map.centerOnNewZealand();

    // add event handlers
    $('searchForm').onsubmit = search;
    $('clear').onclick = clear;
}
*/

/**
 * Initiates searching with the POI web service
 */
function search() {
    // display the loading graphic
    Element.show('loader');

    // use the Prototype Form object to get the form values as a string
    var params = Form.serialize('mapsearch');
	
    // add the map center to the params string
    var center = map.getMapCenter();
    params += '&x=' + center.x + '&y=' + center.y;

    // the POI web service is accessed through a server-side proxy
    var url = '/new-zealand-maps/resources/geo-smart/proxy.php';
    
    // use the Prototype Ajax.Request class to search with the POI web service
    var req = new Ajax.Request(url, {method: 'get', parameters: params, onComplete: searchComplete});
    return false;
}

/**
 * Callback function that will be called by the Prototype library when the background request
 * has completed
 */
function searchComplete(response) {
    // evaluate the JSON data
    var data = eval('(' + response.responseText + ')');

    // get the map's base layer and remove previous search results, if any
    var layer = map.getLayer('base');
    layer.clear(); 

    // add the search results to the map
    layer.addFeaturesJson(data.pois.poi, initFeature);

    // hide the loading graphic
    Element.hide('loader');
}

/**
 * Callback function, called for each feature added to the map
 */
function initFeature(feature, data) {
    // build the HTML string to display in the popup window when the feature is clicked
    var html = '<strong>' + feature.name + '</strong><br/>';
    html += feature.suburb + ', ' + feature.region;
    feature.infoHtml = html;
    
    // attach a 'click' event handler to the feature to show the popup
    feature.addEventHandler('click', function(e) {
            this.showInfoWindow();
            GSUtil.cancelEvent(e);
        });
}

/**
 * Remove search results from the map, re-center on NZ, and then do the
 * default form reset action
 */
function clear() {
    map.closeInfoWindow();
    map.clearLayers();
    map.centerOnNewZealand();
    return true;
}

//window.onload = init;
