// Holds the Hotel objects currently displayed on the map
var hotels=[];

// holds the Google map API
var map=null;

// Holds the results
var accordion=new com.lastminute.labs.Accordion();

/**
 * Initializes the components needed for the page.
 */
function radar_init()
{
	var result=null;

	// Now we have the map, init gears
	try
	{
		result=com.lastminute.labs.gears.init();
	}
	catch (e)
	{
		debug(e);
	}
	
	// Deal with the result
	if (com.lastminute.labs.gears.RESULT_OK==result)
	{
		// Initialize some of the messages
		radar_popup_manager.create_popup(translations['initial_message']);	
		
		// Just show the map section
		reveal_map();
		
		// Hide the default error
		$('gears_misc_error').style.display='none';
	}
	else
	if (com.lastminute.labs.gears.RESULT_GEARS_NOT_INSTALLED==result)
	{
		// Initialize some of the messages
		radar_popup_manager.create_popup(translations['initial_message_no_gears']);	

		// Point them to the gears install page
		$('gears_not_installed_content').style.display='block';

		// Show the map as well
		reveal_map();
		
		// Hide the gears specific links
		$('get_hotels_near_me_link').style.visibility='hidden';
		
		// Hide the default error
		$('gears_misc_error').style.display='none';
	}
}

function reveal_map()
{
	// Create the map and set it to the last known position
	map=new GMap2(document.getElementById("radar_map"));
	map.setCenter(starting_point || new GLatLng(51.5,-0.117), 12); // Init to starting point or default to London

	// Add some controls to the map
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	
	// Show the map
	$('gears_ok_content').style.visibility='visible';
}

function update_map(position)
{
	// We are now getting hotels . . .
	radar_popup_manager.create_popup(translations['hotels_message']);

	get_hotels(position);
	
	if (position.from_text)
		$('radar_accuracy').style.display='none';
	else
	{
		// Use the correct icon
		var p = position.accuracy
		if (p >= 150000)
			$('radar_accuracy').innerHTML = "<span>"+translations['precision_1']+"</span><img src='http://cdn.lastminute.com/site/radar_fix_quality_1.png' alt='' />";
		else if (p < 150000 && p >= 5000)
			$('radar_accuracy').innerHTML = "<span>"+translations['precision_2']+"</span><img src='http://cdn.lastminute.com/site/radar_fix_quality_2.png' alt='' />";
		else if (p < 5000 && p >= 500)
			$('radar_accuracy').innerHTML = "<span>"+translations['precision_3']+"</span><img src='http://cdn.lastminute.com/site/radar_fix_quality_3.png' alt='' />";
		else if (p < 500 && p >= 50)
			$('radar_accuracy').innerHTML = "<span>"+translations['precision_4']+"</span><img src='http://cdn.lastminute.com/site/radar_fix_quality_4.png' alt='' />";
		else if (p < 50)
			$('radar_accuracy').innerHTML = "<span>"+translations['precision_5']+"</span><img src='http://cdn.lastminute.com/site/radar_fix_quality_5.png' alt='' />";
		
		// And display it
		$('radar_accuracy').style.display='block';			
	}	
}

function reverse_geocode()
{
	var location=$('location');
	if (location && location.value!='')
		com.lastminute.labs.gears.get_location_from_string(location.value, update_map, handle_error);
}

function find_location()
{
	radar_popup_manager.create_popup(translations['locating_message']);
	com.lastminute.labs.gears.get_location(update_map, handle_error);
} 

var form_location='';
function find_location_from_form()
{
	var location_input=$('location');
	if (!location_input) return;
	form_location=location_input.value;
	if (form_location.length>0)
	{
		radar_popup_manager.create_popup(translations['locating_message']);
		com.lastminute.labs.gears.get_location_from_string(form_location, update_map, handle_error_from_form);
	}
}

function handle_error(error)
{
	var s=com.lastminute.labs.gears.initialised?translations['location_error']:translations['location_error_no_gears'];
	radar_popup_manager.create_popup(s);
}

function handle_error_from_form(error)
{
	var s=com.lastminute.labs.gears.initialised?translations['geocode_error']:translations['geocode_error_no_gears'];
	s=s.replace('%LOCATION%', form_location);
	radar_popup_manager.create_popup(s);
}

function debug(message)
{
  try { console.log(message); } catch (e) { }
}

