
var namelock = 0;
    
$(document).ready(function() {

	// Select all checkboxes button
	$("#cbSelectAll").live('click', function(){
		
		if ($(this).closest(".searchResults").find("ul li input").length + watchlist.length > 30){
			$(this).attr('checked', false);
			alert('Limit: 30');
		} else {
			if ($(this).is(':checked')){
				$(this).closest(".searchResults").find("ul li input:not(:checked)").click();
			} else {
				$(this).closest(".searchResults").find("ul li input:checked").click();
			}
		}
	
	});
    
    // Need to limit the initial watchlist check to just the edit panel
    checkWatchlist('#pnlEditReport');
    
    $("#tbPasswordOverlay").focus(swapPasswordField);
    $("#tbUserName").focus(clearUsername);
    
    // Hook in creating a report
    $(".create-report").click(function(){
    
    	// Disable the registration fields if they are there
    	
    	$("#ReportCreateForm").submit();
    	
    	
    	return false;
    
    });
    
    // Selecting the measure_set from the dropdown triggers a characteristic search
    $(".ddHospitalMeasures.select ul li").click(function(){
    	
    	filterSearchResults($(this));
    	
    });
    
    // Selecting a state from the dropdown triggers two ajax calls
    $(".ddState.select ul li").click(function(){
    	var state = $(this).html();
		
		// Make ajax call to load up the selectors
		$(this).parent().parent().parent().next().load('/reference_entities_hospitals/characteristics_state/' + state, null,
			function(){
				attachCustomSelectEvents();
			}
		
		);
		filterSearchResults($(this));
    });
    
    $("#btnLogout[value='LOG-IN']").click(function(){
    	// Clear out any need to validate registration fields
    	$("#pnlSaveReport input").remove();
    	return true;
    });
        
    $(".tbHospitalName").click(function(){
    	$(this).val('');
    	$(this).next().hide("slow");
    });
    
    /* !Hospital search by name */
    $(".tbHospitalName").keyup(function(){
    	// Add to the locking
    	if (($(this).val()).length > 2){
    		namelock++;	
    	
    		//console.log(namelock);
    		//console.log($(this));
    		// Queue up a request
    		setTimeout("nameSearch('" + $(this).attr('id') + "')", 500);
    		//nameSearch($(this).attr('id'));
    		// Check off items that are loaded that are in the watchlist
    		//checkWatchlist();
    	}
    });
    
    $(".pnlResults").mouseleave(function(){
    	$(this).hide("slow");
    });
    
    // Add to selected hospitals
    $(".hospitalCompareCheckbox.hospital").live('click', function(){
    	
    	// Cannot have more than 30 items in the watchlist
    	if (watchlist.length >= 30){
    		
    		return false;
    	}
    
    	// Get the hospital name
    	var name = $(this).next().html();
    	
    	// Get the hospital id
    	var id = $(this).val();
    	
    	// Get the state 
    	var state = $(this).attr('state');
		//console.log(state);
    	
    	// Create a new selected hospital if the click is a "check"
    	if ($(this).is(':checked')) {
    		//console.log('unchecked');
    		// Add this selection to the selections list
    		$(".ctSelections ul").append('<li><input class="CompareEntity-' + id + '" type="hidden" value="' + id + '" name="data[ReferenceEntitiesHospital][id][]"/>' + name + ' <span class="sprIcon sprDelete" val="' + id + '"><img src="/images/iconDelete.png" /></span></li>');
			$("#ctSelectionsHospitalCount").html();
			// Add to watchlist variable
			watchlist.push(parseInt(id));
			
			// Show the state average corresponding to this entity
			if (state){
				$(".cbStateAvg" + state).parent().show();
			}
			
 			// grab all current hrrs and see if we match one
 			hrrs = $(this).closest(".reportAdmin").find(".selected-hrrs li").hasClass("active");
 			
 			if (!hrrs || hrrs.length < 3){
				// If we have less than 3 HRRS lookup and add an HRR based on this entity
				hrr_code = $(this).attr('hrr');
 				//console.log(hrr_code);
				$(".selected-hrrs li input[hrr=" + hrr_code + "]").parent().show();
				
			}
			
			// grab all the current systems and see if we match one
			hsas = $(this).closest(".reportAdmin").find(".selected-hsas li").hasClass("active");
			
 			if (!hsas){
				// Add an HRR based on this entity
				hsa_code = $(this).attr('hsa');
			
 				//console.log(hrr_code);
				$(".selected-hsas li input[hsa=" + hsa_code + "]").parent().show();
				
			}
    	} else {
    		// Delete the selected hospital if the click is an "uncheck"\
    		//console.log($(".ctSelections ul .CompareEntity-" + id));
    		$(".ctSelections ul .CompareEntity-" + id).parent().remove();
    		
    		// Remove from watchlist
    		removeItem(watchlist, id);
    	}
    	// show the user how many hospitals he/she has selected
    	updateCtSelectionsHospitalsCount();
    	//console.log(watchlist);
    });
 
 
 	// Remove hospitals from comparison list
 	$(".sprDelete").live('click', function(){
 		id = $(this).attr('val');
 		
 		// Remove from array
 		removeItem(watchlist, id);
 		
 		updateCtSelectionsHospitalsCount();
 		// Remove from screen
 		var nextAll = $(this).closest("li").nextAll("li");
 		$(this).closest("li").remove();
 		nextAll.css("position", "static").css("position", "relative");
 	
 	});
 	
 	// Select by location and characteristics
 	$(".selectedCounty.select li").live('click', function(){
 	        filterSearchResults($(this));
 		}
 	);
 	$(".selectedHealthSystem.select li").live('click', function(){
 			filterSearchResults($(this));
 		}
 	);
 	$(".selectedReferralRegion.select li").live('click', function(){
 			filterSearchResults($(this));
 		}
 	);
 	$(".radioGroup input[name='hospitalCriteria']").live('click', function(){
 	        var rg = $(".radioGroup");
 	        var curVal = rg.data("selectedRadio");
 	        var newVal = $(this).val();
 	        if (newVal == curVal) return;
 	        rg.data("selectedRadio", newVal);
 	    	filterSearchResults($(this));
 	});
 	$(".ddBedCount.select ul li").live('click', function(){
 			filterSearchResults($(this));
 	});
 	$(".ddOwnership.select ul li").live('click', function(){
 			filterSearchResults($(this));
 	});
 	$(".ddOwnership.select ul li").live('click', function(){
 			filterSearchResults($(this));
 	});
 	$(".ddTeachingHospitals").live('click', function(){
 			filterSearchResults($(this));
 	});
 	$(".ddSafetyNet").live('click', function(){
 			filterSearchResults($(this));
 	});
 	$(".ddAcademicHealthCenters").live('click', function(){
 			filterSearchResults($(this));
 	});
 	
 	// When a HRR state is selected 
 	$(".ddStateAvgState ul li").live('click', function(){
 		// Show the selected state average checkbox
 		state = $(this).html();
 		// Show the state average corresponding to this entity
		if (state){
			$(".cbStateAvg" + state).attr("checked", "checked").parent().show();
		}
 	});
 	
 	// When a hrr benchmark state is clicked, return the list of hrrs for that state
 	$(".ddStateHrr ul li").live('click', function(){
 		// Grab the state name
 		state = $(this).html();
 		
 		if (state != 'State'){
 		    $(this).parent().parent().next().load('/reference_entities_hospitals/hrrs_state/' + state);
 		}
 	
 	});
 	
 	// Add a hrr to the list
 	$(".ddReferral ul li").live('click', function(){
 		hrr_id 		= $(this).attr('value');
 		hrr_name 	= $(this).html();
 		
 		// grab all current hrrs and see if we match
 		$(this).closest(".referralRegions").find(".selected-hrrs li input[value=" + hrr_id + "]").attr("checked", "checked").parent().show();
 		
 	});
 	 	
 	// When a hsa benchmark state is clicked, return the list of hsas for that state
 	$(".ddStateHsa ul li").live('click', function(){
 		// Grab the state name
 		state = $(this).html();
 		
 		if (state != 'State'){
 			$(this).parent().parent().next().load('/reference_entities_hospitals/hsas_state/' + state);
 		}
 	
 	});
 	
 	// Add a hrr to the list
 	$(".ddSystem ul li").live('click', function(){
 		hsa_id 		= $(this).attr('value');
 		hsa_name 	= $(this).html();
 		
 		// grab all current hrrs and see if we match
 		$(this).closest(".hospitalSystems").find(".selected-hsas li input[value=" + hsa_id + "]").parent().show();
 		
 	});
 	// Save rpoert button
 	$(".editSaveReport").click(function(){
 		$(this).closest("form").submit();
 	});
});

