//
//
// "LocationsMapper"
// Custom Google Maps Implementation
//
// by Reuben King (c) 2007
// Swirl.net
//
//
// ** See includes/*.js for implementations
//

//
//
// Determine the API key to pass to Google.  You can override this by declaring GoogleApiKey variable elsewhere
function getGoogleApiKey()
{
	if ( typeof this["GoogleApiKey"] == "undefined" )
	{
		switch( window.location.hostname )
		{
		  case 'swirl.net' :
		    this.GoogleApiKey = 'ABQIAAAAXZ1OMLWrd8xzNA-TSJv-gBQQKyAywM3WYPGJ6oWCw8jw8vzORxQeWK8P23Byx0yAVZHObLiS68YDuA';
		    break;
		  case 'www.swirl.net' :
				this.GoogleApiKey = 'ABQIAAAAXZ1OMLWrd8xzNA-TSJv-gBSqdPF4YkV432qIrLILwHcDudi8chSX4XrMFF7OJwtNo_8-ghnGHm7Z3w';
				break;
		  case 'www.swirlintegratedmarketing.com' :
		    this.GoogleApiKey = 'ABQIAAAAXZ1OMLWrd8xzNA-TSJv-gBTtj8ol-mZKLMhCHlsIq2DvZeqMhxRGBK9DARY7fee06OkrvjTcxUOBiw';
		    break;
		  case 'www.swirlclient.com' :
		    this.GoogleApiKey = 'ABQIAAAAXZ1OMLWrd8xzNA-TSJv-gBT7B_BAxkaZBPS1Q7M2yfN7VrmSQBQWTNic18YlhtNScuND7fNGTIFxWg';
		    break;
			case 'mtc.ca.gov' :
				this.GoogleApiKey = 'ABQIAAAAXZ1OMLWrd8xzNA-TSJv-gBTwYB5ZGNEtbr4-6ANzysMrZdigbRS7x_aVJGfWCP1qiQR_AtAgOLNAgg';
				break;
			case 'bayareafastrak.org' :
				this.GoogleApiKey = 'ABQIAAAAXZ1OMLWrd8xzNA-TSJv-gBTssKg_keoj4OfR8VKYfNaQ6UmIahRdP3coO3oOAgfztfCwTz22MwaBGA';
				break;
			case 'www.swirlclient.com' :
				this.GoogleApiKey = 'ABQIAAAAXZ1OMLWrd8xzNA-TSJv-gBTZXGjdPFBwlKhO6EaT_rOTFQvqzBQXapXWvTt0fAQGci9QQK6PQZ8TKA';
				break;		
			case 'swirlclient.com' :
				this.GoogleApiKey = 'ABQIAAAAXZ1OMLWrd8xzNA-TSJv-gBTZXGjdPFBwlKhO6EaT_rOTFQvqzBQXapXWvTt0fAQGci9QQK6PQZ8TKA';
				break;
			case 'swirlworks' :
				this.GoogleApiKey = 'ABQIAAAAXZ1OMLWrd8xzNA-TSJv-gBR4prMfvWaTaE4YGnlGbr4WH60tuhRtWOHJ6XIJUyXUT6MMxE4PRPwdXw';
				break;
			case '12.43.58.115' : //swirlworks external IP
				this.GoogleApiKey = 'ABQIAAAAXZ1OMLWrd8xzNA-TSJv-gBToEOEFvgiTARg8bP7n2nySqni8_RSzYmpF6C2gyskJchBZHqhyewMusQ';
				break;
			case '192.168.200.7' : //swirlworks internal IP
				this.GoogleApiKey = 'ABQIAAAAXZ1OMLWrd8xzNA-TSJv-gBS94kfd9MYIqEJ6iMy4F0wE3bUFHxQZb6UwM4CZ4uwrvJ8wyQm1LeCzVg';
				break;
			case 'mission' :
			  this.GoogleApiKey = 'ABQIAAAAXZ1OMLWrd8xzNA-TSJv-gBQHN8lgX34sHCW8zmDKKgsCfqU3VBQACUrPe_gDNF1eagdmIOuFCHewEw';
			  break;
			case 'mission.local' :
				this.GoogleApiKey = 'ABQIAAAAXZ1OMLWrd8xzNA-TSJv-gBT9vjS6bZoyRWdafA27fSyKa8L53RQgq3_0D0vw22v6_0ra4GDD0G9oNA';
				break;
			case 'www.reubidium.com' :
				this.GoogleApiKey = 'ABQIAAAAXZ1OMLWrd8xzNA-TSJv-gBQfOCCoxcnUmn1mXNR-kH-L5RjKvhRPsQJ7n0gg1iJiJ7peZlXQHVQYiA';
				break;
			case 'lips' :
				this.GoogleApiKey = 'ABQIAAAAXZ1OMLWrd8xzNA-TSJv-gBTSCJc4-PcrtljF3fYWbHiO8ET4BRQWh5I7Koj6CQjpP5Q9P7UdXmoPsA';
				break;
			case 'lips.local' :
				this.GoogleApiKey = 'ABQIAAAAXZ1OMLWrd8xzNA-TSJv-gBQXw9CbfP5SvvliPpoP2e4uMB4geBTFktQB5WY0tiOdK-skDkuZcAYILA';
				break;	
			default :
				window.alert( 'Error: Don\'t know Google Maps API Key for http_host "' + window.location.hostname + '"' );
		}
	}
	
	return this.GoogleApiKey;
}


