nxc = window.nxc || {};
nxc.GeoSearch = function( map ) {

	this.map           = map;
	this.searchMarkers = new Array();
	this.infowindow    = new google.maps.InfoWindow();
	this.geocoder      = new google.maps.Geocoder();
	this.wrapper       = jQuery( '<div/>', {
		'class': 'nxc-geosearch-wrapper'
	} );

	var container = jQuery( '<div/>', {
		'class': 'nxc-geosearch-container'
	} ).appendTo( this.wrapper );
	jQuery( '<input/>', {
		'type' : 'text',
		'name' : 'search_adress',
		'value': '',
		'class': 'nxc-geosearch-adress'
	} ).appendTo( container );
	jQuery( '<input/>', {
		'type' : 'button',
		'name' : 'search_button',
		'value': 'Search',
		'class': 'nxc-geosearch-search-button'
	} ).appendTo( container );

	var searchHandler = function() {

	};
	jQuery( '.nxc-geosearch-search-button', this.wrapper ).click( jQuery.proxy( this.search, this ) );

	return this.wrapper[0];
}

nxc.GeoSearch.prototype.search = function() {
	jQuery.each( this.searchMarkers, function( index, marker ) {
		marker.setMap( null );
	} );
	delete this.searchMarkers;
	this.searchMarkers = new Array();

	var context = this;
	this.geocoder.geocode(
		{
			'address': jQuery( '.nxc-geosearch-adress', this.wrapper ).val()
		},
		function( results, status ) {
			if( status == google.maps.GeocoderStatus.OK ) {
				context.map.setCenter( results[0].geometry.location );
				jQuery.each( results, function( index, result ) {
					var marker = new google.maps.Marker( {
						map: context.map,
						position: result.geometry.location
					} );
					context.searchMarkers.push( marker );
					google.maps.event.addListener( marker, 'click', function( event ) {
						context.infowindow.setContent( result.formatted_address );
						context.infowindow.open( context.map, marker );
					} );
				} );
			} else {
				alert( 'Geocode was not successful for the following reason: ' + status );
			}
		}
	);
}
