function showhide_other() {
	var our_name = $(this).attr('id');

	var other = $("#other"+our_name);
	var other_input = other.find("input");
	if ($(this).val() === 'other') {
		other_input.val(other.attr("hidden_value"));
		other.show();
	}
	else {
		other.attr("hidden_value", other_input.val());
		other_input.val('');
		other.hide();
	}
}

$(function() {
	$('#personaltogglecontainer').show();

	$('#business_toggle').click(function() {
		var get_old_value = function() {
			$(this).val($(this).attr('oldvalue'));
		}
		$('#businesstype').val("");
		$('.businessformelement:hidden select, .businessformelement:hidden input').each(get_old_value);
		$('.businessformelement').show();
	});

	$('#personal_toggle').click(function() {
		var set_old_value = function() {
			$(this).attr('oldvalue',$(this).val());
			$(this).val('');
		}
		$('.businessformelement:visible select, .businessformelement:visible input').each(set_old_value);
		$('#businesstype').val($('#businesstype option:contains("Personal")').val());
		$('.businessformelement').hide();
	});

	if ($('#businesstype option:selected').text() == 'Personal') {
		$('#personal_toggle').click();
	}


	var target_options = { 'title': $('#usertitle option').clone(), 'department':$('#userdepartment option').clone() };

	$('#businesstype').change(function() {
		var business_type = $(this).val();
		var targets = ['title', 'department'];

		for (var target_index in targets) {
			var target = targets[target_index];
			var prev_selected = $("#user"+target).val();

			//remove all options from select box not including "choose xxx" and "other"
			$("#user"+target+" option[value!=''][value!='other']").remove();

			target_options[target].each(function ( ) {
				for (index in business_type_associations[target][business_type]) {
					if ($(this).val() == business_type_associations[target][business_type][index]) {
						$("#user"+target).append($(this).clone());
					}
				}
			});

			//set the select box to the value of the old selection if it exists
			$('#user'+target).val(
				$('#user'+target+' option[value='+prev_selected+']').val()
			);
		}
	});
	$('#businesstype, #userdepartment, #usertitle').change(showhide_other).change();
});

