var BASE_URL = 'http://' + location.host + '/deaggint/1996';
var DEFAULT_LOCATION = null; // This is where the map will center by default.
var ALASKA_LOCATION  = null  // This is the center of Alaska (about)
var HAWAII_LOCATION  = null  // This is the center of Hawaii (about)
var DEFAULT_ZOOM = 3;        // This is the default zoom level of the map.
var LOCATION_TIMEOUT = null; // Timeout handle for location input
var LOCATION_MARKER = null;
var GEOCODER = null;

initApplication = function(_event) {
	addClass('app-wrapper', 'active');
	DEFAULT_LOCATION = new GLatLng(39, -100);
	ALASKA_LOCATION = new GLatLng(65, -150);
	HAWAII_LOCATION = new GLatLng(19.5, -155.5);
	window.IO = new Dialog();
	initControls(_event);
	initGoogleMap(_event);
	initOutputArea(_event);
};

initGoogleMap = function(_event) {
	if (GBrowserIsCompatible()) {
		window.map = new GMap2(document.getElementById('app-map'));
		window.map.setCenter(DEFAULT_LOCATION, DEFAULT_ZOOM, G_PHYSICAL_MAP);
		window.map.addControl(new GSmallMapControl());

		// Create the icon for our marker
		var _icon = new GIcon();
		_icon.image = BASE_URL + '/images/marker_img.gif';
		_icon.shadow = BASE_URL + '/images/marker_shadow.gif';
		_icon.iconSize = new GSize(25, 25);
		_icon.shadowSize = new GSize(25, 25);
		_icon.iconAnchor = new GPoint(13, 24);

		// Create the location marker for our application
		LOCATION_MARKER = new GMarker(DEFAULT_LOCATION, {
				icon:_icon,
				draggable:true,
				clickable:false,
				bouncy:true,
				autoPan:true
			});
		window.map.addOverlay(LOCATION_MARKER);

		// Create the geocoder to do location lookups for us.
		GEOCODER = new GClientGeocoder();

		// Add two pseudo-controls to the map to re-center on AK/HI
		$('#app-map').append(
				'<span id="recentermap">Recenter: ' +
					'<a href="javascript:void(null);" id="centerus">Mainland</a> | '+
					'<a href="javascript:void(null);" id="centerak">Alaska</a> | ' +
					'<a href="javascript:void(null);" id="centerhi">Hawaii</a>' +
				'</span>'
			);

		$('#centerus').click(function() {
			window.map.setCenter(DEFAULT_LOCATION, DEFAULT_ZOOM, G_PHYSICAL_MAP);
			LOCATION_MARKER.setLatLng(DEFAULT_LOCATION);
		});
		$('#centerak').click(function() {
			window.map.setCenter(ALASKA_LOCATION, DEFAULT_ZOOM, G_PHYSICAL_MAP);
			LOCATION_MARKER.setLatLng(ALASKA_LOCATION);
		});
		$('#centerhi').click(function() {
			window.map.setCenter(HAWAII_LOCATION, 6, G_PHYSICAL_MAP);
			LOCATION_MARKER.setLatLng(HAWAII_LOCATION);
		});

	} else {
		window.IO.alert('Your browser does not support Google Maps.');
	}
};

initControls = function(_event) {
	$('#app-controls').empty();
	$('#app-footer').append('<img src="images/btnCompute.gif" id="btnCompute" ' +
			'alt="Compute" />'
		);
	$('#app-footer').append('<img src="images/btnClear.gif" id="btnClear" ' +
			'alt="Clear" />'
		);
	$.get('inc/controls.inc.php?formtype=active', function(_response) {
			$('#app-controls').append($(_response));
			$('#app-controls ol').append('<li><a href="javascript:void(null);" ' +
					'id="toggleMap">Hide Location Map</a></li>'
				);
			initHandlers(_event);
		});
};