function get_hotels(position)
{
	// Mark the hotels things
	accordion.setResultHTML('hotel_results','<div class="result"><img src="http://cdn.lastminute.com/site/radar_loader.gif?skin=engb.lastminute.com" alt="" />'+translations['please_wait']+'</div>');
	
	// Remove the current hotels from the map
	map.clearOverlays();
	
	// Reset the hotels array
	hotels=new Array();
	
	// Get the date that we want a price point for
	var date=new Date();
	date.setMonth(date.getMonth()+1)+1;
	day=date.getDate();
	month=date.getMonth();
	year=date.getFullYear();

	// Create the url
	var url=translations['hotel_feed_url'];
	url=url.replace('%DAY%', day).replace('%MONTH%', month).replace('%LAT%', position.latitude).replace('%LNG%', position.longitude);
	
	// Request the hotel information
	new Ajax.Request(
		url,
		{
			method: 'get',
			onFailure:function(transport)
			{
				accordion.setResultHTML('hotel_results','<div class="result">'+translations['generic_error']+'</div>');				
				if (position)
					map.setCenter(new GLatLng(position.latitude, position.longitude), 12);
				radar_popup_manager.create_popup(translations['no_results_error']);
			},
			onSuccess:function(transport)
			{
				// Clear the loading message
				radar_popup_manager.remove_popup();
				
				// Remove the last list of hotel results
				accordion.clearResult('hotel_results');
				
				// Start the map with the found position
				var pos=new GLatLng(position.latitude, position.longitude);
				var latLngBounds=new GLatLngBounds(pos, pos);
			
				// Get the xml from the response
				var hotelsFromXml=transport.responseXML.getElementsByTagName('item');
			
				// Get the number of hotels
				var letterCode="a".charCodeAt(0);
				var lim=hotelsFromXml.length;
				var tempHotels=[];
				
				// Get all the hotels and put them into a temp array - remember not to include secret ones!
				for (var n=0;n<lim;++n)
				{
					var hotel=new com.lastminute.labs.radar.Hotel(hotelsFromXml[n]);
					if ('True'==hotel.topsecret) continue;
					
					hotel.distancefromlocation=(new GLatLng(hotel.latitude, hotel.longitude)).distanceFrom(pos);
					
					tempHotels.push(hotel);
				}
				
				// Sort by distance
				tempHotels.sort(function(a,b) { return a.distancefromlocation<b.distancefromlocation?-1:1 } );
				
				// Try to add up to 5 of them to the map
				lim=Math.min(5, tempHotels.length);
				for (var n=0;n<lim;++n)
				{					
					hotel=tempHotels[n];
					hotel.url+='&intcmp=labs.radar.hotels.engb';
					hotels.push(hotel);
					
					latLngBounds.extend(new GLatLng(hotel.latitude, hotel.longitude));
			
					hotel.createIcons(String.fromCharCode(letterCode));
					hotel.point=new GLatLng(hotel.latitude, hotel.longitude);
					hotel.marker=new GMarker(hotel.point, { title: hotel.title, icon:hotel.icon } );
					map.addOverlay(hotel.marker);
					addInfoWindow(hotel.marker, createInfoWindowHTML(hotel));
					
					accordion.addResultHTML('hotel_results', createHotelResultHTML(hotel));

					if (hotels.length>5) break;
					letterCode++;
				}

				// Did we get any valid hotels?
				if (hotels.length>0)
				{
					// Zoom correctly to fit on you and all the hotels
					var zoom=map.getBoundsZoomLevel(latLngBounds);
					map.setCenter(latLngBounds.getCenter(), zoom);
				}
				else
				{
					// Display an error message
					$('error_message').innerHTML='Sorry, no results were found for this location.';
					$('error_message').style.display='block';
					
					// Put the map in the right place anyway
					map.setCenter(latLngBounds.getCenter(), 14);	
				}
				
				// Add the 'more results' link to the hotels accordion
				var l=translations['more_results_link'];
				l=l.replace('%DAY%', day).replace('%MONTH%', month).replace('%LAT%', position.latitude).replace('%LNG%', position.longitude);
				accordion.addResultHTML('hotel_results', '<div class="more">'+l+'</div>');
			}
		}
	);
}

function addInfoWindow(marker, html)
{
	GEvent.addListener(marker, "click", function()
	{
		marker.openInfoWindowHtml(html);
		accordion.openResults('hotel_results');
	} );
}

function highlightOnMap(hotelIndex)
{
	var hotel=hotels[hotelIndex];
	GEvent.trigger(hotel.marker, 'click');
}


/**
 * Creates the HTML to go in an info window for a specified hotel object
 */
function createInfoWindowHTML(hotel)
{
	return  "<div class='radar_hotel_popup' style='width:400px; height:140px; overflow: hidden;'>" +
				"<h3>"+hotel.corehotelname+"</h3>" +
				"<img src='"+hotel.imageurl+"' />" +
				"<p>"+hotel.shortdescription.substring(0,200)+"...</p>" +
				"<a class='radar_hotel_link' target='_blank' href='"+hotel.url+"'>"+translations['more_details']+"</a>" +
			"</div>";
}

function createHotelResultHTML(hotel)
{
	return  '<div class="result">' +
				'<img class="result_thumb" src="'+hotel.thumbIcon+'" />' +
				'<a href="'+hotel.url+'">'+hotel.corehotelname+'</a>' +
				'<a href="#" class="radar_show_on_map_link" onclick="highlightOnMap('+hotels.indexOf(hotel)+'); return false;">'+translations['see_on_map']+'</a>'
			'</div>';
}




var radar_popup_manager=
{
	popup_holder:null,
	
	popup_box:null,

	create_popup:function(content)
	{
		if (null==this.popup_holder)
			this.popup_holder=$('radar_popup_holder')
		
		// Remove the old popup
		this.remove_popup();
			
		// Create a new popup
		this.popup_box=document.createElement('div');
		this.popup_box.innerHTML=content;
		this.popup_box.className='popup_message';
		
		// Add it to the holder
		this.popup_holder.appendChild(this.popup_box);
	},
	
	remove_popup:function()
	{
		if (null==this.popup_holder)
			this.popup_holder=$('radar_popup_holder')
	
		// Remove the old popup
		if (null!=this.popup_box)
			if (-1!==Element.childElements(this.popup_holder).indexOf(this.popup_box))
				this.popup_holder.removeChild(this.popup_box);
	}
};
