/*|----------------------------------------------------------------------------------------------
 *|														University of Heidelberg
 *|	  _____ _____  _____      _                     	Department of Geography		
 *|	 / ____|_   _|/ ____|    (_)                    	Chair of GIScience
 *|	| |  __  | | | (___   ___ _  ___ _ __   ___ ___ 	(C) 2011
 *|	| | |_ | | |  \___ \ / __| |/ _ \ '_ \ / __/ _ \	
 *|	| |__| |_| |_ ____) | (__| |  __/ | | | (_|  __/	Berliner Strasse 48								
 *|	 \_____|_____|_____/ \___|_|\___|_| |_|\___\___|	D-69120 Heidelberg, Germany	
 *|	        	                                       	http://www.giscience.uni-hd.de
 *|----------------------------------------------------------------------------------------------*/


/**
 * Class: Nominatim
 * Connector to OMS's Nominatim Geocoding Service
 * 
 * @author Oliver Roick, roick@uni-heidelberg.de
 * @version 0.2
 * @since 0.2
 */

Nominatim = Class.create({
	/**
	 * Property: url
	 * {String} The URL of Nominatim
	 */
	url: null,
	
	/**
	 * Constructor
	 */
	initialize: function () {
//		this.url = 'http://nominatim.openstreetmap.org/search?format=json&polygon=0&addressdetails=1&viewbox=-31.303,71.869,50.455,34.09&bounded=0';
		this.url = 'http://nominatim.openstreetmap.org/search?format=json&polygon=0&addressdetails=1';
//		this.url = 'http://nominatim.openstreetmap.org/search?format=json&addressdetails=1';
	},
	
	/**
	 * Method: geocode
	 * Runs geocoding
	 * 
	 * Parameters:
	 * address - {String} The address to be geocoded
	 * callback - {Object} The callback function executed after a successful request
	 * failure - {Object} The callback function executed after a failed request
	 * 
	 * Returns:
	 * 
	 */
	geocode: function (address, callback, failure) {
		var requestUrl = this.url + '&q=' + address.replace(/\s+/g,'+');
		return this.httpRequest(requestUrl, 'GET', callback, failure);
	},
	
	/**
	 * Method: httpRequest
	 * 
	 * Parameters:
	 * method - {String} The HTTP Method for the request
	 * 
	 * Returns:
	 * {Ajax.Request} The request object
	 */	
	httpRequest: function (requestUrl, method, callback, failure) {
		if (requestUrl.startsWith('http://')) {
//			requestUrl = OpenLayers.ProxyHost + escape(requestUrl);
			requestUrl = OpenLayers.ProxyHost + encodeURIComponent(requestUrl);
		}
		
		return new Ajax.Request(requestUrl, {
			asynchronous: true,
    		method: method,
			onSuccess: callback,
			onFailure: failure
  		});
	},
	
	/**
	 * Method: parseGeocodeResponse
	 *
	 * Parameters:
	 * responseJSON - {Object} The geocoding response, encoded in JSON
	 */
	parseGeocodeResponse: function (responseJSON) {
		var geocodedPlaces = Array();
		
		for (var i = 0; i < responseJSON.length; i++) {
			geocodedPlaces.push(new Nominatim.Address(responseJSON[i]));
		}
		return geocodedPlaces;
	}
});