/** 
 * Name search with timeout delay
 */
function nameSearch(id){
	
	// Dequeue a call, if we're at 0 then load
	namelock--;
    //console.log(namelock);
	//console.log(id);
	var oName = $('#' + id);
	
	if (namelock == 0){
		oName.next().show();
		oName.next().load('/reference_entities_hospitals/name_search/' + encodeURI(oName.val()), null, staggerCheckWatchlist());
		
	}
	//checkWatchlist('.ctSearchByName');
	//console.log('nameSearch:' + id);
}

/**
 * Filter entities 
 */
function filterSearchResults(oBase){
	// Read the state
	
	var conditions = {
		"data[Report][measure_set]" : '',
		"data[Report][state]" 		: '',
		"data[Report][county_name]"	: '',
		"data[Report][aha_sys_id]"	: '',
		"data[Report][hrr_code]"	: '',
		"data[Report][beds]"		: ''
	};
	
	state = oBase.closest(".ctSearchOptions").find(".ddState.select").attr("value");
	if (state != "null"){
		//console.log(state);
		conditions["data[Report][state]"] = state;
	}
	
	// Read the county if applicable
	radioSelected = oBase.closest(".ctSearchOptions").find("input[name='hospitalCriteria']:checked").val();
	//console.log(radioSelected);
	if (radioSelected == 'county'){
		var county = oBase.closest(".ctSearchOptions").find(".selectedCounty").attr("value");
		if (county && county != "null"){
			conditions["data[Report][county_name]"] = county;
		}
	} else if (radioSelected == 'healthSystem'){
	
		var hss = oBase.closest(".ctSearchOptions").find(".selectedHealthSystem").attr("value");
		if (hss && hss != "null"){
			conditions["data[Report][aha_sys_id]"] = hss;
			delete conditions["data[Report][state]"];
			oBase.closest(".ctSearchOptions").find(".ddState.select").attr('value', 'null');
			oBase.closest(".ctSearchOptions").find(".ddState.select em").html('State...');

		}
	} else if (radioSelected == 'referralRegion'){
	
		var hrr = oBase.closest(".ctSearchOptions").find(".selectedReferralRegion").attr("value");
		if (hrr && hrr != "null"){
			conditions["data[Report][hrr_code]"] = hrr;
		}
	}
	
	// Filter by number of beds switch
	var beds = oBase.closest(".ctSearchOptions").find(".ddBedCount.select").attr("value");
	if (beds != "null"){
		conditions["data[Report][beds]"] = beds;
	}
	// Filter by Type of Ownership listing
	var ownership = oBase.closest(".ctSearchOptions").find(".ddOwnership.select").attr("value");
	if (ownership != "null"){
		conditions["data[Report][ownership]"] = ownership;
	}
	
	// Filter by SafetyNet Hospitals	
	if ($(".ddSafetyNet").is(":checked")){
		conditions["data[Report][safety_net]"] = 1;
	}
	// Filter by Teaching Hospitals
	if ($(".ddTeachingHospitals").is(":checked")){
		conditions["data[Report][teaching_hospitals]"] = 1;
	}
	
	// Filter by Academic Health Centers
	if ($(".ddAcademicHealthCenters").is(":checked")){
		conditions["data[Report][academic_health_centers]"] = 1;
	}
	
	// Read the measureset selected
	var measureset = oBase.closest(".ctSearchOptions").find(".ddHospitalMeasures.select").attr("value");

	if (measureset != "null"){
		conditions["data[Report][measure_set]"] = measureset;
	}
	

	
	
	oBase.closest(".ctSearchOptions").children(".searchResults").html('<div class="spinner"><img src="/img/loading3.gif" /></div>');
	
	//console.log(conditions);
	// Read the the state value selected if any and post this to the ajax call
    		oBase.closest(".ctSearchOptions").children(".searchResults").load('/reference_entities_hospitals/characteristics_search',
    			conditions,
    			function(){
    				checkWatchlist();
    			}
    		);


}

