var keystroke_timeout = null;
var search_delay = 300;

$(document).ready(function()
{
	//Get clients location by IP to center the map
	$.get('/services/get-country-from-ip-address',{},function(country)
	{
		var client_country_longitude 	= $('longitude',country).text();
		var client_country_latitude 	= $('latitude',country).text();
		var set_zoom_as 				= ($('name',country).text() == 'New Zealand') ? 6 : 4;
		
		//Show YES members on a map
		$.get('/services/geocoded-contacts-data',{},function(response)
		{
			$('#map').removeClass('loading');
			
			var map = new GMap2(document.getElementById("map"));
			
			map.addControl(new GSmallMapControl());
			map.addControl(new GMapTypeControl());
			map.setCenter(new GLatLng(client_country_latitude, client_country_longitude), set_zoom_as);	
			
			function wheel_zoom(a) 
			{ 
				(a.detail || -a.wheelDelta) < 0 ? map.zoomIn() : map.zoomOut(); 
			}
			
			map.enableContinuousZoom();
			map.enableDoubleClickZoom();
			
			GEvent.addDomListener(document.getElementById("map"), "DOMMouseScroll", wheel_zoom);
	 		GEvent.addDomListener(document.getElementById("map"), "mousewheel", wheel_zoom);
	 				
			$('contact',response).each(function(){
				var point 		= new GLatLng($('latitude',this).text(),$('longitude',this).text());
				var marker 		= new GMarker(point);
				var company 	= $('company',this).text();
				var contact_id 	= $('id',this).text();
				var profile_icon_src 	= $('profile_icon_src',this).text();
				var company_summary 	= $('company_summary',this).text();
				
				GEvent.addListener(marker, "click", function() {
					marker.openInfoWindowHtml('<h3><a href="/member-profile/'+contact_id+'">'+company+'</a></h3><img src="'+profile_icon_src+'" /><p style="width: 250px;">'+company_summary+'</p>');
					select_contact(company);
				});
				
				map.addOverlay(marker);
			});
		});
	});
	
	function select_contact(company)
	{
		$('#search').val(company);
		search_for_member();
	}
	
	$('#search').bind('click',function(){
		if(this.value == 'Search by company...')
			this.value = '';
	});
	
	$('#search').bind('keyup',function(){
		if(keystroke_timeout)
			clearTimeout(keystroke_timeout);
		
		keystroke_timeout = setTimeout(search_for_member,search_delay);	
	});
	
	function search_for_member()
	{
		search_input = $('#search').get(0);
		
		if(search_input.value.length <= 2 && search_input.value.length)
			return;
	
		escaped_search_string = escape($.trim(search_input.value));
		$('#search').addClass('loading');
		
		$.get('/services/search-members?q=' + escaped_search_string,function(response){
			search_results = $('html',response).text();
			$('#members').html(search_results);
			$('#search').removeClass('loading');
		});	
	}
});