var currentLevel = 1;

function updateCategories(event) {
	var level = event.target.name.split('.')[1];
	var value = parseInt(event.target.value);
	if (level == 3) return; // don't need to update anything if level 3 changed.
	currentLevel = level;
	show(level, value);
	updateOptions(level, value);
}

function show(level, value) {
	// Enables / hides the appropriate <select> elements based
	// on the selection in the parent <select> element
	if(level==1) {
		if (value==-1) { $('category.2').hide(); $('category.3').hide(); } 
		else { $('category.2').show(); }
	} else 	if(level==2) {
		if (value==-1) { $('category.3').hide(); }
		else { $('category.3').show(); }
	}	
}

function updateOptions(level, value) {
	if (value < 0) return;
	new Ajax.Request('/business-directory/load-category/' + value + '/',{
		method: 'get',
		onComplete: handleJSON
	});
}

function handleJSON(response) {
	// Determine which <select> to update.
	var level = currentLevel;
	var select = null;
	if(level == 1) select = $('category.2');
	else if (level == 2) select = $('category.3');
	else return;
	data = response.responseJSON;
	select.childElements().each(function(el) { el.remove(); });
	if (level==1) {
		// Also clear out <select> #3 and remove it
		$('category.3').childElements().each(function(el) { el.remove(); });
		$('category.3').hide();
	}
	var o = document.createElement('option');
	o.appendChild(document.createTextNode('-- All categories --'));
	o.setAttribute('value', '-1');
	select.appendChild(o);	
	data.each(function(key) {
		var o = document.createElement('option');
		o.appendChild(document.createTextNode(key[1]));
		o.setAttribute('value', key[0]);
		select.appendChild(o);
	});
}