var map;
var current_control = 'map_controls_zoom_container';
var map_markers = new Array();
var map_locations = new Array();
var legend_showing = false;
var location_id;
var area_id;
var zoom_val;
var local_bounds;
var global_bounds;
var zoomer_slider;

var min_zoom = 9;
var max_zoom = 15;

function map_load( location_id, area_id ) {

	if ( GBrowserIsCompatible() ) {

		map = new GMap2( $("map") ); //initialise map
		map.getPane( G_MAP_FLOAT_SHADOW_PANE ).style.visibility = "hidden"; //hide shadows 
		map.addControl( new dummy_controller() ); //add dummy controller, see comment below for details
		var overviewMapControl =  new GOverviewMapControl();
		map.addControl( overviewMapControl ); //overview control in bottom right corner
		map.setCenter(new GLatLng( 0,0 ), 10 ); //arbitrary init, changed later, 10 == zoom level
		
		//set up boundaries
		global_bounds = new GLatLngBounds();
		local_bounds = new Array();
		for( var i=1; i<=9; i++ ) local_bounds[i] = new GLatLngBounds();
		
		//initialise markers
		for( ml in map_locations ) {

			if( !ml.match( /^[0-9]+$/ ) ) continue;
		
			map_markers[ml] = create_marker( map_locations[ml].get_point(), ml, map_locations[ml].get_type() );
			map.addOverlay( map_markers[ml] );			
		
			//add to global and local bounds
			global_bounds.extend( map_locations[ml].get_point() );
			local_bounds[ map_locations[ml].get_area_id() ].extend( map_locations[ml].get_point() );
		
		} //end for

		//which bounds are in use?
		//var bounds = area_id == 0 ? global_bounds : local_bounds[ area_id ];
		var bounds = area_id == 0 ? local_bounds[ 2 ] : local_bounds[ area_id ]; //if nothing default to london
		
		//work out zoom value to fit all markers for this area (or global) in
		zoom_val = get_zoom_level( map.getBoundsZoomLevel( bounds ) );

		//zoom slider
		zoomer_slider = new Control.Slider( 'slider_handle', 'slider_track', {
			range: $R( min_zoom, max_zoom + 0.2),
			//values: [6,7,8,9,10,11,12,13,14,15],
			values: [9,10,11,12,13,14,15],
			sliderValue: zoom_val,
			onChange: function(val) {
				if( val >= min_zoom && val <= max_zoom && val != zoom_val ) update_zoom( val, false );
			}
		} );
		
		if( is_opera ) zoomer_slider.setValue( zoom_val ); //fix opera bug
		
		//set center and zoom based on bounds
		map.setCenter( bounds.getCenter(), zoom_val )
	
		if( location_id > 0 ) center_on_location( location_id );
	
	} //end if

} //end function

//create icons
var icons = new Array();
var baseIcon = new GIcon();
baseIcon.iconSize = new GSize(30, 30);
baseIcon.iconAnchor = new GPoint(14, 29);
baseIcon.infoWindowAnchor = new GPoint(12, 18);
for( var i=1; i<=8; i++ ) icons[i] = new GIcon( baseIcon, "images/map_icons/" + i + ".png" );

/* fake controller to help stop the info window displaying under the custom controls */
function dummy_controller() {};
dummy_controller.prototype = new GControl();
dummy_controller.prototype.printable = function() { return false; }
dummy_controller.prototype.selectable = function() { return false; }
dummy_controller.prototype.initialize = function(m) { var dummy = document.createElement('span'); dummy.style.width='180px'; dummy.style.height='40px'; dummy.appendChild( document.createTextNode(' ') ); m.getContainer().appendChild( dummy ); return dummy; }
dummy_controller.prototype.getDefaultPosition = function() { return new GControlPosition( G_ANCHOR_TOP_RIGHT, new GSize( 20, 30 ) ) }

function create_marker( point, id, type ) {

	var marker = new GMarker( point, icons[ type ] );

	GEvent.addListener( marker, "click", function() { center_on_location( id );	});
	GEvent.addListener( marker,"mouseover", function() { show_tooltip( id ); });        
    GEvent.addListener( marker,"mouseout", function() { hide_tooltip() }); 

	return marker;

} //end function