//
// Default Settings in case the config.js doesnt load
if ( typeof this["LocationsMapperConfig"] == "undefined" ) 
{
  if ( typeof(console) == 'object' ) {
    console.log('using default configuration, LocationsMapperConfig var not found');
  }
	this.LocationsMapperConfig = 
	{
		// Definitions of Locations Layers:
		// "id" - corresponds to Location attribute "type" for filtering if FilterOnId is true
		// "MarkerIcon" - the URL (relative to calling HTML page) of the icon to be used for Locations in this layer
		// "LocationsXmlFile" - The URL (relative to calling HTML page) of the XML Locations data
		// "ShowOnLoad" - If true, this layer will be loaded and displayed immediately
		Layers : [
			{ ID: 'costco',  title: 'Costco',  MarkerIcon: 'googlemap/marker_icons/mm_20_red.png',    LocationsXmlFile: 'locations.xml', FilterOnId: true, ShowOnLoad: false },
			{ ID: 'safeway', title: 'Safeway', MarkerIcon: 'googlemap/marker_icons/mm_20_green.png',  LocationsXmlFile: 'locations.xml', FilterOnId: true, ShowOnLoad: false },
			{ ID: 'other',   title: 'Other',   MarkerIcon: 'googlemap/marker_icons/mm_20_yellow.png', LocationsXmlFile: 'locations.xml', FilterOnId: true, ShowOnLoad: false }
		],
		
		//
		// If you'd like to use the Regions functionality, define them in here:
		Regions : [
			{ ID: 'marin',    title: 'Marin County',  lat: 38.04917251752292, long: -122.67059326171875, zoom: 10 },
			{ ID: 'sf',       title: 'San Francisco', lat: 37.74872922848492, long: -122.43061065673828, zoom: 12 },
			{ ID: 'eastbay',  title: 'East Bay',      lat: 37.899239630600185, long: -122.27508544921875, zoom: 11 },
			{ ID: 'southbay', title: 'South Bay',     lat: 37.45523781879053, long: -122.19406127929688, zoom: 10 }
		],
		
		// set this to TRUE to have a user select a Region from above before being allowed to use the map
		SelectRegionOnLoad : true,
		
		// this is a function that will be called to build the contents of the Select Region dialog.  
		// It must return a DOM tree!
		// note that the first argument is a handle to the caller MapDialog so the onRegionSelect handler
		// can be bound
		SelectRegionDialogContents: function( caller, regions ) 
		{
			// you can pass regions to this function or it will use what is here already
			if ( typeof regions == 'undefined' ) {
				var regions = LocationsMapperConfig.Regions;
			}
			
			var div1 = $( document.createElement('div') );
			div1.addClassName( 'regionSelect' );
			div1.innerHTML = '<p>Select A Region:</p>';
			
			for ( var i = 0; i < regions.length; i++ ) {
				var el = $( document.createElement('button') );
				el.innerHTML = regions[i].title;
				el.setAttribute( 'region_id', regions[i].ID );
				
				Event.observe( el, 'click', caller.onRegionSelect.bindAsEventListener( caller ) );
				
				var el2 = $( document.createElement('p') );
				el2.addClassName( 'regionRow' );
				
				el2.appendChild( el );
				div1.appendChild( el2 );
			}
			
			return div1;
		},
		
		
		/* Uncomment and use this if you'd like to use the Icon attribute for Locations and determine the marker icon based on this hash table:
		MarkerIcons : {
			costco : 'googlemap/marker_icons/mm_20_red.png',
			safeway : 'googlemap/marker_icons/mm_20_green.png',
			other : 'googlemap/marker_icons/mm_20_yellow.png'
		},
		*/
		
		MapLoadedDialogContentsURL : 'googlemap/mapLoaded.html',
		
		// The graphic shadow to place under the marker icon
		MarkerShadowIcon : 'googlemap/marker_icons/mm_20_shadow.png',
		
		// A default icon to use if the location type does not match one defined above
		MarkerIconDefault : 'googlemap/marker_icons/mm_20_grey.png',
		
		// IDs of content DIVs
		MapOuterDivId      : 'googleMapOuter',
		MapInnerDivId      : 'googleMap',
		DirectionsDivId    : 'gDrivingDirections',
		
		// Pixel dimensions of Driving Directions Div
		DirectionsWidth   : 200,
		DirectionsPadding : 8,
		
		// Initial center of origin point for map (latitude/longitude)
		InitialLatitude  : 37.820632846207864,
		InitialLongitude : -122.07183837890625,
		InitialZoomLevel : 9,
		
		// Set to TRUE if you'd like the zoom/pan controls available
		ShowBaseControls   : true,
		
		// Set to TRUE if you'd like the street/satellite/hybrid selection controls available
		ShowExtraControls  : true,
	
		// Set this to TRUE to disable caching of XML location data:
		ForceNoCache : true
		
	};
}
else {
  if ( typeof(console) == 'object' ) {
    console.log('using user specified LocationsMapperConfig');
  }
}



