/**
 * Unobtrusively set up AJAX county controls
 */
$( function() {

	// unhide the county controls
	$("select[name=county_id]").css( "display", "inline" );

	// initialize the county controls at page load
	// ...or not
	//$("select[name=state_id]").each( _updateCounties );
	
	// update the county controls when the state is changed
	$("select[name=state_id]").change( _updateCounties );

	function _updateCounties() {
	
		var $stateId = $(this);
		var $form = $stateId.parents("form");
		var $countyId = $( "select[name=county_id]", $form );
		var $countyBusy = $( ".county_busy", $form );
		
		if ( $countyId.length ) {
		
			if ( $stateId.val() === "" ) {
				$countyId.val("");
				$countyId.attr("disabled","disabled");
			} else {
				$countyId.attr("disabled","disabled");
				$countyBusy.css("visibility","visible");
				$.ajax( {
					url: "/ajax.php",
					method: "POST",
					dataType: "json",
					data: {
						fn: "getCountiesByState",
						state_id: $stateId.val()
					},
					success: function( resp ) {				
						if ( resp.success ) {
							$countyId.empty();
							var $emptyOption = $("<option></option>");
							$countyId.append( $emptyOption );
							$.each( resp.data, function() {
								var $option = $("<option></option>");
								$option.attr( "value", this.id );
								$option.text( this.name );
								$countyId.append( $option );
							} );
							$countyId.removeAttr("disabled");
						} else {
							// TODO: handle errors
						}
					},
					error: function() {
						// TODO
					},
					complete: function() {
						$countyBusy.css( "visibility", "hidden" );
					}
				} );
			}
			
		}
	
	}

} );

