function injectListings(page) {
	
	// If #ajax_listings div exists
	if ($('#ajax_listings')[0]) {
	
		var category = $('.category_id').text();
  		var t1 = $('.t1_id').text();
	  	
	  	$.ajax({
  		
  			url: "ajax-listings-" + category + "-" + t1 + "-" + page,
  			dataType: "html",
	  		success: function(data) {
			
				$('#ajax_listings').html(data);
			
			}
		
		});
		
	}

}

function textifySelectedCategories() {
	
	var selected = Array();
	var first = "";
	var c = 0;
 	$('.checkbox:checked').each(function() {
   		
   		if (c == 0) {
       		first = $(this).val();
       	}
   		selected.push($(this).val());
   		
   		c++;
 	
 	});
 	
 	var num = c - 1;
 	
 	var text = first;
 	if (num > 0) {
  		text = text + " + " + num + " more categor";
 	}
 	
 	if (num == 1) {
 		text = text + "y";
 	} else if (num > 1) {
 		text = text + "ies";
 	}
 	
 	$('.category_dropdown').val(text);
 	
 	if ($('.category_dropdown').val() == "") {
 		$('.category_dropdown').val("Click to select categories relevant to you");
 	}
	
	$(".category_blocks").hide();

}

$(document).ready(function() {

	// AJAX listings
	injectListings(1);
	
	// AJAX listing pagination
	$(".page_link").live("click", function() {
	
		injectListings($(this).text());
	
	});
	
	textifySelectedCategories();
	
	// Select category dropdown
	$(".category_dropdown").click(function() {
	
		$(".category_blocks").show();
	
	});
	
	$(".category_select_continue").click(function() {
		
		textifySelectedCategories();
		return false;
	
	});
	
	// Set form "spam" field to no
	$("form .spam").val("no");
	
	$(".contact_submit").click(function() {
	
		$(this)/*.attr('disabled', 'disabled')*/.val('Submitting…');
		return true;
	
	});
	
	// Auto populate fields with default values
	$(".auto_value").each(function() {
		
		$(this).attr('defaultVal', $(this).val());
    
    });
      
    // Remove default value on focus
    $(".auto_value").focus(function() {
		
		if ($(this).val() == $(this).attr("defaultVal")){
      		
      		$(this).val("");

    	}
		
	});
	
	// Add default value on blur if value is empty
	$(".auto_value").blur(function() {
		
		if ($(this).val() == ""){
      		
      		$(this).val($(this).attr("defaultVal"));
      		
    	}
		
	});
	
	$(".ac_field").autocomplete("/_ajax/ac_results.php", {
		matchContains: true
	});
  	  	
});
