var g_map;
var g_clickTimeOut;
var g_directions;
var g_directionID;

// mData indicies			(sync with placeLib)
var IX_LONG			= 0;
var IX_LAT			= 1;
var IX_DESC 		= 2;
var IX_TYPE			= 3;
var IX_IMAGE		= 4;
var IX_WIDTH		= 5;
var IX_HEIGHT		= 6;
var IX_CAPTION		= 7;
var IX_CAPTION_SITE	= 8;
var IX_ID			= 9;

var TIMEOUT			= 500;

// sync with placeLib
var MARKER_SUMMARY	= 0;	
var URL_PLACE		= '/places/place.php?place=';

// image dimension enhancements (sync with placeLib)
var IMAGE_WIDTH_INC	= 40;
var IMAGE_HEIGHT_INC= 80;

function mapInitialize( id, aMarker, aIconType, markerDir, directionID ) {
	g_map = new google.maps.Map2( document.getElementById( id ) );
	g_map.setCenter( new google.maps.LatLng(0,0), 2 );	// g_map needs a center, else not happy
	g_map.addMapType( G_PHYSICAL_MAP );		// not a default
    g_map.addMapType( G_SATELLITE_3D_MAP );
	g_map.setMapType( G_HYBRID_MAP );
	
	//g_map.addControl( new google.maps.MapTypeControl() );
    g_map.addControl( new google.maps.MenuMapTypeControl() );
	g_map.addControl( new google.maps.LargeMapControl() );
	//g_map.addControl( new google.maps.OverviewMapControl() );
	
	var bounds = new google.maps.LatLngBounds();
	_addWayPoints( aMarker, aIconType, markerDir, bounds );
	//
	// trying to get markers away from top and away from LHS
	bounds.extend( new google.maps.LatLng( bounds.getNorthEast().lat() + ( .15 * bounds.toSpan().lat()), bounds.getNorthEast().lng() ));
	bounds.extend( new google.maps.LatLng( bounds.getSouthWest().lat(), bounds.getSouthWest().lng()  - ( .08 * bounds.toSpan().lng()) ));
	g_map.setCenter( bounds.getCenter(), Math.min( g_map.getBoundsZoomLevel( bounds ), 18 ) ); 
	
	g_directions		= new google.maps.Directions( g_map, document.getElementById( directionID ));
	google.maps.Event.addListener( g_directions, "error", mapDirectionsHandleError );
	google.maps.Event.addListener( g_directions, "load", mapDirectionsHandleAfterLoad );		
	
}

function _addWayPoints( aMarker, aIconType, markerDir, bounds ){
	if( aMarker.length ) {
		for (n=1 ; n <= aMarker.length ; n++ ) {
			var mData = aMarker[ n-1 ].split( ';' );
			var point = new google.maps.LatLng( parseFloat( mData[ IX_LONG ] ), parseFloat( mData[ IX_LAT ] ));
			bounds.extend( point );
			
			var icon = new google.maps.Icon( G_DEFAULT_ICON );
			icon.image =  markerDir + aIconType[ mData[ IX_TYPE ]] + "/" + n + ".png";;
			
			var title;
			if( mData[ IX_TYPE ] == MARKER_SUMMARY ) {
				title = 'Double click to go to ' + mData[ IX_DESC ];
			}
			else {
				title = ( mData[ IX_IMAGE ] ? 'Double click for photo of ' : '' ) + mData[ IX_DESC ];
			}
			
			var marker = new google.maps.Marker( point, { title: title , icon: icon } );						
			g_map.addOverlay( marker );
			google.maps.Event.addListener( marker, "click", 
							   				function( coord ) {
													 if( g_clickTimeOut ) {
//alert( 'timeout set' );
														 //
														 // let timer pop -- double does nothing here
														 // 
													}
													else {
														g_clickTimeOut = window.setTimeout( function()
																			{ _singleClick( coord ) }, TIMEOUT );
													}
 											});
			if( mData[ IX_TYPE ] == MARKER_SUMMARY ) {
				//
				// summary (overview) of all the places
				//
				marker.myID = mData[ IX_ID ];
				google.maps.Event.addListener( marker, "dblclick", 
								  	function() { 
													_clearTimeout();
													window.location.href = URL_PLACE + this.myID ; }
												);
			}
			else if( mData[ IX_IMAGE ] ) { 
				//place, not summary, && image url
				// stash data
				marker.myImage = '/places/pop-image.php?image=' + mData[ IX_IMAGE ] + '&caption=' + mData[ IX_DESC ] + '&credit=' + mData[ IX_CAPTION ] + '&creditsite=' + mData[ IX_CAPTION_SITE ];
				marker.myImageWidth = parseInt( mData[ IX_WIDTH ] ) + IMAGE_WIDTH_INC;
				marker.myImageHeight = parseInt( mData[ IX_HEIGHT ] ) + IMAGE_HEIGHT_INC;
				marker.myMarkerIcon = icon.image;
				// change marker image on mouseover
				google.maps.Event.addListener( marker, "mouseover", 
												function(  ) {
													this.setImage( markerDir + "symbols/binoculars.png" );
												});
				// display image on right click
				google.maps.Event.addListener( marker, "dblclick", 
												function() { genericPop( this.myImage, this.myImageHeight, this.myImageWidth )}
												);
				// restore marker image on mouseout
				google.maps.Event.addListener( marker, "mouseout", 
												function() {
													this.setImage( this.myMarkerIcon );
												});
			}
		}
	}
}

