$(document).ready(function(){

	var country = $("#countrybox");
	var state = $("#statebox");
	var region = $("#regionbox");
	
	if(country && state) {
		var countrySelect = country.find("select").attr("id");
		var stateSelect = state.find("select").attr("id");
		country.find("option[value*='null']").attr("value","null");
		country.find("option[value='AU']").attr("rel","state");
		country.find("option[value='NZ']").attr("rel","state");		
		makeSublist(countrySelect, stateSelect, true);
	}	
	if(state && region) {
		var stateSelect = state.find("select").attr("id");
		var regionSelect = region.find("select").attr("id");
		makeSublist(stateSelect, regionSelect, true);
	}
});


/*
 * Link select boxes
*/
function makeSublist(parent,child) {
	$("body").append("<select style='display:none' id='"+parent+child+"'></select>");
	
	var parentchild = $("#"+parent+child);
	parent = $("#"+parent);
	child = $("#"+child);

	parentchild.html(child.find("option"));
	child.html("<option value='null'></option>");

	if(parent.find("option:selected").attr("value")!="null") {
		var parentValue = parent.attr('value');
		if (parentValue == 'null') {
			child.attr('disabled','true');	
			//child.hide();
		}		
		child.html(parentchild.find(".sub_"+parentValue).clone());
		if (parentValue != 'null') {
			child.prepend("<option value='null'>-----------------------------</option>");
			child.prepend("<option value='null'>Select region</option>");					
			child.attr('disabled','');
			child.show();
		} else {
			child.prepend("<option value='null'></option>");
		}
	} else {
		child.attr("disabled","true");
		//child.hide();
	}
	
	// Update select box event
	parent.bind("updateSelectbox", function(e, level){
		var parentValue = parent.attr('value');
		var newchildhtml = parentchild.find("option[class='sub_"+parentValue+"']");
		if (newchildhtml.length > 0) {
			child.html(newchildhtml.clone());
			if (parentValue == 'null') {
				child.attr('disabled','true');
				//child.hide();
				child.prepend("<option value='null'></option>");
			} else {
				child.prepend("<option value='null'>-----------------------------</option>");
				child.prepend("<option value='null'>Please select</option>");
				child.attr('disabled','');
				child.show();
			}
			child.find("option:first").attr("selected", "selected");
		} else {
			child.html("");
			child.attr('disabled','true');
			//child.hide();
			child.prepend("<option value='null'></option>");
		}
		
	});

	// Update all select boxes when country is changed
    parent.change(function () {
		var level = $(this).find("option:selected").attr("rel");
		$(this).trigger("updateSelectbox", [level]);
		if ($(this).parent("div").attr("id")=="countrybox") {
			$("#statebox select").trigger("updateSelectbox", [level]);
		}
    });

}