/* 
 * Dependent (Cascading) Dropdown Selects
 * www.ajaxray.com
 * http://www.ajaxray.com/blog/2007/11/08/jquery-controlled-dependent-or-cascading-select-list-2/
 *
 * Version 2.0
 * 
 */
 
 /**
 	USAGE
	--------------
	JAVASCRIPT:
	// Params: parent, child, isSubselectOptional (true adds default value '-- Select --'), childVal (default selected option)
	$(document).ready(function(){
 		makeSublist('child','grandchild', false, '');	// level 2
 		makeSublist('parent','child', false, '');		// level 1
 	}
	--------------
	XHTML:
	// child class = sub_[value of corresponding parent]
	<select id="parent" name="select0">
		<option value="1">Parent Choice 1</option>
		<option value="2">Parent Choice 2</option>
		<option value="3">Parent Choice 3</option>
	</select>
    <select id="child" name="select1">
		<option class="sub_1" value="6">Child Choice 1</option>
		<option class="sub_2" value="7">Child Choice 2</option>
		<option class="sub_3" value="8">Child Choice 3</option>
	</select>
	<select id="grandchild" name="select2">
		<option class="sub_6" value="100">Grandchild Choice 1</option>
		<option class="sub_7" value="101">Grandchild Choice 2</option>
		<option class="sub_8" value="102">Grandchild Choice 3</option>
	</select>	
 */

function makeSublist(parent,child,isSubselectOptional,childVal){
	$("body").append("<select style='display:none' id='"+parent+child+"'></select>");
	$('#'+parent+child).html($("#"+child+" option"));
	
		var parentValue = $('#'+parent).attr('value');
		$('#'+child).html($("#"+parent+child+" .sub_"+parentValue).clone());
	
	childVal = (typeof childVal == "undefined")? "" : childVal ;
	$("#"+child+' option[@value="'+ childVal +'"]').attr('selected','selected');
	
	$('#'+parent).change( 
		function()
		{
			var parentValue = $('#'+parent).attr('value');
			$('#'+child).html($("#"+parent+child+" .sub_"+parentValue).clone());
			if(isSubselectOptional) $('#'+child).prepend("<option value='none'> -- Select -- </option>");
			$('#'+child).trigger("change");
                        $('#'+child).focus();
		}
	);
}