function _singleClick( coord ) {
trace( '_singleClick' );
	_clearTimeout();
	g_map.setCenter( coord, g_map.getZoom() );
}

function _openUrl( coord, url ) {
	_clearTimeout();
	window.location.href = url;
}

function _openPhoto( coord ) {
	_singleClick( coord );		// not opening photo...
}

function _clearTimeout() {
//alert( 'clearing timeout' );
	window.clearTimeout( g_clickTimeOut );
    g_clickTimeOut = null; 	
}

//
// utilizes both onclick and ondblclick for mapMarker clicks
// Can't use one handler with timer as IE can't process 2 clicks (treats as 1); it will process 3 as a double
//
function mapMarkerClick( latitude, longitude ) {
	//
	// invoked from anchor on php page
	//
	var coord = new google.maps.LatLng( latitude, longitude );
	if( g_clickTimeOut ) {
		// do nothing: mapMarkerDblclick() will handle double
	}
	else {
			g_clickTimeOut = window.setTimeout( function()
							{ _singleClick( coord ) }, TIMEOUT );
	}
	
}

function mapMarkerDblclick( latitude, longitude, url ) {
	//
	// invoked from anchor on php page
	//
	var coord = new google.maps.LatLng( latitude, longitude );
	 if( url == undefined ) {
		_openPhoto( coord );
	 }
	 else {
		 // open
		 _openUrl( coord, url );
	 }
}

function mapSetDirections( fromAddress, toCoord, directionID ) {
	dirDiv = document.getElementById( directionID );
	dirDiv.setAttribute( "class", "direction-hidden");
	dirDiv.setAttribute( "className", "direction-hidden");		// IE6
	g_directionID = directionID;
	g_map.setMapType( G_NORMAL_MAP );
	g_directions.loadFromWaypoints( Array( fromAddress, toCoord ));
}

function mapDirectionsHandleAfterLoad() {
		dirDiv = document.getElementById( g_directionID );
		dirDiv.setAttribute( "class", "LHS-box");
		dirDiv.setAttribute( "className", "LHS-box");		// IE6
}
function mapMapHandleError( errorCode ) {
	if (errorCode == FLASH_UNAVAILABLE) {
		alert("Error: Flash doesn't appear to be supported by your browser");
		return;
	}
}  

function mapDirectionsHandleError() {
	if (g_directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		alert("No corresponding geographic location could be found the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\n\nWere city and state specified?" );
	else if (g_directions.getStatus().code == G_GEO_SERVER_ERROR)
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n\nError code: " + g_directions.getStatus().code);
	
	else if (g_directions.getStatus().code == G_GEO_MISSING_QUERY)
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + g_directions.getStatus().code);
	
	else if (g_directions.getStatus().code == G_GEO_BAD_KEY)
		alert("The given key is either invalid or does not match the domain for which it was given. \n\n Error code: " + g_directions.getStatus().code);
	
	else if (g_directions.getStatus().code == G_GEO_BAD_REQUEST)
		alert("A directions request could not be successfully parsed.\n\n Error code: " + g_directions.getStatus().code);
	
	else alert("An unknown error occurred while processing directions.\n\nWas an address specified?");
} 

function trace( msg ){
  if( typeof( jsTrace ) != 'undefined' ){
    jsTrace.send( msg );
  }
}

