/**********************************************************************
 * HH400 Google Maps API Project
 * @File: hh400.map.utilities.js
 * Core JS functions utilized by the HH400 Google Map
 * These functions handle a lot of the functionality for
 * Sidebar non-map-specific elements and the general HTML/DOM type stuff
 * Basic map setup is done via hh400.map.js
 * Additional map functions are handled via hh400.map.helper.js
 * Version 1.0 | 05-04-2009
 * Developed by Cartosoft, LLC
 * http://www.cartosoft.com | info@cartosoft.com
 * Copyright 2009 Google, Inc. | http://www.google.com
**********************************************************************/

/***
Browser Detection Function (used for those pesky IE quirks)
***/

function detectBrowser() {

	if (document.all) {
		return true;
	}
}

/***
Detect IE 6...addressing browser/version specific quirks
***/

function detectIeSix() {
	if (window.XMLHttpRequest) {
		return false;
	} else {
		return true;
	}
}

/***
Show/Hide Sidebar
***/

function toggleSidebar(_ttype_, t_init, _set_) {

	var b_check = detectIeSix();
	
	var map_wrapper_small;
	var map_wrapper_large;
	
	if (fullscreen == 0) {
		map_wrapper_small = '447px';
		map_wrapper_large = '657px';
	}
	else {
		var view_width = document.viewport.getWidth();
		map_wrapper_large = (view_width - 21) + 'px';
		map_wrapper_small = (view_width - 249) + 'px';
	}
	

	if (_ttype_ == 'max') {
		
		$('mapwrapper').setStyle({
		  width: map_wrapper_small,
		  marginLeft: '0px'
		});

		Effect.Grow('sidebar', {direction: 'top-left'});
		
		$('max-button').setStyle({
		  display: 'none'
		});
		
		$('min-button').setStyle({
		  right: '0px'
		});
		
		$('max-fullscreen-button').setStyle({
		  display: 'none'
		});
		
		$('max-smallscreen-button').setStyle({
		  display: 'none'
		});
		
		map.checkResize();
		map.panBy(new GSize(-114,0));
	}
	
	if (_ttype_ == 'min') {
		$('mapwrapper').morph('width:'+map_wrapper_large+';');
		
		$('sidebar').setStyle({
		  display: 'none'
		});
		
		if (!b_check) {
			$('mapwrapper').setStyle({
			  marginLeft: '23px'
			});
		}
		else {
			$('mapwrapper').setStyle({
			  marginLeft: '10px'
			});
		}
		
		$('max-button').setStyle({
		  display: 'inline'
		});
		
		if (fullscreen == 1) {
			$('max-smallscreen-button').setStyle({
			  display: 'block'
			});
		}
		else {
			$('max-fullscreen-button').setStyle({
			  display: 'block'
			});
		}
		
		map.panBy(new GSize(114,0));
		
	}
	
	if (t_init) {
		$('min-button').setStyle({
		  display: 'inline'
		});
		setTimeout(function(){init()}, 1200);
	}
	
	if (!_set_) {
		sidebar_status = _ttype_;
	}

}


/***
Dynamically resize map elements
***/

function resizeMapElements() {

	if (fullscreen == 1) {
	
		//Get the viewport height:
		var view_height = document.viewport.getHeight() - 100;
		var view_width = document.viewport.getWidth();
		
		//Restyle the contents
		$('sidebar').setStyle({
		  height: view_height+'px'
		});
		
		$('mapwrapper').setStyle({
		  width: (view_width - 274) +'px',
		  height: view_height+'px'
		});
	
	}

}


/***
Initialize Content
***/
var ini_maphelp;
function init() {

	//Set up the geocoder
	geocoder = new GClientGeocoder();

	//Open up an infowinfow bubble with a call to action
		var action_html;
		GDownloadUrl('static/call-to-action.txt', function(data, responseCode) {
			 if (responseCode == 200) {
				
				action_html = data;
				
				var check_prefs = getIntroPrefs();
				
				if (check_prefs) {
					map.openInfoWindowHtml(ini_point, action_html, {suppressMapPan:true });
					ini_window = map.getInfoWindow();
					map.panBy(new GSize(-30,450))
					
					ini_maphelp =GEvent.addListener(ini_window, 'closeclick', showMapHelp);
					
				}
			 }
		});
		
	//Show the full screen teaser
	//showHelpTip('fullscreen-tip', $('fullscreen-button'), 'fullscreen', 'Large Map', 10, 5);

	var rec_spans = new Array(
								'num-origins',
								'num-historic-voyages',
								'num-historical-maps',
								'num-historical-illustrations',
								'num-locations-events',
								'num-water-forum'
							);
	
	var check_vars = new Array(
								num_dutch_dna,
								num_historic_voyages,
								num_historical_maps,
								num_historical_illustrations,
								num_locations_events,
								num_water_forum
							);
							
	for (var i=0; i<check_vars.length; i++) {
	
		if (check_vars[i]) {
			$(rec_spans[i]).replace('<span class="num-records">(' + check_vars[i] + ')</span>');
		}
	
	}
	
	//Listener for screen size changes
	Event.observe(document.onresize ? document : window, "resize", resizeMapElements );
	
	//Listener for shortcut list
	Event.observe('shortcuts-control', 'mouseover', function(e) { $('shortcuts-list').setStyle({display:'block'}); });
	Event.observe('shortcuts-control', 'mouseout', function(e) { $('shortcuts-list').setStyle({display:'none'}); });
	
	//Listener for topten list
	Event.observe('topten-control', 'mouseover', function(e) { $('topten-list').setStyle({display:'block'}); });
	Event.observe('topten-control', 'mouseout', function(e) { $('topten-list').setStyle({display:'none'});  });

}