// Dynamic includes:
// These will be included in the order they are defined in this array.
// Note the ywill all be appended to the end of the HTML HEAD element
function getRequiredIncludes()
{
	var requiredIncludes = [
		{
		  name : 'google-maps-api',
		  type : 'javascript',
		   src : 'http://maps.google.com/maps?file=googleapi&v=2&key=' + escape( getGoogleApiKey() )
		},
		/*
		not using this in favor of above method
		{
		  name : 'google-loader',
		  type : 'javascript',
		   src : 'http://www.google.com/jsapi?key=' + escape( getGoogleApiKey() )
		 },
		*/
		
		{ 
		  name : 'prototype-js',
		  type : 'javascript', 
		   src : 'googlemap/includes/ext/prototype.js'
		},
		
		{
		  name : 'scriptaculous',
		  type : 'javascript',
		   src : 'googlemap/includes/ext/scriptaculous.js'
		},
		
		{
		  name : 'effects',
		  type : 'javascript',
		   src : 'googlemap/includes/ext/effects.js'
		},

		{ 
		  name : 'prototype-window',
		  type : 'javascript', 
		   src : 'googlemap/includes/ext/window.js'
		},
		
		{ 
		  name : 'utilities',
		  type : 'javascript', 
		   src : 'googlemap/includes/util.js'
		},
		
		{
		  name : 'MapDialog implementation',
		  type : 'javascript',
		   src : 'googlemap/includes/MapDialog.js'
		},
		
		{
		  name : 'Location implementation',
		  type : 'javascript',
		   src : 'googlemap/includes/Location.js'
		},
		
		{
		  name : 'LocationsManager implementation',
		  type : 'javascript',
		   src : 'googlemap/includes/LocationsManager.js'
		},
		
		{
		  name : 'DirectionsManager implementation',
		  type : 'javascript',
		   src : 'googlemap/includes/DirectionsManager.js'
		},
		
		{ 
		  name : 'LocationsMapper core',
		  type : 'javascript', 
		   src : 'googlemap/includes/core.js'
		},
		
		{ 
		  name : 'LocationsMapper implementation',
		  type : 'javascript', 
		   src : 'googlemap/includes/LocationsMapper.js'
		}
				
	];
	
	return requiredIncludes;
}