initHandlers = function(_event) {
	// Handler to toggle the map hide/show feature
	$('#toggleMap').click(function() {
			if ($('#toggleMap').text() == 'Hide Location Map') {
				$('#toggleMap').text('Show Location Map');
				$('#app-map').slideUp();
			} else {
				$('#toggleMap').text('Hide Location Map');
				$('#app-map').slideDown();
			}
		});
	
	// Handler to watch for changes to the location field
	$('#location').keypress(function(_event) {
			if (LOCATION_TIMEOUT != null) { clearTimeout(LOCATION_TIMEOUT); }
			var c = _event.charCode || _event.keyCode;
			if (c == 13) { // 'Enter' key was pressed, trigger immediately
				updateLocation(true);
			} else { // Wait 2.5 seconds, then compute results
				LOCATION_TIMEOUT = setTimeout("updateLocation()", 2500);
			}
		});
	
	// Handler to watch for loss of focus on location field. Update address.
	$('#location').blur(function() {
			if (LOCATION_TIMEOUT) { clearTimeout(LOCATION_TIMEOUT); }
			updateLocation(true);
		});

	// Handler to check loaction of marker when dagged
	GEvent.addListener(LOCATION_MARKER, 'dragend', function(_point) {
			if (pointIsValid(_point)) {
				$('#location').val(''); // Clear the location field
				window.map.setCenter(_point, 13);
			} else {
				var message = document.createElement('div');
				$(message).text($('<p>' + prettyLat(_point.lat()) + ', ' +
					prettyLng(_point.lng()) + ' is not within the bounds of the ' +
					'United States. Please select a U.S. location and try again.</p>'
					).html());
				window.IO.alert(message, 
						{ctype:'text/html',title:'Location Out Of Bounds'}
					);
				LOCATION_MARKER.setLatLng(DEFAULT_LOCATION);
			}
		});

	// Handler to switch map types when zoomed in.
	GEvent.addListener(LOCATION_MARKER, 'zoomed', function(_old, _new) {
			if (_old <= 13 && _new > 13) {
				window.map.setMapType(G_HYBRID_MAP);
			} else if (_old > 13 && _new <= 13) {
				window.map.setMapType(G_PHYSICAL_MAP);
			}
		});

	// Handler to compute results when clicked
	$('#btnCompute').click(function() {
			$('#btnCompute').attr('src', 'images/btnCompute_down.gif');
			window.IO.showLoading('Computing Results...');
			computeResults();
		});
	// Handler to clear the output area when clicked.
	$('#btnClear').click(function() {
			$('#btnClear').attr('src', 'images/btnClear_down.gif');
			setTimeout("clearOutput()", 250);
		});
};

clearOutput = function() {
	$('#app-output').slideUp();
	$('#output-links').empty();
	$('#btnClear').attr('src','images/btnClear.gif');
};

initOutputArea = function(_event) {
	$('#app-output').append($('<ul id="output-links"></ul>'));
	$('#app-output').slideUp();
};

updateLocation = function(_withNotification) {
	_withNotification = _withNotification || false;
	GEOCODER.getLatLng($('#location').val(), function(_point) {
		if (pointIsValid(_point)) {
			LOCATION_MARKER.setLatLng(_point);
			window.map.setCenter(_point, 13);
		} else {
			if (_withNotification) {
				var message = document.createElement('div');
				$(message).text($('<p>Query for: &ldquo;' + $('#location').val() + 
					'&rdquo; did not return a valid location. Please select a U.S. '+
					'location ' + 'and try again.</p></div>').html());
				window.IO.alert(message,
					{ctype:'text/html',title:'Location Out Of Bounds'});
			}
		}
	});
};

computeResults = function() {
	var location = LOCATION_MARKER.getLatLng();
	var url = 'inc/response_xml.php?name='+$('#name').val()+
	          '&lat='+location.lat()+'&lng='+location.lng()+
	          '&period='+$('#period').val()+'&sa='+$('#sa').val()+
				 '&geo='+$('#geo').attr('checked');
	$.get(url, function(_response) {
		var status = $('status', $(_response)).text();
		if (status == 0) {
			// Successfully generated output. Show it to user.
			generateOutput($('name', $(_response)).text(),
					$('lat', $(_response)).text(), $('lng', $(_response)).text(),
					$('period', $(_response)).text(), $('sa', $(_response)).text(),
					$('links', $(_response))
				);
		} else {
			// An error occurred while generating the output. Alert an error.
			window.IO.alert('An error occurred while processing your request. ' +
					'Please check your input values and try again.');
		}
		$('#btnCompute').attr('src', 'images/btnCompute.gif');
		window.IO.closeDialog();
	});
};

generateOutput = function(_sitename,_latitude,_longitude,_period,_sa,_links) {
	var output = '<li><strong>'+_sitename+'</strong><span class="downloads">';
	$('link', $(_links)).each(function() {
		output += '<a href="' + $(this).attr('url') + '" title="' +
				$(this).attr('size') + '" target="_blank">' + 
				$(this).attr('display')+'</a>';
	});
	output += '</span><span class="metainfo">'+_sa+' '+_period+'</span></li>';

	$('#output-links').append($(output));
	$('#app-output').slideDown();
};

prettyLat = function(_lat) {
	_lat = Math.round(_lat * 100) / 100;
	var extra = '&deg;N';
	if (_lat < 0) { extra = '&deg S'; _lat *= -1; }
	return '' + _lat + extra;
};

prettyLng = function(_lng) {
	_lng = Math.round(_lng * 100) / 100;
	var extra = '&deg;E';
	if (_lng < 0) { extra = '&deg;W'; _lng *= -1; }
	return '' + _lng + extra;
}

pointIsValid = function(_point) {
	if (!_point) { return false; }
	var lat = _point.lat();
	var lng = _point.lng();
	return (lat>=24.6&&lat<=50.0&&lng>=-125.0&&lng<=-65.0) || /*48 Conterminous*/
	       (lat>=48&&lat<=72&&lng>=-200&&lng<=-125) || /*Alaska*/
			 (lat>=18&&lat<=23&&lng>=-161&&lng<=-154); /*Hawaii*/
};

addEvent(window, 'load', initApplication);