/***
Toggle all of the overlays (lmh)
***/
function toggleOverlaysOff() {
	var check_boxes = new Array('illustrations-toggle','locations-toggle','voyage-toggle-1','voyage-toggle-2','voyage-toggle-3','voyage-toggle-4','origins-toggle','water-toggle');
	
	for (var i=0; i < check_boxes.length; i++) {
		if (check_boxes[i] != mst_overlay) {
			$(check_boxes[i]).checked = false;
		}
	}
	
	if (mst_overlay != 'illustrations-toggle') { toggleIllustrations(); }
	if (mst_overlay != 'locations-toggle') { toggleLocations(); }
	if (mst_overlay != 'origins-toggle') { toggleOrigins(); }
	if (mst_overlay != 'water-toggle') { toggleWater(); }
	
	for (var i=1; i < 5; i++) {
		if (mst_overlay != 'voyage-toggle-'+i) { toggleVoyage(i, '#FFFFFF'); }
	}
	
	overlays_tracker = 1;
	var dsp = new Effect.Fade('num-overlays-div', {duration: 0.5});
}


/***
Check the number of overlays currently visible
***/
function checkNumOverlays() {
	if (overlays_tracker >= 2) {
		var check_prefs = getOverlayPrefs();
		if (check_prefs) {
			var dsp = new Effect.Appear('num-overlays-div', {duration: 0.5});
		}
	}
}



/***
Show User a Brief Description of How to Toggle Default Historical Map Off
***/
function showMapHelp() {
		
	var check_prefs = getIntroMapPrefs();
			
	if (check_prefs) {
		
		//Open up an infowinfow bubble with a call to action
		var action_html;
		GDownloadUrl("static/initial-map-help.txt", function(data, responseCode) {
			 if (responseCode == 200) {
				action_html = data;
				map.openInfoWindowHtml(ini_point, action_html, {suppressMapPan:true });
				
				GEvent.removeListener(ini_maphelp);
			 }
		});
	}
}


/***
Show/Hide Theme Content
***/

function showHelp() {

	var help_elements = $('help-content').childElements();
	
	if (help_elements.length < 2) {
		
		$('help-wrapper').toggle();
	
		GDownloadUrl('static/help-content.txt', function(data, responseCode) {
		
			if (responseCode == 200) {
				$('help-content').update(data);
			}
		});
	}
	else {
		if (!$('help-wrapper').visible()) {
			$('help-wrapper').toggle();
		}
	}
	
}

/***
Show/Hide Theme Content
***/

function toggleTheme(_themeid_, _no_change_) {

	var cur_div = $(_themeid_ +'-content').visible();

	var themes = new Array(
							'historical-maps',
							'historic-voyages',
							'locations-events',
							'origins',
							'international-water-forum'
							);
							
	for (var i=0; i<themes.length; i++) {
	
		var theme = themes[i];
		
		$(theme +'-header').addClassName('inactive-header');
		$(theme +'-content').hide();
		$(theme +'-arrow').src="images/library/icons/icon-arrow-min.gif";
		
	}
	
	setTheme();
	
	
	function setTheme() {
	
		if (!cur_div) {
			$(_themeid_ +'-header').removeClassName('inactive-header');
			$(_themeid_ +'-content').show();
			$(_themeid_ +'-arrow').src="images/library/icons/icon-arrow-max.gif";
		}
		else {
			
			if (!_no_change_) {
				$(_themeid_ +'-content').hide();
			}
			
			else {
				$(_themeid_ +'-header').removeClassName('inactive-header');
				$(_themeid_ +'-content').show();
				$(_themeid_ +'-arrow').src="images/library/icons/icon-arrow-max.gif";
			}
		}
	}


}

