// Globals
var locationChangeTimeout = null;
var DEFAULT_ZOOM = 3;
var ZOOM_IN      = 13;
var DEFAULT_LOCATION = null;
var BASE_URL = null;
var IS_LOADING_LOCATION = false;

var _lat_lng_loc = 'Switch to latitude/longitude input instead';
var _address_loc = 'Switch to generic address input instead';

initApplication = function(_event) {
	window.IO = new Dialog();
	BASE_URL = 'http://'+window.location.host+'/deaggint/2008'
	window.application = document.getElementById('application');
	addClass(application, 'enabled');
	// Prevent user from submitting by hitting enter key.
	$('#frm_app').submit(function(_event) {return false;});

	initAppControls();
	initAppMap();
	initAppFooter();
};

initAppControls = function() {
	// Remove the default 'compute' button and re-size the form to accomodate.
	$('#btnGo').remove();
	$('#frm_app').css({height:'16em'});

	// Check if the Google Map is shown
	if (GBrowserIsCompatible()) {
		// The Google Map is shown, so change 'latitude' and 'longitude' to
		// 'location'. This allows for a much more free-form input. Add handlers.
		$('#location').hide(); //$('#location').removeClass('oneline');
		$('#location').after($(
			'<li id="coords">' +
			'<label for="location_input">Address</label>' +
			'<input type="text" name="location_input" id="location_input" />' +
			'</li>'
		));
		$('#location').before($(
			'<li id="loc_coord_toggle">' +
			'<a href="javascript:void(null);" onclick="toggleLocation();">' +
				_lat_lng_loc +
			'</a></li>'
		));
		$('#latitude').keypress(function(_event){locKeyEvent(_event);});
		$('#longitude').keypress(function(_event){locKeyEvent(_event);});
		$('#location_input').keypress(function(_event){locKeyEvent(_event);});

		$('#latitude').blur(function(_event) { locationInputChanged(); });
		$('#longitude').blur(function(_event) { locationInputChanged(); });
		$('#location_input').blur(function(_event) {
				locationInputChanged($('#location_input').text()!='');
			});
	}
};

locKeyEvent = function(_event) {
	IS_LOADING_LOCATION = true;
	_event = getEvent(_event);
	var c = _event.charCode || _event.keyCode;
	if (locationChangeTimeout) { clearTimeout(locationChangeTimeout); }
	if (c == 13) { // Immediately trigger if user presses 'Enter'
		locationInputChanged(true);
	} else { // Wait a bit, then assume user is done and update location
		locationChangeTimeout =
		setTimeout('locationInputChanged()', 2000);
	}
};

toggleLocation = function() {
	if ($('#loc_coord_toggle a').text() == _lat_lng_loc) {
		$('#location').show();
		$('#coords').hide();
		$('#loc_coord_toggle a').text(_address_loc);
	} else {
		$('#coords').show();
		$('#location').hide();
		$('#loc_coord_toggle a').text(_lat_lng_loc);
	}
};

locationInputChanged = function(_notifyUser) {
	_notifyUser = _notifyUser||false;
	var zoom = (map.getZoom() == DEFAULT_ZOOM)?ZOOM_IN:map.getZoom();
	if ( $('#loc_coord_toggle a').text() == _lat_lng_loc) {
		// Lat/Lng text is visible so we are currently searching by address
		var locationStr = $('#location_input').val();
		window.geocoder.getLatLng(locationStr, function(_point) {
			IS_LOADING_LOCATION = false;
			if (!pointIsValid(_point)) {
				if (_notifyUser) {
					window.IO.alert(
						'The input location is out of range. Please select a ' +
						'location within the United States and try again.'
					);
				}
				_point = DEFAULT_LOCATION;
				zoom = DEFAULT_ZOOM;
			}
			$('#latitude').val(_point.lat());
			$('#longitude').val(_point.lng());
			window.marker.setLatLng(_point);
			map.setCenter(_point, zoom);
		});
	} else {
		// Address text is visible so we are currently searching by lat/lng
		var point = new GLatLng(
			$.trim($('#latitude').val()),
			$.trim($('#longitude').val())
		);
		// Since the latitude/longitude values are separate fields, the user may
		// have changed one but not updated the other yet. Don't warn and don't
		// reset, let the user fix the problem on their own if the interem point
		// is not valid. We will do a final validation before submitting the
		// point back to the server.
		if (pointIsValid(point)) {
			window.marker.setLatLng(point);
			map.setCenter(point, zoom);
		}
		IS_LOADING_LOCATION = false;
	}
};

pointIsValid = function(_point) {
	if (!_point) return false;
	var lat = _point.lat();
	var lng = _point.lng();
	return (lng >= -125.0 && lng <= -65.0 && lat >= 24.6 && lat <= 50);
};

