/**
 * Rits Framework
 *
 * LICENSE
 * 
 * This source file is subject to the Rits Commercial license.
 * 
 * @copyright  2008 Rits Comunicação & Tecnologia. (http://www.rits.com.br)
 * @license    Rits Commercial License 1.0
 * @version    $Id:$
 */

/**
 * Map 
 *
 * @category   Rits
 * @package    Rits
 * @copyright  2008 Rits Comunicação & Tecnologia. (http://www.rits.com.br)
 * @license    Rits Commercial License 1.0
 */
Rits.Map = function(mapContent, mapInput) {
	if (GBrowserIsCompatible()) {
 			
  		var lat, lng;
  		
		this._input = $(mapInput);
		this._content = $(mapContent);
	 			
		this._map = new GMap2(this._content);
						 
		//lat = -5.794478;
		//lng = -35.210953;
		lat = 41.65649719441145;
		lng = -0.8768463134765625;		
		
		if(this._input.value) {
			var a = this._input.value.split(' ');
			if(a.length == 2) {
				lat = a[0];
				lng = a[1];
				var point =  new GLatLng(lat, lng);
				this._marker = new GMarker(point, {draggable: true});
			}
		}
		var obj = this;
		this._map.setCenter(new GLatLng(lat, lng), 13);
		this._map.addControl(new GLargeMapControl());
		this._map.addControl(new GMapTypeControl());
		GEvent.addListener(this._map, 'click', function(marker, clickedPoint) {
			
			if(!obj._marker) {
				obj._marker = new GMarker(clickedPoint, {draggable: true});
				obj._map.addOverlay(obj._marker);						
			} else {
				obj._marker.setPoint(clickedPoint);			
			}		
			obj._input.value = clickedPoint.lat()+' '+clickedPoint.lng();
		
		});
		
		if(this._marker) {
			this._map.addOverlay(this._marker);
		}
		
		this._geocoder = new GClientGeocoder();
	}
}

Rits.Map.prototype = {
		
	_map: null,
	_geocoder: null,
	_marker: null,
	
	_content: null,
	_input: null,
		
	/**
	 * Search for an address
	 *
	 * @param string field
	 */
	search: function(field) {
		var f = $(field);
		if(!f.value) {
			alert(Rits.Language.get('map.search.check'));
		}
		var address = f.value;
		var _map = this._map;
		if (this._geocoder) {
			this._geocoder.getLatLng(address,
				function(point) {
					if (!point) {
						alert(Rits.Language.get('map.search.notfound'));
					} else {
						_map.setCenter(point, 13);
					}
				}
       		);		
		}
	},
	
	/**
	 * Clear map markers
	 */	 
	clear: function() {
		this._input.value = '';
		this._marker = null;
		this._map.clearOverlays();		
	}
};