/***
Show loading message for theme
***/
function showLoadingStatus(theme) {
	$('status-div').setStyle({display:'block'});
	$('status-message').update('Loading...');
}

function hideLoadingStatus() {
	$('status-div').setStyle({display:'none'});
}


/***
Legend Info Tool Tip
***/

function showTip(sel_div, no_ajax, t_id) {

	var sel_element = $(sel_div+'-tooltip');
   	var sel_icon = $(sel_div+'-tooltip-icon');
   	
   	if (t_id) {
   		sel_element = $(sel_div+'-tooltip-'+t_id);
   		sel_icon = $(sel_div+'-tooltip-icon-'+t_id);
   	}
   	
   	var off_set = sel_icon.viewportOffset();
   	
   	var m_type = map.getCurrentMapType();
   	
   	if (m_type == G_SATELLITE_3D_MAP) {
   		$(sel_element).setStyle({
		  left: '0px',
		  top: '0px',
		  width: '100%'
			});
   	}
   	else {
   	
   	$(sel_element).setStyle({
		  left: off_set[0] + 25 + 'px',
		  top: off_set[1] -14 + 'px'
		});
	}
	
	sel_element.toggle();
	
	//See if the AJAX call should be made:
	if (!no_ajax) {
	
		//A little AJAX call to get the content (every little bit counts!)
		var url = 'static/'+sel_div+'-content.txt';
				
		GDownloadUrl(url, function(data, responseCode) {
		
			if (responseCode == 200) {
				$(sel_div+'-tooltip').update(data);
			}
		});
	}
}


/***
Legend Help Tool Tip Functions
***/

function showHelpTip(sel_div, icon, help_type, title, off_top, off_left) {
	
	var icon_a = $(icon);
	
	var off_set = icon_a.viewportOffset();
	
	var sel_seg = sel_div.substr(0,3);
	
	if (!off_top) { off_top = 0; }
	if (!off_left) { off_left = 0; }
	
	var iesix_check = detectIeSix();
	
	//Adjust CSS styling for IE...
	if (ie_check) {
		off_left = 7;
		//Another hack for IE...does it ever end!
		if (sel_seg == 'ill' || sel_seg == 'voy') {
			off_left = 11;
		}
	}
	
	var offset_right = ($('container').getWidth() - off_set[0]) -20 + off_left + 'px';
	var offset_bottom = ($('container').getHeight() - off_set[1]) + 6 + off_top + 'px';
   	
   	var html = '';
   	
   	switch (help_type) {
		case 'opacity':
		html = 'Click on this button to <strong>show or hide the opacity control</strong> for this layer.';
		break;
		case 'extent':
		html = 'Click on this button to <strong>see everything</strong> in this layer (map will zoom in/out).';
		break;
		case 'info':
		html = 'Click on this button to view <strong>more information</strong> for this layer.';
		break;
		case 'icon':
		html = 'This is the icon used to display <strong>' + title + '</strong> on the map.';
		break;
		case 'line':
		html = 'A line this color is used to display <strong>' + title + '</strong> on the map.';
		break;
		case 'origins-teaser':
		html = 'Click here to <strong>contribute your own information</strong> to the Origins map layer.';
		break;
		case 'fullscreen':
		html = 'Click here to make<br/>the map bigger.'; 
		break;
	}
	
	if ($(sel_div + '-' + help_type)) {
		$(sel_div + '-' + help_type).remove();
	}
   	
	var tooltip = new Element('div', { 'class': 'legend-help-tooltip', 'id': sel_div + '-' + help_type }).update(html);
	
	var tooltip_img = '<span class="legend-help-tooltip-arrow"><img src="images/library/misc/legend-help-tooltip-arrow.gif" alt="" /></span>';
	
	tooltip.insert(tooltip_img);
	
	tooltip.setStyle({
	  right: offset_right,
	  bottom: offset_bottom,
	  zIndex: 99999999
	});
		
	$('container').insert({before:tooltip});

}

function hideHelpTip(sel_div, help_type) {
	$(sel_div+ '-' + help_type).hide();
}