initAppMap = function() {
	if (GBrowserIsCompatible()) {
		DEFAULT_LOCATION = new GLatLng(38.5, -100.0);
		var mapdiv = document.getElementById('mapdiv');
		var map    = new GMap2(mapdiv);
		window.map = map;
		map.setCenter(DEFAULT_LOCATION, DEFAULT_ZOOM, G_PHYSICAL_MAP);
		map.addControl(new GSmallMapControl());

		window.geocoder = new GClientGeocoder();
		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);
		window.marker = new GMarker(DEFAULT_LOCATION, {
				icon:_icon,
				title:'Current Location',
				clickable:false,
				draggable:true,
				bouncy:true,
				autoPan:true
			});
		map.addOverlay(window.marker);

		GEvent.addListener(map, 'zoomend', function(_old, _new) {
				if (_new > 13) { this.setMapType(G_HYBRID_MAP); }
				else { this.setMapType(G_PHYSICAL_MAP); }
			});
		GEvent.addListener(marker, 'dragend', function(_point) {
			var zoom = (window.map.getZoom() == DEFAULT_ZOOM)?
				ZOOM_IN:window.map.getZoom();
			if (!pointIsValid(_point)) {
				var lat = Math.round(_point.lat() * 100) / 100;
				var lng = Math.round(_point.lng() * 100) / 100;
				window.IO.alert('The location (' + lat + ', ' + lng + 
						') is outside the bounds of the U.S. Please try ' +
						'again.', {title:'Location Out Of Bounds'}
				);
				window.map.setCenter(DEFAULT_LOCATION,DEFAULT_ZOOM,
						G_PHYSICAL_MAP);
				window.marker.setLatLng(DEFAULT_LOCATION);
			} else {
				$('#latitude').val(_point.lat());
				$('#longitude').val(_point.lng());
				window.map.setCenter(_point, zoom);
			}
		});
		// Create a control to slide the map up and down (hide/show)
		$('#appControls').append($(
				'<a href="javascript:void(null);" title="Hide/Show Map" ' +
						'id="toggleMap">(Hide Map)</a>'
			));
		$('#toggleMap').click(function() {
				if ($(this).text() == '(Hide Map)') {
					// Map is visible, hide it
					$('#mapdiv').slideUp();
					$(this).text('(Show Map)');
				} else {
					// Map is hidden, show it
					$('#mapdiv').slideDown();
					$(this).text('(Hide Map)');
				}
			});
		$('#toggleMap').click();
	} else {
		window.IO.alert('Your browser is not compatible with Google Maps.');
	}
};

initAppFooter = function() {
	// Add the new 'Compute' button
	$('#appFooter').append(
		$('<img id="btnCompute" src="images/btnCompute.gif" alt="Compute" />')
	);
	// Add a handler to perform the action
	$('#btnCompute').click(function() {
		// Show the "clicked" image
		$('#btnCompute').attr('src', 'images/btnCompute_down.gif');

		computeDeaggregation();

	});

	// Add the output list stub
	$('#appOutput').append($('<ul id="appOutputList"></ul>'));
};

computeDeaggregation = function() {
	if (IS_LOADING_LOCATION) {
		setTimeout('computeDeaggregation()', 1000);
		return;
	}

	if ( $('#latitude').val() != window.marker.getLatLng().lat() ||
	    $('#longitude').val() != window.marker.getLatLng().lng() ) {
		window.IO.alert(
			'The current location is out of range. Please update the ' +
			'location and try again.', {title:'Location Error'}
		);
		return;
	}
	// Show a loading screen
	window.IO.showLoading('Computing Results');

	// Build a GET request
	var name      = $('#name').val();
	var latitude  = window.marker.getLatLng().lat();
	var longitude = window.marker.getLatLng().lng();
	var percent   = $('#percent').val();
	var years     = $('#years').val();
	var sa        = $('#sa').val();
	var gmpe      = $('input[name="gmpe"]:checked').val();
	var vs30      = $('#vs30').val();

	var url = BASE_URL + '/application.php?';
	url += 'name=' + name;
	url += '&latitude=' + latitude;
	url += '&longitude=' + longitude;
	url += '&percent=' + percent;
	url += '&years=' + years;
	url += '&sa=' + sa;
	url += '&gmpe=' + gmpe;
	url += '&vs30=' + vs30;

	$.get(url, function(_response) {
		var status = $('status', $(_response)).text();
		if (status == 0) {
			var item = document.createElement('li');
			var downloads = '';
			$('link', $(_response)).each(function() {
				downloads += '<a href="' + $(this).attr('url') + '" title="' +
						$(this).attr('title') + ' ' + $(this).attr('size') + 
						'" target="appOutputWindow">' + $(this).attr('display') + 
						'</a>';
			});
			downloads = downloads.replace(/></g, '>&nbsp;|&nbsp;<');
			var itemContentStr = '<span class="downloads">[ ' + downloads +
					' ]</span>';
			itemContentStr += '<span class="name">' +
					$('name', $(_response)).text() + '</span>';
			itemContentStr += '<span class="meta">' + 
					$('metadata', $(_response)).text() + '</span>';

			$(item).append($(itemContentStr));
			$('#appOutputList').prepend(item);
			window.IO.closeDialog();
		} else {
			// Error, just alert the error message.
			var ul = document.createElement('ul');
			addClass(ul, 'error');
			$(ul).append($($('metadata', $(_response)).text()).html());
			window.IO.closeDialog();
			window.IO.alert(ul,{ctype:'text/html',title:'Error'});
		}
		$('#btnCompute').attr('src', 'images/btnCompute.gif');
	});
};

addEvent(window, 'load', initApplication);
