BoatSurveySearch = {

	boat_marker:null,

	init:function(){

		this.map = new JSONMap
		(
			"#map",
			{
				controls: {
					zoom:'small',
					pan:true
				}
			}
		);

		// Create 'boat' icon
		this.map.AddIcon
		(
			'boat',
			"/images/map/icon_boat.png",
			26,
			26,
			"/images/map/icon_shadow_small.png",
			39,
			26,
			17,
			34,
			17,
			1,
			[3,0,29,0,29,26,3,26]
		);

		// Create 'boat' icon
		this.map.AddIcon
		(
			'surveyor',
			"/images/map/icon_surveyor.png",
			35,
			35,
			"/images/map/icon_shadow.png",
			52,
			35,
			17,
			34,
			17,
			1,
			[3,0,31,0,31,35,3,35]
		);


//		var cookie = new Cookie();
//		var lat_lon = cookie.Read( 'boat_location' );


/*
		var lat_lon = Cookie.Read( 'boat_location' );
		if( lat_lon ){
			var lat_lon = lat_lon.split( '|' );
			var latitude = parseFloat( lat_lon[0] );
			var longitude = parseFloat( lat_lon[1] );
			this.SetBoatMarker( latitude, longitude );
			this.SetCountryFromLatLng( latitude, longitude );
		} else {
			var country = jQuery( '#form_country' ).val();
			if( !country ){
				this.SetSummary( 'Click on the map or choose from the country list above to indicate the location of your boat.' );
				// Bind click event
				this.map.Bind
				(
					'click',
					Utilities.Bind(
						this.UpdateBoatLocation,
						this
					)
				);
			}
			this.UpdateFromCountry();
		}

*/
		var country = jQuery( '#form_country' ).val();
		var lat_lon = Cookie.Read( 'boat_location' );
		if( lat_lon ){
			var lat_lon = lat_lon.split( '|' );
			var latitude = parseFloat( lat_lon[0] );
			var longitude = parseFloat( lat_lon[1] );
			this.SetBoatMarker( latitude, longitude );
			this.SetCountryFromLatLng( latitude, longitude );
		} else if( country ){
			this.GetBoatLocationFromForm();
		} else {
			this.SetSummary( 'Click on the map or choose from the country list above<br/>to indicate the location of your boat.' );
			// Bind click event
			this.map.Bind
			(
				'click',
				Utilities.Bind(
					this.UpdateBoatLocation,
					this
				)
			);
		}



	},

	SetSummary:function( summary ){
		jQuery( '#summary' ).html( summary );
	},

	SetBoatMarker:function( latitude, longitude ){
		if( this.boat_marker ){
			this.map.MoveMarker( this.boat_marker, latitude, longitude );
		} else {
			this.boat_marker = this.map.AddMarker
			(
				latitude,
				longitude,
				{
					icon:'boat',
					draggable:true,
					group:'boat',
					zIndex:10000,
					events:{
						dragend:Utilities.Bind(
							function( marker ){
								this.SetCountryFromLatLng( marker.lat(), marker.lng() );
							},
							this
						)
					}
				}
			);

			// Create 'centre on my boat' button
			var centre_boat_button = Utilities.Create
			(
				'img',
				{
					src:'/images/map/center_on_boat.png',
					title:'Click to centre the map on your boat'
				}
			)[0];
			var centre_boat_button_control = this.map.CreateControl
			(
				centre_boat_button
			);
			this.map.AddControl
			(
				centre_boat_button_control,
				{
					position:'top_right',
					h:7,
					v:7
				}
			);
			this.map.BindElementEvent
			(
				centre_boat_button,
				'click',
				Utilities.Bind(
					function(){
						var lat_lon = this.boat_marker.getLatLng();
						this.map.SetCenter( lat_lon.lat(), lat_lon.lng() );
					},
					this
				)
			);

			// Create 'show all results' button
			var show_all_button = Utilities.Create
			(
				'img',
				{
					src:'/images/map/show_all_results.png',
					title:'Click to show all results'
				}
			)[0];
			var show_all_button_control = this.map.CreateControl
			(
				show_all_button
			);

			this.map.AddControl
			(
				show_all_button_control,
				{
					position:'top_right',
					h:7,
					v:30
				}
			);
			this.map.BindElementEvent
			(
				show_all_button,
				'click',
				Utilities.Bind(
					function(){
						this.map.ZoomExtents();
					},
					this
				)
			);
		}
		this.SetSummary( 'Drag the boat icon to refine the location of your boat.' );
	},

	/**
	 * Use adddress data to find latitude and longitude for boat
	 */
	GetBoatLocationFromForm:function(){
		var address_all = [];

		var address = jQuery( 'input[name=address]' ).val();
		if( address ){
			address_all.push( address );
		}

		var postcode = jQuery( 'input[name=postcode]' ).val();
		if( postcode ){
			address_all.push( postcode );
		}

		var country = jQuery( '#form_country' ).val();

		if( country ){

			if( country == "MT" ){
			    address_all.push( "Malta" );
			} else {
				address_all.push( country );
			}

		} else {
			alert( 'You must choose a country.' );
			return false;
		}

		this.map.AddressToLatLng
		(
			address_all.join( ', ' ),
			Utilities.Bind(
				function( latitude, longitude ){
					if( latitude !== null && longitude !== null ){
						this.SetBoatMarker( latitude, longitude );
						this.map.ClearMarkers( 'results' );
						jQuery( '#form_country' ).val( country );
						this.Search( country );
					} else {
						alert( 'ERROR: The system was unable to locate the address given.\r\n\r\nPlease verify address details.' );
					}
				},
				this
			)
		);
		
		return false;
	},

	UpdateBoatLocation:function( target, event_properties ){
		if( !this.boat_marker ){
			this.SetBoatMarker( event_properties.lat(), event_properties.lng() );
			this.SetCountryFromLatLng( event_properties.lat(), event_properties.lng() );
		}
	},


	SetCountryFromLatLng:function( latitude, longitude ){
		this.map.LatLngToAddress
		(
			latitude,
			longitude,
			Utilities.Bind(
				function( result ){
					if( result.Placemark ){
						var country = result.Placemark.pop().AddressDetails.Country.CountryNameCode;
						this.map.ClearMarkers( 'results' );
						this.current_country = country;
						jQuery( '#form_country' ).val( country );
						this.Search( country );
					} else {
						alert( 'Please place your boat in a country.' );
					}
				},
				this
			)
		);
	},

	UpdateFromCountry:function(){
		var country = jQuery( '#form_country' ).val();

		this.current_country = country;
		country_text = jQuery( '#form_country' ).find( 'option[value=' + country +']' ).text().split( ',' )[ 0 ].split( '(' )[ 0 ];

		if( country ){
			// Place boat icon
			this.map.AddressToLatLng
			(
				country_text,
				Utilities.Bind(
					function( latitude, longitude, name ){
						if( latitude !== null && longitude !== null ){
							this.map.ClearMarkers( 'results' );
							this.SetBoatMarker( latitude, longitude );
							this.Search( country );
						} else {
							alert( 'Unable to locate ' + name + '. Please place the boat icon on the location of your boat.' );
						}
					},
					this
				)
			);
		}
	},

	ManualSearch:function(){
		var country = jQuery( '#form_country' ).val();
		if( country ){
			this.map.ClearMarkers( 'results' );
			this.Search( country );
		} else {
			alert( 'You must place your boat on the map first.' );
		}
		
		return false;
	},

	Search:function( country ){

		this.map.ShowLoading();

		var lat_lon = this.boat_marker.getLatLng();

		Cookie.Create( 'boat_location', lat_lon.lat() +'|' + lat_lon.lng(), 30 );
		var search_values = { lat:lat_lon.lat(), lon:lat_lon.lng() };

		if( country ){
			search_values.country = country;
		}

		var craft = jQuery( 'select[name=craft]' ).val();
		if( craft ){
			search_values.craft = craft;
		}
		var material = jQuery( 'select[name=material]' ).val();
		if( material ){
			search_values.material = material;
		}
		var type = jQuery( 'select[name=type]' ).val();
		if( type ){
			search_values.type = type;
		}
		var hull = jQuery( 'select[name=hull]' ).val();
		if( hull ){
			search_values.hull = hull;
		}
		var keywords = jQuery( 'input[name=keywords]' ).val();
		if( keywords ){
			search_values.keywords = keywords;
		}
		search_values.range = jQuery( 'select[name=range]' ).val();

		// Load data
		this.map.LoadData
		(
			'/search/data_json',
			search_values,
			{
				callback:Utilities.Bind
				(
					function( results ){
						this.SetSearchResults( results );
						this.map.ZoomExtents();
						this.map.HideLoading();

					},
					this
				)
			}
		);

	},

	SetSearchResults:function( results ){
		this.results = results;
		this.UpdateSearchResults()
	},

	/**
	 * Callback for showing search results on the map and in the list
	 */
	UpdateSearchResults:function(){

		var results = this.results;

		var range = jQuery( 'select[name=range]' ).val();
		var lat_lon = this.boat_marker.getLatLng();
		var boat_latitude = lat_lon.lat();
		var boat_longitude = lat_lon.lng();

		this.map.AddOverlay
		(
			'range_circle',
			this.map.CreateCircle
			(
				boat_latitude,
				boat_longitude,
				range * 1.609344,
				40,
				'#000000',
				5,
				0.2
			)
		);

		var results_html = '';

		if( results.local.count > 0 ){

// 			results_html += '<div style="border-bottom:1px solid #ccc;"><b>Surveyors based in this country (' + results.local.count + '):</b></div>';
			results_html += '<h2 style="border-bottom:1px solid #ccc;">Surveyors based nearby (' + results.local.count + '):</h2>';

			var lat_lon = this.boat_marker.getLatLng();
			var boat_latitude = lat_lon.lat();
			var boat_longitude = lat_lon.lng();

			for( var i = 0; i < results.local.items.length; i++ ){
				var result = results.local.items[ i ];
				results.local.items[ i ].distance = this.map.GetLatLngDistance( boat_latitude, boat_longitude, result.latitude, result.longitude, 'M' );
			}

			results.local.items = results.local.items.sort(function(a,b){return a.distance-b.distance;});

			for( var i = 0; i < results.local.items.length; i++ ){

				var result = results.local.items[ i ];
				var properties = result.properties;
				if( !properties ){
					properties = {};
				}
				properties.group = 'results';
				properties.icon = 'surveyor';

				var marker = this.map.AddMarker
				(
					result.latitude,
					result.longitude,
					properties
				);

				if( result.logo ){
					var logo = '<img src="/images/members/' + result.logo + '" width="150" align="left"/>';
				} else {
					var logo = '';
				}

				result_html = Utilities.Replace
				(
					[
						'[[id]]',
						'[[company_name]]',
						'[[clean_name]]',
						'[[location]]',
						'[[description]]',
						'[[distance]]'
					],
					[
						result.id,
						result.name,
						result.clean_name,
						result.location,
						result.description.truncate( 200 ),
						result.distance.toFixed(1)
					],
					'<h3><a title="Click for Full Details" href="/member/view/[[id]]/[[clean_name]]">[[company_name]]</a></h3><p class="location">[[location]] ([[distance]] miles)</p><p>[[description]]</p>'
				);

				this.map.AddPopupToMarker
				(
					marker,
					result_html,
					{
						maxWidth:300
					}
				);

				results_html += result_html;
			}

		} else {
			// No results so just zoom to target country
			var boat_pos = this.boat_marker.getLatLng();
			this.map.ZoomToCountryFromLatLng( boat_pos.lat(), boat_pos.lng() );
		}

		if( results.global.count > 0 ){

// 			results_html += '<div style="border-bottom:1px solid #ccc;"><b>Surveyors who operate in this country (' + results.global.count + '):</b></div>';
			results_html += '<h2 style="border-bottom:1px solid #ccc;">Surveyors who operate in this country (' + results.global.count + '):</h2>';

			for( var i = 0; i < results.global.items.length; i++ ){

				var result = results.global.items[ i ];

				result_html = Utilities.Replace
				(
					[
						'[[id]]',
						'[[company_name]]',
						'[[clean_name]]',
						'[[location]]',
						'[[description]]'
					],
					[
						result.id,
						result.name,
						result.clean_name,
						result.location,
						result.description.truncate( 200 )
					],
					'<h3><a title="Click for Full Details" href="/member/view/[[id]]/[[clean_name]]">[[company_name]]</a></h3><p class="location">[[location]]</p><p>[[description]]</p>'
				);

				results_html += result_html;
			}
		}

		jQuery( '#results_list' ).html( results_html );
		jQuery( '#results_header' ).html( 'There were ' + ( results.local.count + results.global.count ) + ' surveyors matching your criteria:' );

	},

	ShowAll:function(){
		this.map.ZoomExtents();
	}
}