/***
Scroller/Carousel for Historical Maps
Home-grown carousel function; avoids bloat from other scripts
***/
function scrollMaps(s_wrapper, s_container, direction, increment, opacity_control) {

	var scroll_duration = 0.5
	
	var wrapper_height = $(s_wrapper).getHeight();
	
	var container_height = $(s_container).getHeight();
	
	if (!increment) { increment = wrapper_height/2; }
	
	var container_top = $(s_container).getStyle('top');
	
	
	if (opacity_control) {
	
		var op_coords = $(opacity_control).viewportOffset();
		
		var wrapper_coords = $(s_wrapper).viewportOffset();
		
		var op_top = op_coords[1];
		
		var wrapper_bottom = wrapper_coords[1] + wrapper_height - 60;
		
		if (op_top < wrapper_bottom) {
			return false;
		}
		
	}
	
	
	if (direction == 'up') {
		
		var off_set = parseInt(increment) + parseInt(container_top);
	
		if (off_set > 0) {
			off_set = 0;
		}
	
		new Effect.Move(s_container, { x: 0, y: off_set, mode: 'absolute', duration: scroll_duration });
	}
	
	if (direction == 'down') {
		
		var off_set = parseInt(container_top) - parseInt(increment);
	
		if (Math.abs(off_set) > container_height) {
			off_set = parseInt(container_top);
		}
	
		new Effect.Move(s_container, { x: 0, y: off_set, mode: 'absolute', duration: scroll_duration });	
	}
	
	if (opacity_control) {
		new Effect.Highlight($(opacity_control));
	}

}

/***
Image Scroller (in Info Window) for 2 or more images
***/
function scrollImages(rec, id) {
	var im_elements = $('table-image-'+rec).childElements()[0].childElements();
	
	for (var i=0; i<im_elements.length; i++) {
		var sel_element = im_elements[i];
		var sel_id = sel_element.identify();
		
		if (sel_id == 'table-image-tr-'+id) {
			sel_element.setStyle({display:'inline'});
			$('carousel-image-li-'+i).addClassName('active-image');
			$('carousel-image-li-'+i).removeClassName('inactive-image');
		}
		else {
			sel_element.setStyle({display:'none'});
			$('carousel-image-li-'+i).removeClassName('active-image');
			$('carousel-image-li-'+i).addClassName('inactive-image');
		}
	}

}

/***
Get list of GE Models
***/
function getGeList() {
	var ge_list = new Element('div', {'id':'ge-list'});
	var ge_status_div = new Element('div', {'id':'ge-status-div'});
	$('ge-list-wrapper').insert(ge_list);
	GDownloadUrl("utilities/hh400.3dmodels.php", function(data, responseCode) {
		 if (responseCode == 200) {
		 	var close_button = '<img src="images/library/misc/legend-tooltip-close.gif" alt="Close" class="legend-tooltip-close" onClick="hideGeList();" style="top: 10px; right:10px;" />';
			ge_list.innerHTML = data + close_button;;
		 }
	});
}

function hideGeList() {
var a = new Effect.Shrink('ge-list-wrapper', {direction:'top-left'});
$('ge-list-toggle').setStyle({display:'block'});
$('sidebar-content').setStyle({display:'block'});
}

/***
Set whether GE Buildings layer is show or not
***/
function setGeBuildings() {
	if ($('show-ge-buildings').checked == true) {
		ge_buildings = 1;
		ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS, true);
	}
	else {
		ge_buildings = 0;
		ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS, false);
	}
}

/******************************************** Cookie Functions ************************************/
/***
Set Intro Message Preferences
***/

function setIntroPrefs() {
	var check_status = $('show-intro-window').checked;
	
	if (check_status) {
		createCookie('intro-prefs','No',30);
	}
	else {
		eraseCookie('intro-prefs');
	}
	
}

function getIntroPrefs() {
	var check_prefs = readCookie('intro-prefs');
	if (check_prefs == 'No') {
		return false;
	}
	else {
		return true;
	}
}


/***
Set Intro Map Help Preferences
***/

function setIntroMapPrefs() {
	var check_status = $('show-intro-maphelp').checked;
	
	if (check_status) {
		createCookie('intro-map-prefs','No',30);
	}
	else {
		eraseCookie('intro-map-prefs');
	}
	
}

function getIntroMapPrefs() {
	var check_prefs = readCookie('intro-map-prefs');
	if (check_prefs == 'No') {
		return false;
	}
	else {
		return true;
	}
}

/***
Set Number of Overlays Message Preferences
***/

function setOverlayPrefs() {
	var check_status = $('show-num-overlays').checked;
	
	if (check_status) {
		createCookie('overlay-prefs','No',30);
	}
	else {
		eraseCookie('overlay-prefs');
	}
	
}

function getOverlayPrefs() {
	var check_prefs = readCookie('overlay-prefs');
	if (check_prefs == 'No') {
		return false;
	}
	else {
		return true;
	}
}


/***
Create Cookie
***/

function createCookie(name,value,days) {

	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

/***
Read Cookie
***/

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

/***
Erase Cookie
***/

function eraseCookie(name) {
	createCookie(name,"",-1);
}
