var BASE_URL   = '/earthquakes/dyfi/inc/locations';
var REGION_URL = BASE_URL + '/region/';
var CITY_URL   = BASE_URL + '/city/';
var ZIP_URL    = BASE_URL + '/zip/';

initForm = function(_event) {
	initLocationForm(_event);
	initQuestionnaireForm(_event);
};

initLocationForm = function(_event) {
	// Remove the update buttons
	$('.btnUpdate').remove();

	// Select U.S. for default country.
	$("#selcountry option[value='000222']").attr('selected','selected');

	// Hide the submit button
	$("#frmCiimLocation input[type='submit']").hide();
	
	// Bind the events...
	$('#selcountry').change(selCountryChanged);
	$('#selregion').change(selRegionChanged);
	$('#inZip').keyup(function(_event) {
		if(this.value.length == 5) {
			$("#frmCiimLocation input[type='submit']").show();
		} else {
			$("#frmCiimLocation input[type='submit']").hide();
		}
	});

	$('#frmCiimLocation').submit(updateCiimLocation);
};

selCountryChanged = function(_event) {
	var newCountryId = this[this.selectedIndex].value;

	$('#selcity').parent('li').hide();
	$("#frmCiimLocation input[type='submit']").hide();

	if(newCountryId == '000222') {
		// User selected U.S., so show the zip code input field.
		$('#selregion').parent('li').hide();
		$('#inZip').parent('li').show();
	} else {
		// User selected non-U.S., so show the region sub-select box.
		// Hide and clear zip code
		$('#inZip').parent('li').hide()
		$('#inZip').val(''); 

		// Update the region select box contents.
		var url = REGION_URL + newCountryId + '.inc.html';
		$.get(url, function(_response) {
			$('#selregion').replaceWith(_response);
			$('#selregion').change(selRegionChanged);
			$('#selregion').parent('li').show();
			// Always trigger the change so if desired region is selected by 
			// default then it saves user two clicks (to change off the desired 
			// region, then change back. This seems like best way to interact 
			// with user.
			$('#selregion').change();
		});
		
	}
};

selRegionChanged = function(_event) {
	var url = CITY_URL + this[this.selectedIndex].value + '.inc.html';
	$.get(url, function(_response) {
		$('#selcity').replaceWith(_response);
		$('#selcity').parent('li').show();
		$("#frmCiimLocation input[type='submit']").show();
	});
};

updateCiimLocation = function(_event) {

	// Set the location header identifier
	if($('#inZip').val() != '') {
		// Zip code is set, so look up name
		var url = ZIP_URL + '0' + $('#inZip').val() + '.inc.html';
		$.get(url, createJumpBack);

		// Set the zip code in CIIM and clear others.
		$('#ciim_zip').val($('#inZip').val());
		$('#ciim_address').val($('#inAddr').val());
		$('#ciim_country').val('');
		$('#ciim_region').val('');
		$('#ciim_city').val('');

	} else {
		// City must have been set
		var cityElem = document.getElementById('selcity');
		var cityOpt  = cityElem[cityElem.selectedIndex];
		if(cityOpt.value == 'undefn') {
			alert('You must specify a location to continue.');
			return cancelEvent(_event);
		}

		// Construct a clickable option to toggle back the location selectors
		createJumpBack($(cityOpt).text());

		// Set the country/region/city and clear the zip
		$('#ciim_zip').val('');
		$('#ciim_address').val('');

		var country = document.getElementById('selcountry');
		var region  = document.getElementById('selregion');
		var city    = document.getElementById('selcity');

		$('#ciim_country').val(country[country.selectedIndex].value + ' ' +
			country[country.selectedIndex].innerHTML);
		$('#ciim_region').val(region[region.selectedIndex].value + ' ' +
			region[region.selectedIndex].innerHTML);
		$('#ciim_city').val(city[city.selectedIndex].value + ' ' +
			city[city.selectedIndex].innerHTML);
	}

	// Always set the time option if an anknown event
	if ($('#network').val() == 'unknown' && $('#code').val() == 'unknown') {
		$('#ciim_time').val($('#evttime').val());
	}

	// Show the questionnaire form
	$('#frmCiim').show();

	// Hide the location form
	$('#frmCiimLocation').hide();

	// Stop default action
	return cancelEvent(_event);
};


