$(document).ready(function() {
	/*$(".mls_main_listing_types").bind('change', function() {
		$.post("/listings/type_change", "type=" + this.value, function(data, statusText) { 
			updateOrReplaceFields("mls_main_listing_types", "mls_sub_listing_types", data);
		});
	});
	
	$(".mls_main_listing_areas").bind('change', function() {
		$.post("/listings/area_change", "area=" + this.value, function(data, statusText) { 
			updateOrReplaceFields('mls_main_listing_areas', "mls_sub_listing_areas", data);
		});
	});*/
	bindAutoSubmit();
});

function bindAutoSubmit(data) {
	$(".mls_main_listing_types, .mls_main_listing_areas").bind('change', function() {
		$('#edit-mls-search-form').attr('value', '');
		$('#mls-search-form').ajaxSubmit({ 
		        target:        '#mls-search-form-container',   // target element(s) to be updated with server response 
		        //beforeSubmit:  showRequest,  // pre-submit callback 
		        success:       bindAutoSubmit,  // post-submit callback 

		        // other available options: 
		        url: Drupal.settings.mls.base_path + 'listings/search_change' // override for form's 'action' attribute 
		        //type: 'xml'        // 'get' or 'post', override for form's 'method' attribute 
		        //dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
		        //clearForm: true        // clear all form fields after successful submit 
		        //resetForm: true        // reset the form after successful submit 

		        // $.ajax options can be used here too, for example: 
		        //timeout:   3000 
		    });
	});
}

function updateOrReplaceFields(parentId, childId, contents) {
	if(contents.length == 0 && $("#" + childId).size() > 0) {
		$("#" + childId).remove();
	} else if(contents.length > 0 && $("#" + childId).size() > 0) {
		$("#" + childId).before(contents).remove();
	} else {
		$("." + parentId).parent().after(contents); 
	}
}
