/* Sibling is enabled if and only if element is empty. */
function disablesSibling(element, sibling) {
	element.sibling = sibling;
	element.previousValue = '';
	
	element.onkeyup = function() {
		if (this.value == '') {
			if (this.previousValue != '') {
				this.sibling.disabled = false;
				this.sibling.removeClassName('disabled');
			}
		} else if (this.previousValue == '') {
			this.sibling.disabled = true;
			this.sibling.addClassName('disabled');
		}
		this.previousValue = this.value;
	}
	
	element.onkeyup();	/* Initial check */
}

/* Validated the form values */
function accomm_validate(form) {
	/* Check that either all date fields are filled out or none of them are */
	if (form.day.value || form.month.value || form.year.value) {
		if (!form.day.value || !form.month.value || !form.year.value) {
			alert('For an availability search, please fill out the day, month and year fields.\n' +
				'For a simple directory search, please clear all of the above fields.\n');
			return false;
		}
	}
	
	/* Check that the 'location' field has *some* letters at least */
	if (form.rls.value.match(/^[^A-Za-z]+$/)) {
		alert('Please enter a valid location');
		return false;
	}
	
	return true;	/* All good */
}

var hidden = null;	// Are bookings search rows currently hidden? (currently unknown)

/* Hide one select box and show the next */
function swapSelectBoxes(sOld, sNew) {
	if (!(sOld instanceof Element)) sOld = $(sOld);
	if (!(sNew instanceof Element)) sNew = $(sNew);
	
	var chosen = sOld.options[sOld.selectedIndex].text;
	sOld.selectedIndex = 0;
	sOld.hide();
	
	for (var i = 0; i < sNew.length; i++) {
		if (sNew.options[i].text == chosen) {
			sNew.selectedIndex = i;
		}
	}
	sNew.show();
	
	sNew.name = sOld.name;
	sOld.name += '_OLD';
}

/* Hide all bookings search rows, and show directory search accommodation type options */
function hideExtended() {
	if (hidden != true) {
		$$('.extended').invoke('hide');
		swapSelectBoxes('bkgTypes', 'dirTypes');
	}
	hidden = true;
}

/* Show all bookings search rows, and show booking search accommodation type options */
function showExtended() {
	if (hidden != false) {
		$$('.extended').invoke('show');
		swapSelectBoxes('dirTypes', 'bkgTypes');		
	}
	hidden = false;
}

var dropdownsActive = new Array();	// What dropdowns currently have values in them?

/* Update currently active dropdowns, and show or hide rows accordingly */
function dropdownsChange(dropdown) {
	dropdownsActive[dropdown.name] = (dropdown.value != "");

	if (dropdownsActive['day'] || dropdownsActive['month'] || dropdownsActive['year']) {
		showExtended();
	} else {
		hideExtended();
	}
}

// Update with initial state of dropdowns (not necessarily blank at start)
dropdownsChange(document.scout.day);
dropdownsChange(document.scout.month);
dropdownsChange(document.scout.year);