jQuery(document).ready(function(){

	function setSecondaryRegions(primary_region) {
		var select_el = jQuery('#id_secondary_regions');
		if (primary_region && primary_region.val() != '') {
			options = jQuery(".region-label:contains('" + primary_region.val() + "') + .subregions").html();
			select_el.html(options);
		} else {
			select_el.html('');
		}
	}

	// On page load...
	setSecondaryRegions(jQuery("#id_primary_region option:selected"));
	// Move catch-all options to the end of the primary region selector.
	var last_options = ['Global', 'Other'];
	for (key in last_options) {
		jQuery("#id_primary_region option:contains('" + last_options[key] + "')").insertAfter("#id_primary_region option:last");
	}

	// Clear search form.
	jQuery('#advanced-search a.search-extra').click(function() {
		jQuery(this).parents().find("input").each(function() {
			jQuery(this).attr('value', '');
		});
		jQuery(this).parents().find("select option").each(function() {
			jQuery(this).attr('selected', '');
		});
		jQuery('#id_primary_region').find("option:first").attr('selected', 'selected');
		setSecondaryRegions();
		return false;
	});

	jQuery('#id_primary_region').change(function() {
		setSecondaryRegions(jQuery(this));
	});

});