createJumpBack = function(_display) {
	var a = $('<a href="javascript:void(null);" ' +
			'title="Click to change location">'+_display+'</a>');
	$(a).click(function(_event) {
		$(this).replaceWith('<b>&nbsp;</b>');
		$('#frmCiim').hide();
		$('#frmCiimLocation').show();
	});

	$('#ciim_header b').replaceWith(a);
};

initQuestionnaireForm = function(_event) {

	// Hide the conditional options.
	$('.other').hide();
	$('#fldSituation_structure').parent('div').hide();

	// Alternate field row colors
	$('#frmCiim fieldset').each(function() {
		$('#' + $(this).attr('id') + ' ol > li:odd').addClass('even');
	});
	$('#submit_questionnaire').removeClass('even');

	// Hide each fieldset individually
	$('#frmCiim fieldset').hide();

	// But unhide the first one...
	$('#frmCiim_fldSituation').show();

	//------------------------- Add the event handlers ------------------------//

	// Toggle structural conditional fields.
	$('#fldSituation_situation').change(function() {
		var value = this[this.selectedIndex].value;
		if(value=='inside') {
			$('#fldSituation_structure').parent('div').show();
		} else {
			$('#fldSituation_structure').parent('div').hide();
		}
	});

	// Toggle conditional 'other' fields.
	$("option[value='other']").parent('select').change(function(_event) {
		var value = this[this.selectedIndex].value;
		if(value=='other') {
			$(this).siblings('.other').show();
		} else {
			$(this).siblings('.other').hide();
		}
	});

	$('#feltYes').one('click',function(){$('.nextLink').removeClass('hidden');});
	$('#feltNo').one('click',function(){$('.nextLink').removeClass('hidden');});

	// Add the form paging controls.
	$('#frmCiim > fieldset').each(function() {
		// Don't add form controls to the always-hidden fieldset
		if($(this).attr('id') == 'ciim_hidden') { return true; }

		var prevFieldSet = $(this).prev('fieldset');
		var nextFieldSet = $(this).next('fieldset');

		var backText = $('#back').text();
		var nextText = $('#next').text();

		// Don't add 'back' link to first fieldset
		if( $(prevFieldSet).attr('id') != 'ciim_hidden' ){ 
			// Create and append a link to view previous fieldset.

			var prevLink = $('<a href="javascript:void(null);" ' +
					'title="View Previous Page" class="backLink">'+backText+'</a>');

			$(prevLink).click(function(_event) {
				$(this).parent('fieldset').hide();
				$(this).parent('fieldset').prev('fieldset').show();
				return cancelEvent(_event); // Just in case...
			});

			$(this).append(prevLink);
		}

		// Don't add a 'next' link to last fieldset.
		if( $(nextFieldSet).length != 0 ) {
			
			var nextLink = $('<a href="javascript:void(null);" title="Next Page" '+
					'class="hidden nextLink">'+nextText+'</a>');

			$(nextLink).click(function(_event) {
				$(this).parent('fieldset').hide();
				$(this).parent('fieldset').next('fieldset').show();
				return cancelEvent(_event); // Just in case...
			});

			$(this).append(nextLink);
		}

	}); // END: each(fieldset)

};


//----- This can be removed once lib.js is corrected.

cancelEvent = function(_event) {

	if(_event.preventDefault) {
		_event.preventDefault();
	}

	_event.returnValue = false;

	return false;
};
// --------------------------------------------------

addEvent(window, 'load', initForm);

