jQuery(document).ready(function($) {

	//Make the loans sortable
	$("#sort_loans").sortable({
		revert: true,
		axis: 'y',
		containment: 'parent',
		zIndex: 10,
		opacity: 50,
		placeholder: "hover",
		handle: 'div.result_header',
		update: function(e,ui) {
		}
	});

	//Make the loans closable
	$("a.discard").click(function(){

		--no_loans;

		var loan_detail = 'list_' + $(this).attr("id");

		var loan_id = $(this).attr("id").replace('discard','');

		//document.getElementById(loan_detail).innerHTML = '';
		
		var loan_list_element = document.getElementById("sort_loans");
		var loan_detail_element = document.getElementById(loan_detail);
		
		loan_detail_element.innerHTML='';
		
		loan_list_element.removeChild(loan_detail_element);
		
		//document.getElementById(loan_detail).display = 'none';

		if(no_loans == 1){
			document.getElementById('results').innerHTML = 'Your <strong>' + no_loans + '</strong> result';
			document.getElementById('results_count').innerHTML = 'There is <a href="#results">' + no_loans + ' result</a> matching your criteria.'
		}else{

			document.getElementById('results').innerHTML = 'Your <strong>' + no_loans + '</strong> results';
			document.getElementById('results_count').innerHTML = 'There are <a href="#results">' + no_loans + ' results</a> matching your criteria.'
		}

		$.getJSON("/unset_result.html?id=" + loan_id);
		
		return false;

	});

	//Toggle to closed in the first instance if we have loans
	if (typeof(errors) == 'boolean' && errors == false){
		$("#search_form").toggle();
	}

	$("#search_toggle").click(function(){
		$("#search_form").toggle();
	});

});