function get_zoom_level( val ) {

	if( val < min_zoom ) return min_zoom;
	if( val > max_zoom ) return max_zoom;

	return val;

} //end if

function set_map_type( type ) {

	switch( type ) {
		case 'hybrid' : map.setMapType( G_HYBRID_MAP ); break;
		case 'satellite' : map.setMapType( G_SATELLITE_MAP ); break;
		default : map.setMapType( G_NORMAL_MAP ); break;
	} //end switch

} //end function

function center_on_area( id ) {

	//which bounds are in use?
	var bounds = id > 0 ? local_bounds[ id ] : global_bounds;
	
	//work out zoom value to fit all markers for this area (or global) in
	zoom_val = get_zoom_level( map.getBoundsZoomLevel( bounds ) );

	setTimeout( "zoomer_slider.setValue(" + zoom_val + ")", 100 );
	
	//set center and zoom based on bounds
	var clat = ( bounds.getNorthEast().lat() + bounds.getSouthWest().lat() ) / 2;
	var clng = ( bounds.getNorthEast().lng() + bounds.getSouthWest().lng() ) / 2;
	map.setCenter( bounds.getCenter(), zoom_val )

} //end function

function show_tooltip( id ) {

	$('using_the_map').style.visibility = 'hidden';
	$('map_tooltip').style.visibility = 'visible';
	$('map_tooltip').innerHTML = map_locations[id].get_title() + ': Click the icon for more information';

} //end function

function hide_tooltip() {

	$('using_the_map').style.visibility = 'visible';
	$('map_tooltip').style.visibility = 'hidden';

} //end function

function center_on_location( id ) {

	var new_coords = map_locations[id].get_point();
	var adj_coords = new GLatLng( map_locations[id].get_lat()+.09, map_locations[id].get_lon()+.03 );
	//var adj_coords = new_coords;

	//center and adjust zoom
	map.panTo( adj_coords );
	//map.setZoom( 10 );

	//show popup
	var details;
	new Ajax.Request(
					 
		'property_details',
		
		{
			method: 'get',
			parameters: 'id=' + id,
			onComplete: function(t) {
				
				details = t.responseText;
			
				//map_markers[id].openInfoWindowHtml( details, { maxWidth: 270 } );
				map_markers[id].openInfoWindowHtml( details );
				
				map_markers[id].setPoint( new_coords );
				
			} //end function
			
		} //end var
		
	); //end Ajax.Request

} //end function

function update_zoom( val, update_slider ) {

	if( val < min_zoom || val > max_zoom || val == zoom_val ) return;

	map.setZoom( val );
	
	//update the slider
	if( update_slider ) zoomer_slider.setValue( val );

	zoom_val = val;

} //end function

function show_details( id ) {

	open_popup( 'property_details?id=' + id, 640, 467 );

} //end function

function select_control( type ) {
	
	if( current_control == type ) return;

	if( type == 'map_controls_legend' ) toggle_legend('ru','rd');

	$(type).style.display = 'block';

	//fade in if using a decent browser
	if( !is_ie ) {
		set_opacity( $(type), 0 );
		new Effect.Opacity( type, { duration: 0.5, from: 0, to: 1 } );
		new Effect.Opacity( current_control, { duration: 0.5, from: 1, to: 0 } );
		setTimeout( "$('" + current_control +"').style.display = 'none';", 500 );
	} else {
		$(current_control).style.display = 'none';
	} //end if

	current_control = type;

} //end function

function toggle_legend( from, to ) {

	if( $('map_controls_legend_' + to).style.display == 'block' ) return;
	
	$('map_controls_legend_' + to).style.display = 'block';

	//fade in if using a decent browser
	if( !is_ie ) {
		set_opacity( $('map_controls_legend_' + to), 0 );
		new Effect.Opacity( 'map_controls_legend_' + to, { duration: 0.5, from: 0, to: 1 } );
		new Effect.Opacity( 'map_controls_legend_' + from, { duration: 0.5, from: 1, to: 0 } );
		setTimeout( "$('map_controls_legend_" + from + "').style.display = 'none';", 500 );
		setTimeout( "$('map_controls_legend').style.height = 'auto';", 500 );
	} else {
		$('map_controls_legend_' + from).style.display = 'none';
	} //end if

} //end function