//
//
// Includes of above are established within here:
//
(function() {
	var requiredIncludes = getRequiredIncludes();
    
	var htmlHead = document.getElementsByTagName('head').item(0);
	var el;
	
	for ( var i = 0; i < requiredIncludes.length; i++ )
	{
		
		if ( requiredIncludes[i].type == 'javascript' )
		{
			if ( typeof(console) == 'object' ) console.log( 'include ' + requiredIncludes[i].name + ': ' + requiredIncludes[i].src );
			/*
			tried using DOM to do this but it was not working out well in IE6: 
			The document onload event would be fired before everything was finished loading.  
			el = document.createElement( 'script' );
			el.setAttribute( 'language', 'javascript' );
			el.setAttribute( 'type', 'text/javascript' );
			el.setAttribute( 'src', requiredIncludes[i].src );
			
			htmlHead.appendChild( el );
			*/
			
			// this seems to work more reliably:
			document.write( '<script language="javascript" type="text/javascript" src="' + requiredIncludes[i].src + '"></script>' );
		}
		
		else if ( requiredIncludes[i].type == 'stylesheet' )
		{
			if ( typeof(console) == 'object' ) console.log( 'use stylesheet ' + requiredIncludes[i].name + ': ' + requiredIncludes[i].src );
			
			el = document.createElement( 'link' );
			el.setAttribute( 'href', requiredIncludes[i].src );
			el.setAttribute( 'rel', 'stylesheet' );
			el.setAttribute( 'type', 'text/css' );
			
			if ( typeof requiredIncludes[i].media != "undefined" )
				el.setAttribute( 'media', requiredIncludes[i].media );
			
			htmlHead.appendChild( el );
		}
		
		else
		{
			if ( typeof(console) == 'object' ) console.log( 'error parsing dep ' + requiredIncludes[i].name + ' (' + requiredIncludes[i].type + '): ' + requiredIncludes[i].src );
		}
	}
})();


//
//
// image preloads
//
(function() {
	 if ( typeof(console) == 'object' ) console.log( 'preloading various map images' );
	
	// throbber images
	this._throbberImg = new Image(32,32);
	this._throbberImg.src = 'googlemap/includes/img/ajax-loader.gif';
	
	this._throbberBkgd = new Image(10,10);
	this._throbberBkgd.src = 'googlemap/includes/img/80_perc_white.png';
	
	this._throbberBkgdIE = new Image(2,2);
	this._throbberBkgdIE.src = 'googlemap/includes/img/50_perc_white.gif';
	
	//
	// marker icons and shadow images
	this._iconImgs = [];
	// legend icons (may not be present)
	this._legendImgs = [];
	
	var tImg;
	
	tImg = new Image();
	tImg.src = LocationsMapperConfig.MarkerIconDefault;
	this._iconImgs.push( tImg );
	
	tImg = new Image();
	tImg.src = LocationsMapperConfig.MarkerShadowIcon;
	this._iconImgs.push( tImg );
	
	for ( var i = 0; i < LocationsMapperConfig.Layers.length; i++ ) {
		tImg = new Image();
		tImg.src = LocationsMapperConfig.Layers[i].MarkerIcon;
		this._iconImgs.push( tImg );
		
		if ( ( 'LegendIcon' in LocationsMapperConfig.Layers[i] ) && typeof( LocationsMapperConfig.Layers[i].LegendIcon ) != 'undefined' ) {
		  var tImg = new Image();
		  tImg.src = LocationsMapperConfig.Layers[i].LegendIcon;
		  this._legendImgs.push( tImg );
		}
	}
	
	if ( 'PreloadImages' in LocationsMapperConfig ) {
	 this._preloadOtherImages = [];
	 
	 for ( var i = 0; i < LocationsMapperConfig.PreloadImages.length; i++ ) {
	   tImg = new Image();
	   tImg.src = LocationsMapperConfig.PreloadImages[i];
	   this._preloadOtherImages.push( tImg );
	 }
	}
	
	
})();


function dieGracefully( str )
{
	//@todo: beef this up
	if ( ( 'console' in window ) && ( 'firebug' in console ) ) {
		console.error('died: ' + str );
	}
	
	try {
		var outerDiv = $( LocationsMapperConfig.MapOuterDivId );
		var innerDiv = $( LocationsMapperConfig.MapInnerDivId );
		var fatalErrDiv = document.createElement('div');
		
		fatalErrDiv.id = 'gMapsError';
		fatalErrDiv.innerHTML = '<p class="error title">Unable to display locations map:</p><p class="error">' + str + '</p>'
		
		outerDiv.replaceChild(  fatalErrDiv, innerDiv );
	} catch ( ex ) {
		window.alert( str );
	}
}