function staggerCheckWatchlist(){

	setTimeout('checkWatchlist()', 500);

}

/**
 * Checks off all the watchlist items that are in the entity list
 */
function checkWatchlist(enclosing){
	//console.log(enclosing);
	if (typeof enclosing == 'undefined'){
		enclosing = '';
	} else {
		enclosing = enclosing + ' ';
	}
	//console.log($(".hospitalCompareCheckbox"));
	// Find all available hospitalComparCheckboxes
	$(enclosing + ".hospitalCompareCheckbox").map(function(){
		
		val = parseInt($(this).val());
		
		if (detectItem(watchlist, val)){
			//console.log(val);
			$(this).attr('checked', true);
		}
	});
	
	
}

/**
 * Swaps out the visible password field for hidden password on focus
 */
function swapPasswordField(){
	$(this).hide();
	$("#tbPassword").show();
	$("#tbPassword").focus();
}
/** 
 * Clears the text in the login box 
 */
function clearUsername(){
	username = $("#tbUserName").val();
	if (username == 'Email Address'){
		$("#tbUserName").val('');
	}
}

function suggestHrrs(){
	// How many hhrs are there currently?
	selected = $(this).closest(".reportAdmin").find(".selected-hrrs li");
	
	// Only get 3 suggestions
	if (selected.length < 3){
		limit = 3 - selected.length;
		
		
		
	}
}

//updates the ctSelectionsHospitalsCount with the count of the hospitals
function updateCtSelectionsHospitalsCount() {
	$("#ctSelectionsHospitalsCount").html(watchlist.length +" hospital(s)" );
}

