// Init
// ----------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------

// ----------------------------------------------------------------------------------
// Array protyping functions, just piddling along
// ----------------------------------------------------------------------------------

function getAsciiTotal(thestring)
{
	var output = 0;
	for(i=0; i<thestring.length; i++) {
		output = output + (thestring.charCodeAt(i)); 
	}
	return output;
}

  
function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

Array.prototype.flip=function(a1, a2){ var tmp=this[a2]; this[a2]=this[a1]; this[a1]=tmp; }

// Array.unique( strict ) - Remove duplicate values
Array.prototype.unique = function( b ) {
 var a = [], i, l = this.length;
 for( i=0; i<l; i++ ) {
  if( a.indexOf( this[i], 0, b ) < 0 ) { a.push( this[i] ); }
 }
 return a;
};
Array.prototype.max = function() {
    return Math.max.apply(null, this);
};
Array.prototype.min = function() {
    return Math.min.apply(null, this);
};

var measure_data_retrieved = 0;
var map_has_been_created=0;

// ----------------------------------------------------------------------------------
// On with the jQuery!
// ----------------------------------------------------------------------------------

$(document).ready(function(){	
//alert($('#page_for_hit').val());
// quick HIT stuff
$('.read_more_measure_text_button_hit').click(function() { 
	var div_to_show_and_hide = $(this).parent().find('.read_more_measure_text_hit');
	div_to_show_and_hide.toggle();
	if($(this).html() == 'Read More &gt;') { 
		$(this).html('&lt Read Less');
	} else { 
		$(this).html('Read More &gt;');
	}
	return false;
})

//

	
	// Navigation Rollovers 
	setupNav();	
	
	flipA=0;
	flipB=0;
	


	if($("#page").val() == 'cost_reports' || $("#page").val() == 'cost_landing'){
	  //   getCostMeasureData($('#sf').val(), $('#category').val(), $('#sub_category').val()); 
	  //   getCostCategoryList($('#cost_cat_filter').val(), $('#cost_selected_cpt').val());
	  getCostCategoryList($("#cost_selected_cat").val(), $('#cost_selected_cpt').val());

		 		 
	}	
	if($("#page").val() == 'cost_list') {
		getMeasureData($('#sf').val(), $('#category').val(), $('#sub_category').val());
	}
	
	if($("#page").val() == 'cost_search'){		
		getCostCategoryList($("#cost_selected_cat").val(), $('#cost_selected_cpt').val());
	}
	

	if($("#page").val() == 'cost_profile'){
		getCostCategoryList($('#cost_selected_cat').val(), $('#cost_selected_cpt').val());
	}
	
	if($("#page").val() == 'cost_reports'){
		//alert("Get Measure Data?");
		//
	}	
	// Set Cost Select to Auto Update CPT Select
//	if($("#page").val() != 'cost_landing') {
	$('#cost_cat_filter').change(function(){ 
		if($("#page").val() == 'cost_profile'){
			//$('#cost_cat_filter').val($('#cost_selected_cat').val());
			//$('#data_table_tbody').empty();
			//getCostData($('#cost_cat_filter').val(), $('#cost_selected_cpt').val());
			//getCostCPTList($('#cost_cat_filter').val(), $('#cost_selected_cpt').val());
		}
		else {
		    
     		$('#cost_selected_cat').val( $('#cost_cat_filter option:selected').val() );
			$('#cost_cat_filter').val( $('#cost_cat_filter option:selected').val() );
			$('#data_table_tbody').empty();
			getCostCategoryList($('#cost_cat_filter').val(), $('#cost_selected_cpt').val());
			//getCostCPTList($('#cost_cat_filter').val(), $('#cost_selected_cpt').val());

			$('#cost_cpt_filter').empty();
			$('#cost_cpt_filter').append("<option>Loading...</option>");
		
			
				}
	});
	
	// Set Cost Select to Auto Update CPT Select
	$('#cost_cpt_filter').change(function(){ 
			$('#cost_selected_cpt').val( $('#cost_cpt_filter option:selected').val() );
			$('#data_table_tbody').empty();
			//getCostData( $('#cost_cat_filter').val(), $('#cost_selected_cpt').val() );
			getCostCPTList($('#cost_cat_filter').val(), $('#cost_selected_cpt').val());
			    
		    $('#procedure_info_text1').empty();
			$('#procedure_info_text2').empty();
			$('#cost_title_item').empty();
			if($('#search_phrase').val() != "") { 

				$('#sort_by_name').empty();			
				$('#sort_by_name').append("Sort by Name <span id=\"sorttable_sortfwdind\"><img alt='' src='assets/down_arrow.gif' /></span>");
				
				$("#sort_by_name").removeClass();
				$("#sort_by_name").addClass("sorttable_sorted")
    			
				$('#sort_by_rate').empty();			
				$('#sort_by_rate').append('Sort By Cost');			
				$('#sort_by_rate').removeClass();			
				$('#sort_by_rate').addClass('sorttable_numeric');			
				
				/*
				<th id='sort_by_name' class='sorttable_sorted'>Sort by Name
				<span id="sorttable_sortfwdind"><img alt='' src='assets/down_arrow.gif' /></span></th>
				<th class='sorttable_nosort'></th>
				<th class='sorttable_nosort'></th>
				<th id='sort_by_rate' class='sorttable_numeric'>Sort by Cost</th>
				*/
				
			} else {
				$('#sort_by_name').empty();			
				$('#sort_by_name').append("Sort by Name");
				
				$("#sort_by_name").removeClass();
			//	$("#sort_by_name").addClass("sorttable")
    			
				$('#sort_by_rate').empty();			
				$('#sort_by_rate').append("Sort By Cost  <span id=\"sorttable_sortfwdind\"><img alt='' src='assets/down_arrow.gif' /></span>");			
				$('#sort_by_rate').removeClass();			
				$('#sort_by_rate').addClass('sorttable_numeric sorttable_sorted');			
							
			}
	});	
//	}
	

/* ----- Get AND POPULATE COST CATEGORIES AND CPT CODE DESCRIPTIONS Measure List 
------------------------------------------------------------------------------------- */


function getCostCategoryList(cost_cat_filter, cost_selected_cpt){
/*if(!cost_cat_filter) { 
	cost_cat_filter = 9; // temporary fix for CTP list
}*/

	$.ajax({
		type: "POST", url: "actions/get_xml.php",
		data: 'feed=cost_category/',
		success: 	function(xml){ populateCostCategoryList(xml, cost_cat_filter, cost_selected_cpt);  },
		error: 		function(){ $('#error_feedback').append(""); }	
	});
}

function populateCostCategoryList(xml, cost_cat_filter, cost_selected_cpt){
	// Populate Categories
	//alert("Populate Cost Category");
	$('#cost_cat_filter').empty();
	
	$('report-category',xml).each(function(i){
		id = $(this).find('id:first').text();

		abbrev = $(this).find('name:first').text();
		selected = (id == cost_cat_filter )? "selected='selected'" : "";		
		
		
		if(!cost_cat_filter){
			//$('#cost_cat_filter').append("<option  value=''>Select a Category</option>");
		}
		$('#cost_cat_filter').append("<option "+selected+" value='"+id+"'>"+abbrev+"</option>");

	});
	//alert("First: " + first);
    //default mode, please populate secondary conditions with first shown.
	getCostCPTList($('#cost_cat_filter').val(), cost_selected_cpt);



	
}

function getCostCPTList(cost_cat_filter, cost_selected_cpt){
		// alert("cost_cat_filter: " + cost_cat_filter);
		// alert("Cost_Selected_CPT: " + cost_selected_cpt);
	$.ajax({
		type: "POST", url: "actions/get_xml.php",
		data: 'feed=cost_cpt_list/'+cost_cat_filter+'',	
		success: 	function(xml){ populateCostCptList(xml, cost_cat_filter, cost_selected_cpt); },
		error: 		function(){ $('#error_feedback').append(""); }	
	});
}

// -- cost cpt list 
function populateCostCptList(xml, cost_cat_filter, cost_selected_cpt) {
//alert("Populate cost cpt list: " + cost_selected_cpt);
/*if(cost_selected_cpt == "0") { // remove procedure info without cost_selected_cpt to avoid empty div
			$('#procedure_info').empty();
}*/
	// Populate CPTs
	i = 0;
	$('#cost_cpt_filter').empty();
	var groups = Array();
    var first_cpt;
    var first_desc;
    var first_note;
    var first_short;
    var has_selected_item = 0; // set to zero to declare no selected item
    
	//alert("Cost Selected CPT: " +cost_selected_cpt);
	$('cpt-code',xml).each(function(i){
		id                  = $(this).find('id:first').text();
		cpt_description     = $(this).find('short-description:first').text();
		cpt_cat_name        = $(this).find('report-category-name:first').text();
		selected            = (id == cost_selected_cpt ) ? "selected='selected'" : "";
		code                = $(this).find('code:first').text(); 
		description     = $(this).find('description:first').text();
		note  			= $(this).find('note:first').text();
		if(!first_cpt) {  // if the variable is not set, set it once and only once
			first_cpt = code;
		    first_desc = description;
		    first_note = note;
			first_short = cpt_description;	
		}
		
		if(selected != "") { // There is a selected value, set the infotip to that.
			//alert("Selected");
			var description     = $(this).find('description:first').text();
			var note  			= $(this).find('note:first').text();
			
            var short           = $(this).find('short-description:first').text();
            has_selected_item = 1;
			
			if(description) {
				$('#procedure_info_text1').empty();
				first_div_append = ""  + description + "<br/>"; 
				$('#procedure_info_text1').append(first_div_append);
			} else {
				$('#procedure_info_text1').empty();
			}
			if(note) {
				$('#procedure_info_text2').empty();
				second_div_append = "" + note + "<br/>";						
				$('#procedure_info_text2').append(second_div_append);
			} else {
				$('#procedure_info_text2').empty();
			}
				$('#cost_title_item').empty();
				$('#cost_title_item').append(short);
				if(!note) { 
						$('#procedure_info_readmore').hide();
				} else {
						$('#procedure_info_readmore').show();
				}
	

		}		

	



			// if it's selected, provide the note and description.
	
		 $('#cost_cpt_filter').append("<option "+selected+" value='"+id+"'>"+cpt_description+" </option>");

   });




// -- after the loop - if there was no selected value, use the default first selected value
		if(has_selected_item == 0) {
		//alert("No Selected Item");
		    $('#procedure_info_text1').empty();
			$('#procedure_info_text2').empty();
			$('#cost_title_item').empty();
				
			first_div_append = ""  + first_desc + "<br/>"; 
			second_div_append = "" + first_note + "<br/>";						
							
			
			$('#procedure_info_text1').append(first_div_append);
			$('#procedure_info_text2').append(second_div_append);
			$('#cost_title_item').append(first_short);
			//alert("First Note: '" + first_note + "'");
			if(!first_note) { 
						$('#procedure_info_readmore').hide();
				} else {
						$('#procedure_info_readmore').show();
				}
	

			}
//




	$('#cost_selected_cpt').val( $('#cost_cpt_filter option:selected').val() );
	getCostData(cost_cat_filter, $('#cost_selected_cpt').val() );
}

// -- cost cpt list

	


function getCostData(cost_cat_filter, cost_selected_cpt){
	cost_search_phrase = $('#cost_search_field').val();
	
	cost_search_phrase =  cost_search_phrase.replace(/ /g, "_");
	//alert("Cost Search Phrase: " + cost_search_phrase);
	//alert("Getting Cost Data");
	$('#data_table_loading').html("<div id='data_table_loading_inner'><img alt='Loading...' src='assets/loading.gif' /></div>");
	
	if($("#page").val()=='cost_profile'){
			this_name_id = $('#name_id').val();
			this_data_stream = 'feed=cost_group_data/'+this_name_id+'/'+cost_cat_filter+'/';
			//alert("Cost Groups, cost_cat_filter = " + cost_cat_filter+ " Feed: " + this_data_stream);
			$.ajax({
				type: "POST", url: "actions/get_xml.php",
				data: 'feed=cost_group_data/'+this_name_id+'/'+cost_cat_filter+'/',
				//data: 'feed=cost_group_data/56/9/',
				success: 	function(xml){ populateCostProfileData(xml, cost_cat_filter, cost_selected_cpt); },
				error: 		function(){ populateCostProfileData('error', cost_cat_filter, cost_selected_cpt); }	
			});	
	}
	else {
		// NO SEARCH TERM
		if(cost_search_phrase == ''){
			//alert('Cost Selected CPT: ' + cost_selected_cpt);
			$.ajax({
				type: "POST", url: "actions/get_xml.php",
				data: 'feed=cost_cpt_data/'+cost_selected_cpt+'',
				success: 	function(xml){ populateCostData(xml, cost_cat_filter, cost_selected_cpt); },
				error: 		function(){ populateCostData('error', cost_cat_filter, cost_selected_cpt); }	
			});		
		}
	
		// WITH SEARCH TERM
		else {
			//alert('with search');
			$.ajax({
				type: "POST", url: "actions/get_xml.php",
				data: 'feed=cost_group_search/'+cost_search_phrase+'/'+cost_selected_cpt+'',
				//data: 'feed=cost_cpt_data/'+cost_selected_cpt+'',
				success: 	function(xml){ populateCostData(xml, cost_cat_filter, cost_selected_cpt);},
				error: 		function(){ populateCostData('error', cost_cat_filter, cost_selected_cpt);}	
			});	
		}	
	}
	
}


function populateCostData(xml, cost_cat_filter, cost_selected_cpt){
	$('#data_table_loading').empty();
	$('#data_table_tbody').empty();
	$('#procedure_info').show();
	
	if(measure_data_retrieved ==0) {
	
	
	// ----------------------------------------------------------------------------------------------------------------------------------
	// convert cost data to appropriate scale for a 1 to 100 graph
	// ----------------------------------------------------------------------------------------------------------------------------------
	
	
	var name_ids = [];
	var names = [];
	var per_units = [];
	var cities = [];
	var zips = [];
	var medians = [];
	
	
	// ----------------------------------------------------------------------------------------------------------------------------------
	// storing all xml data in an array to process later.  We must have maximum and minimum of the values BEFORE outputting data.
	// ----------------------------------------------------------------------------------------------------------------------------------
	
	
	// ----------------------------------------------------------------------------------------------------------------------------------
	// Parse XML and append data to the dropdown
	// ----------------------------------------------------------------------------------------------------------------------------------
	
	
	
	$('public-measure-summary',xml).each(function(i){
		name_ids.push($(this).find('medical-group-identifier:first').text());
		names.push($(this).find('medical-group-name:first').text());
		cities.push($(this).find('city:first').text());
		zips.push($(this).find('zip-code:first').text());
		
		temp_per_unit = $(this).find('allowed-per-unit:first').text();

		per_units.push(eval(temp_per_unit).toFixed(0));
		medians.push($(this).find('overall-median:first').text());

	});
	    //--------------------------------------------------------------------------------------
	    // Convert the old values into a new appropriately scaled range for use when outputting
	    // -------------------------------------------------------------------------------------
	
		var oldmax = per_units.max();
		var oldmin = per_units.min();
		var oldrange = (oldmax - oldmin);
	    var newrange = 100;
	    var count = 0;
		var zeeswitch = 0;
	    var new_median = (((medians[0] - oldmin) * newrange) / oldrange) + 0;  // only for graphing purposes
	    //alert("Oldmin: " + oldmin + " New Median " + new_median);
	    if(new_median < 0) {
	    	new_median = 0;
			zeeswitch = 1;
	    }
	    if(new_median > 100) {
	    	new_median = 100;
			zeeswitch = 1;
	    }
	    jQuery.each(name_ids, function() {
	    var new_value = (((per_units[count] - oldmin) * newrange) / oldrange) + 0; // only for graphing purposes
	    
	    
		
		if(zeeswitch){			
			$('#data_table_tbody').append(
				"<tr class='colbody_top'>"+
					"<td class='name'><a class='data_list_name' href='?p=cost_profile&name_id="+name_ids[count]+"&cost_cat_filter="+ cost_cat_filter +"'>"+names[count]+"</a></td>"+
					"<td class='secondary'>"+cities[count]+"</td>"+
					"<td class='secondary'>"+zips[count]+"</td>"+
					"<td class='graph_area'>"+
						"<div class='rate_num left'>$"+per_units[count]+"</div>"+
						
							"<!--<div class='average_bar left' style='position:relative; left: "+(new_median+3)+"px; line-height: 0px; width: 3px; height: 13px;'></div>-->"+
							"<div class='left'>"+
								"<div class='graph'>"+
									"<div class='rate' style='width: "+new_value+"px;'></div></div>"+
								"</div>"+
							"<div class='clear'></div>" +			
					"</td>"+
					"<td class='view_details'><a href='?p=cost_profile&name_id="+name_ids[count]+"&cost_cat_filter="+ cost_cat_filter +"'>view profile ></a></td>"+
					"<!--td class='compare_button_cell'><div class='compare_button'><input class='compare_checkbox' type='checkbox' name='' value='"+name_ids[count]+"' /></div></td-->"+
				"</tr>"
			);				
		}
		if(!zeeswitch){			
			$('#data_table_tbody').append(
				"<tr class='colbody_top'>"+
					"<td class='name'><a class='data_list_name' href='?p=cost_profile&name_id="+name_ids[count]+"&cost_cat_filter="+ cost_cat_filter +"'>"+names[count]+"</a></td>"+
					"<td class='secondary'>"+cities[count]+"</td>"+
					"<td class='secondary'>"+zips[count]+"</td>"+
					"<td class='graph_area'>"+
						"<div class='rate_num left'>$"+per_units[count]+"</div>"+
						
							"<div class='average_bar left' style='position:relative; left: "+(new_median+3)+"px; line-height: 0px; width: 3px; height: 13px;'></div>"+
							"<div class='left'>"+
								"<div class='graph'>"+
									"<div class='rate' style='width: "+new_value+"px;'></div></div>"+
								"</div>"+
							"<div class='clear'></div>" +			
					"</td>"+
					"<td class='view_details'><a href='?p=cost_profile&name_id="+name_ids[count]+"&cost_cat_filter="+ cost_cat_filter +"'>view profile ></a></td>"+
					"<!--td class='compare_button_cell'><div class='compare_button'><input class='compare_checkbox' type='checkbox' name='' value='"+name_ids[count]+"' /></div></td-->"+
				"</tr>"
			);				
		}
		
		count++;
	});
	
	// Footnotes
	if(0){
		$('#data_table_tfoot').append(
			"<tr class='colbody_top'>"+
				"<td colspan='6' class='footnote'>"+
					"* HealthScores shown here for diabetes are based on data provided by the medical group. No data was provided by this medical group. To view this medical group's score based on health plan data, click on the medical group's View Profile button."+
					
							
				"</td>"+
			"</tr>"
		);
	}		

	// If there were no results
	// --------------------------------------------------------------------------------	
	if(!count){
		$('#data_table_tbody').append(
			"<tr class='colbody_top'>"+
				"<td colspan='6' class='no_results'>"+
					"<b>We're sorry, there were no results found for your search.</b><br />"+
					"Here are a few ideas that will hopefully improve your search results:<br /><br />"+
					"1. Double check the spelling of your search.<br />"+
					"2. Try using fewer words.<br />"+
					"3. Try using just part of the word that you are looking for.<br />"+
				"</td>"+
			"</tr>"
		);
	}
	}
	$("#entry_table").tablesorter({ 
			

	    }); 
}

function populateCostProfileData(xml, cost_cat_filter, cost_selected_cpt){
	count = 0;
	
	$('#data_table_tbody').empty();
	$('#data_table_loading').empty();
	//$('#procedure_info').hide();
	
	
	
	
	
	// Parse XML and append data to the dropdown
	$('public-measure-summary',xml).each(function(i){
		
		this_name_id = $(this).find('medical-group-identifier:first').text();
		name = $(this).find('medical-group-name:first').text();
		report_name = $(this).find('report-category-name:first').text();
		cpt_name = $(this).find('cpt-name:first').text();
		
		per_unit = $(this).find('allowed-per-unit:first').text();		
		per_unit = eval(per_unit).toFixed(2);
		
		$('#medical_group_name').text(name);
		
		if(1){			
			$('#data_table_tbody').append(
				"<tr class='colbody_top'>"+
					"<td class='name'><h2>"+report_name+"</h2>"+cpt_name+"</td>"+
					"<td class='graph_area'>"+
						"<b>$"+per_unit+"</b>"+
					"</td>"+
					"<!--td class='view_details'><a href='?p=cost_profile&name_id="+this_name_id+"'>view profile ></a></td-->"+
					"<!--td class='compare_button_cell'><div class='compare_button'><input class='compare_checkbox' type='checkbox' name='' value='"+this_name_id+"' /></div></td-->"+
				"</tr>"
			);				
		}
		
		count++;
		$("#entry_table").tablesorter({ 
			

	    }); 
	});

	// If there were no results
	// --------------------------------------------------------------------------------	
	if(!count){
		$('#data_table_tbody').append(
			"<tr class='colbody_top'>"+
				"<td colspan='6' class='no_results'>"+
					"<b>This Medical Group has no currently published data for this category.</b>"+
				"</td>"+
			"</tr>"
		);
	}	
}







	
	// Setup Read More button
	$('#read_more_measure_text_button').click( function(){ $('#read_more_measure_text').toggle('fast', function(){ flipA++; button = (flipA%2)? $('#read_more_measure_text_button').attr('src', 'assets/buttons/read_less.gif') : $('#read_more_measure_text_button').attr('src', 'assets/buttons/read_more.gif'); } ); return false; } );
	// Setup Read More for cost information
	
		$('#procedure_info_readmore').click( function(){ $('#procedure_info_text2').toggle('fast', function(){ flipA++; button = (flipA%2)? $('#procedure_info_readmore').attr('src', 'assets/buttons/read_less.gif') : $('#procedure_info_readmore').attr('src', 'assets/buttons/read_more.gif'); } ); return false; } );
	
	// cost landing
	$('#read_more_cost_landing_button').click( function(){ $('#read_more_cost_landing').toggle('fast', function(){ flipA++; button = (flipA%2)? $('#read_more_cost_landing_button').attr('src', 'assets/buttons/read_less.gif') : $('#read_more_cost_landing_button').attr('src', 'assets/buttons/read_more.gif'); } ); return false; } );
	
	// Setup Legend Display link
	$('#legend_link').click( function(){ $('#legend').toggle('slow', function(){ flipB++; button = (flipB%2)? $('#legend_link').text('Hide Legend') : $('#legend_link').text('What do these numbers mean?'); } ); return false; } );
	
	// Setup Compare Button
	$('#compare_button').click(function(){ sendToCompare($('#category').val(), $('#sub_category').val()); });
	
	// Depending on the page, perform the appropriate data pull		
	if($("#page").val() == 'home'){			
		getMeasureList('dropdown', $('#sf').val());
	}
	
	if($("#page").val() == 'our_reports' && $('#sf').val() != 'hospital'){		
		getMeasureList('sidebar', $('#sf').val());		
		getMeasureData($('#sf').val(), $('#category').val(), $('#sub_category').val()); 
	}
	
	if($("#page").val() == 'search' && $('#sf').val() != 'hospital'){		
		getMeasureList('sidebar', $('#sf').val());		
		getSearchResults($('#sf').val(), $('#category').val(), $('#sub_category').val(), $('#search_phrase').val()); 
	}
	
	if($("#page").val() == 'compare' && $('#sf').val() != 'hospital'){
		getMeasureList('sidebar', $('#sf').val());		
		getComparisonData($('#sf').val(), $('#category').val(), $('#sub_category').val(), $('#compare').val()); 
	}
	
	if($("#page").val() == 'profile' && $('#sf').val() != 'hospital'){
		getMeasureList('sidebar', $('#sf').val());
		getProfileInfo($('#sf').val(), $('#category').val(), $('#sub_category').val(), $('#name_id').val());
	}


	
});


// Setup
// ----------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------

function setupNav(){
var old ="";
	$('#nav_link_home').mouseover( function(){ old = this.src; this.src = 'assets/nav/home_mo.gif'; }).mouseout( function(){ this.src = old; });
	$('#nav_link_our_reports').mouseover( function(){ old = this.src; this.src = 'assets/nav/our_reports_mo.gif'; }).mouseout( function(){ this.src = old; });
	$('#nav_link_learn_more').mouseover( function(){ old = this.src; this.src = 'assets/nav/learn_more_mo.gif'; }).mouseout( function(){ this.src = old; });
}


/* ----- Send to Compare 
------------------------------------------------------------------------------------- */

function sendToCompare(category, sub_category){
	
	var sf = $('#sf').val();
	var search_phrase = $('#search_phrase').val();
	
	// Get all of the compare check boxes
	compare_check_boxes = $('.compare_checkbox');
	
	// Build a string of the checked boxes
	checked_boxes = '';
	for(i=0; i<compare_check_boxes.length; i++){
		checked_boxes = (compare_check_boxes[i].checked)? checked_boxes+compare_check_boxes[i].value+"," : checked_boxes+"";
	}
	
	// Send checked boxes along with category/sub_category to comparison page (if 2 or 3 entries have been checked)
	if( (checked_boxes.split(",")).length !=3 && (checked_boxes.split(",")).length !=4 ){ alert("Please choose either 2 or 3 entries for comparision."); }
	else {
	if($('#page').val() == 'cost_reports'){
				window.location = "?p=cost_compare&sf="+sf+"&category="+category+"&sub_category="+sub_category+"&compare="+checked_boxes+"&search_phrase="+search_phrase+"";	
	} else {
		window.location = "?p=compare&sf="+sf+"&category="+category+"&sub_category="+sub_category+"&compare="+checked_boxes+"&search_phrase="+search_phrase+"";
	}
	}
	return false;
}


// Getting Feeds
// ----------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------
function showTooltip(x, y, contents) {
        $('<div id="tooltip">' + contents + '</div>').css( {
            position: 'absolute',
            display: 'none',
            top: y - 35,
            left: x + 5,
            border: '1px solid #e8e8e8',
            padding: '2px',
            'background-color': '#fff',
            opacity: 0.80
        }).appendTo("body").fadeIn(200);
    }


/* ----- Get Search Results
------------------------------------------------------------------------------------- */

function getSearchResults(sf, category, sub_category, search_phrase){
	
	if(!search_phrase){ window.location = "?p=our_reports&sf="+sf+"&category="+category+"&sub_category="+sub_category+""; }
	else {
		// Strip of all but first word until a more robust search has been implemented
		//search_phrase = search_phrase.split(' ');
		//search_phrase = search_phrase[0];
		if(category == '18') { 



			feed = (sf=='group')? 'feed=hit_group_search/'+search_phrase+'' : 'feed=hit_clinic_search/'+search_phrase+'';
			
				
			$('#data_table_loading').html("<div id='data_table_loading_inner'><img alt='Loading...' src='assets/loading.gif' /></div>");
			
			$.ajax({
				type: "POST", url: "actions/get_xml.php",
				data: feed,
				success: 	function(xml){ populateHITdata(sf, category, sub_category, xml, 1); },		
				error: 		function(xml){ $('#error_feedback').append(""); populateHITdata(sf, category, sub_category, xml, 0); },
				complete: 	function(){ $('#data_table_loading').remove(); }
			});		
		
		
		
		} else {
			/*search_phrase = search_phrase.replace(/ /g, '_');
			search_phrase = search_phrase.replace(/'/g, '_');
			search_phrase = search_phrase.replace(/"/g, '_');*/
			
			feed = (sf=='group')? 'feed=group_search/'+search_phrase+'/' : 'feed=clinic_search/'+search_phrase+'/';
			feed = (category!='all')? feed + ''+category+'' : feed + '';
					
			$('#data_table_loading').html("<div id='data_table_loading_inner'><img alt='Loading...' src='assets/loading.gif' /></div>");
			
			$.ajax({
				type: "POST", url: "actions/get_xml.php",
				data: feed,
				success: 	function(xml){ populateDataList(sf, category, sub_category, xml); },		
				error: 		function(xml){ $('#error_feedback').append(""); populateDataList(sf, category, sub_category, xml); },
				complete: 	function(){ $('#data_table_loading').remove(); }
			});
		}
	}	
}


/* ----- Get Measure List 
------------------------------------------------------------------------------------- */

function getMeasureList(type, sf){		
	$.ajax({
		type: "POST", url: "actions/get_xml.php",
		data: 'feed=measure_list/'+sf+'',
		success: 	function(xml){	
						if(type=='dropdown'){ populateCategoryDropdown(xml); }	
						if(type=='sidebar'){ populateCategorySidebar(xml); }
					},		
		error: 		function(){ $('#error_feedback').append(""); }	
	});
}

//-----------------------------------------------------------------------------------
// 
//    populateHITdata function
//
//
//-----------------------------------------------------------------------------------
function populateHITLanding() { 
	$('.dd_mid_content').empty();
	
	$('.dd_mid_content').append("		"+	
						"<div class='dd_inner_top'><img alt='' src='assets/data_display/dd_inner_top.gif' /></div>" +
						"<div class='dd_inner_mid'>" +
						"<a href='?p=our_reports&sf=clinic&search_phrase=&category=18&name_id=&compare=&show_hit_data=1' style='float: right'><img src='assets/view_the_data.gif' alt='' /></a><h1>Health Information Technology</h1><div class='clear'></div>"+
						"<div class='measure_text depression_landing_text'>" +
""+
"" +
"<p>Health Information Technology (HIT) is the use of computers and computer programs, such as an " +
"electronic health records (EHR) to store, retrieve and securely transfer patient information electronically " +
"within health care settings. HIT use in clinics includes three phases: 1) adopting " +
"an EHR system; 2) utilizing its various features to gather and manage patient information, and; 3) " +
"exchanging patient information among providers.</p>" +
"<b>Care You Should Expect to Receive</b>" +
"<ul style='margin-top: 0px;'>" +
"	<li>Information about you and the care you need is recorded in an EHR instead of a paper medical record.</li>" +
"	<li>Your provider uses the EHR to help order lab tests, track your health problems, and use information to improve your care.</li>" +
"	<li>Your information is sent and received in a secure manner among the health care providers involved in your care.</li>" +
"</ul>" +
"<p>Doctors, hospitals, laboratories and pharmacies that use HIT can document and share information about " +
"the care they provide to you. This can be helpful if you see multiple doctors or have a medical condition "  +
"that requires specific types of care.</p> <a href='#' class='hit_example_open'>How Will This Help Me?</a></div><br/><br/>" +
						"<div class='measure_text depression_landing_text'>" +
"<b>What Does This Info Mean?</b><br/>" +
"<p>The table and checkmarks below will tell you how successful Minnesota physicians and other health care " +
"providers are in advancing the use of HIT in their practice. " +
"Each checkmark represents a milestone in the advancement of HIT use in provider practices.  A high number of green checkmarks shows more advanced HIT use which signifies high quality care.</p>" +
"<p>" +
"<a href='#' class='hit_grid_jqm'>View Milestones for HIT Use.</a></p>" +
"<p>This report is based on provider responses to the 2010 Health Information Technology (HIT) Ambulatory Clinic Survey, submitted to MN Community Measurement. The survey was sent to all clinics in early 2010 and the response rate was over 85%. <a href='#' class='hit_statewide_show'>Statewide Summary.</a></p>" +
"<p>It is important to know that small differences in the number of checkmarks should not be of concern. It is more important to look at larger differences. The information in this report is collected annually, and may not reflect recent advancements in an individual provider's efforts to use HIT in their practice. Talk with your provider if you have questions about their score.</p>"+
"<div class='hit_grid jqmWindow' style='display:none'><a href='#' class='right hit_grid_jqm_close' >Close (X)</a> <a href='printer.php?content=hit_grid' target='_BLANK' class='right' style='margin-right: 10px'><img src='assets/printer_icon.jpg' /></a> <b>Milestones for Advancement of HIT Use in DoctorÕs Offices</b><br/>" +
"<img src='assets/hit_grid_top_arrow.jpg' alt='' />" +
	"<table>" +
		"<thead><tr>"+
		"<th><b>Adopt</b></th>"+
		"<th><b>Use</b></th>"+
		"<th><b>Exchange</b></th>"+
		"</tr></thead>"+
		"<tbody><tr>" +
			"<td><img src='assets/check_on.jpg' width='12' /><br/>Planning on adopting an electronic health record</td>" +
			"<td><img src='assets/check_on.jpg' width='12' /><br/>Use the EHR for lab and test results</td>" +
			"<td><img src='assets/check_on.jpg' width='12' /><br/>Do electronic prescribing OR safely send data to hospitals in the provider's network</td>" +
		"</tr>" +
		"<tr>" +
			"<td><img src='assets/check_on.jpg' width='12' /><img src='assets/check_on.jpg' width='12' /><br/>Started installation of an EHR</td>" +
			"<td><img src='assets/check_on.jpg' width='12' /><img src='assets/check_on.jpg' width='12' /><br/>And also use the EHR to track patients' health problems and track doctor orders</td>" +
			"<td><img src='assets/check_on.jpg' width='12' /><img src='assets/check_on.jpg' width='12' /><br/>Do electronic prescribing AND send data to hospitals in the doctors network</td>" +
		"</tr>" +
		"<tr>" +
			"<td><img src='assets/check_on.jpg' width='12' /><img src='assets/check_on.jpg' width='12' /><img src='assets/check_on.jpg' width='12' /><br/>Fully installed EHR</td>" +
			"<td><img src='assets/check_on.jpg' width='12' /><img src='assets/check_on.jpg' width='12' /><img src='assets/check_on.jpg' width='12' /><br/>And also use the EHR to create benchmarks and remind patients when they need preventative care</td>" +
			"<td><img src='assets/check_on.jpg' width='12' /><img src='assets/check_on.jpg' width='12' /><img src='assets/check_on.jpg' width='12' /><br/>And can also safely send data from the EHR to hospitals outside the doctor's network</td>" +
		"</tr></tbody>" +
	"</table>" +
"</div>" + 
"<div class='hit_example jqmWindow' style='display:none'><b>How Will This Help Me?</b><br/>" +
"<a href='#top' class='right hit_example_close' >Close (X)</a><br/>" + 
"<p>If you have diabetes and you need emergency care in another community, emergency department providers can quickly learn of your diabetes treatments through your EHR. This information will help them determine the treatment that is best for your emergency condition and also safe for patients with diabetes.  When you return to your community, your doctor can learn about the emergency care you received and make sure you receive appropriate follow up care.</p>" +
	"</div>"+
	"<div class='hit_statewide jqmWindow' style='display:none'><b>2009 Statewide Advancement of HIT Use in Provider Practices</b><br/>" +
"<a href='#top' class='right hit_statewide_close' >Close (X)</a><br/>" + 
"<img src='assets/hit_state_summary.jpg' alt='' />" +
"Advancement of HIT use in provider practices across Minnesota is summarized above. The numbers above represent the percentage of providers across the state who have achieved the milestones in each of the three phases of HIT use. Responses for individual provider clinics are displayed using a slightly different model. <a href='#'>Return to provider list.</a> " +
"</div>" + 
	"</div><br/><a href='?p=our_reports&sf=clinic&search_phrase=&category=18&name_id=&compare=&show_hit_data=1' style='float: right'><img src='assets/view_the_data.gif' alt='' /></a><div class='clear'></div></div>"+

						"<div class='dd_inner_bottom'><img alt='' src='assets/data_display/dd_inner_bottom.gif' /></div>");
				$('.hit_grid').jqm();
				$('.hit_grid_jqm').click(function() { 
					$('.hit_grid').jqmShow();	
					//return false;
				});
				$('.hit_grid_jqm_close').click(function() { 
					$('.hit_grid').jqmHide();	
					//return false;
				});
				$('.hit_statewide').jqm();
				$('.hit_statewide_show').click(function() { 
					$('.hit_statewide').jqmShow();	
					//return false;
				});
				$('.hit_statewide_close').click(function() { 
					$('.hit_statewide').jqmHide();	
					//return false;
				});
				$('.hit_example').jqm();
				$('.hit_example_open').click(function() { 
					$('.hit_example').jqmShow();	
					//return false;
				});
				$('.hit_example_close').click(function() { 
					$('.hit_example').jqmHide();	
					//return false;
				});
				
						
						$('#read_more_measure_text_button').click( function(){ $('#read_more_measure_text').toggle('fast', function(){ flipA++; button = (flipA%2)? $('#read_more_measure_text_button').attr('src', 'assets/buttons/read_less.gif') : $('#read_more_measure_text_button').attr('src', 'assets/buttons/read_more.gif'); } ); return false; } );
	
	
}
function populateHITdata(sf, category, sub_category, xml, success) {

			total_pages = $(xml).find('total-pages:first').text();
			total_pages = parseInt(total_pages);
			/*
			/?p=our_reports&sf=clinic&search_phrase=&category=18&name_id=&compare=&
			*/
			
			var this_page = $('#page').val();
			var this_sf = $('#sf').val();
			var this_search_phrase = $('#search_phrase').val();
			var this_category = $('#category').val();
			var this_name_id = $('#name_id').val();
			var this_compare = $('#compare').val();
			var this_page_for_hit = $('#page_for_hit').val();
			var temp_class;
			for(x=0;x<total_pages;x++) { 
				var m = x+1;
				if(x == $('#page_for_hit').val()) { 
					temp_class = " class='selected_hit_page' ";
				} else { 
					temp_class = ""
				}
				$('.page_numbers').append("" + 
					"<a " + temp_class + "href='?p=" + 
					this_page + 
					"&amp;sf=" + this_sf +  
					"&amp;search_phrase=" + this_search_phrase + 
					"&amp;category=" + this_category + 
					"&amp;name_id=" + this_name_id + 
					"&amp;page_for_hit=" + x + 
					"&amp;compare=" + this_compare +"'>" + m + "</a>" + 
					"&nbsp;"
				);
			
			}
			
			// Parse XML and append data to the dropdown
			
					$('.hit_grid').jqm();
				$('.hit_grid_jqm').click(function() { 
					$('.hit_grid').jqmShow();	
					//return false;
				});
				$('.hit_grid_jqm_close').click(function() { 
					$('.hit_grid').jqmHide();	
					//return false;
				});
				$('.hit_statewide').jqm();
				$('.hit_statewide_show').click(function() { 
					$('.hit_statewide').jqmShow();	
					//return false;
				});
				$('.hit_statewide_close').click(function() { 
					$('.hit_statewide').jqmHide();	
					//return false;
				});
				$('.hit_example').jqm();
				$('.hit_example_open').click(function() { 
					$('.hit_example').jqmShow();	
					//return false;
				});
				$('.hit_example_close').click(function() { 
					$('.hit_example').jqmHide();	
					//return false;
				});
		var count = 0;
		var first = 0;
		if(success){
		$('public-measure-summary',xml).each(function(i){ // loop through each public-measure-summary node in XML (dur)
		
		

		 
			var clinic_id          		 = $(this).find('clinic-id:first').text();
			var clinic_name        		 = $(this).find('clinic-name:first').text();
			
			if(sf == 'group') {
				var clinic_name        	 = $(this).find('medical-group-name:first').text();
				var clinic_id          	 = $(this).find('medical-group-identifier:first').text();
			}
			var measure_period_id		 = $(this).find('measure-period-id:first').text();
			
			var adoption_full			 = ($(this).find('adoption-full:first').text() == 1) ? 'check_on.jpg' : 'check_off.jpg';
			var adoption_partial		 = ($(this).find('adoption-partial:first').text() == 1) ? 'check_on.jpg' : 'check_off.jpg';
			var adoption_planning		 = ($(this).find('adoption-planning:first').text() == 1) ? 'check_on.jpg' : 'check_off.jpg';
			
			var exchange_adv			 = ($(this).find('exchange-adv:first').text() == 1) ? 'check_on.jpg' : 'check_off.jpg';
			var exchange_beg			 = ($(this).find('exchange-beg:first').text() == 1) ? 'check_on.jpg' : 'check_off.jpg';
			var exchange_int			 = ($(this).find('exchange-int:first').text() == 1) ? 'check_on.jpg' : 'check_off.jpg';
			
			var utilization_adv			 = ($(this).find('utilization-adv:first').text() == 1) ? 'check_on.jpg' : 'check_off.jpg';
			var utilization_beg			 = ($(this).find('utilization-beg:first').text() == 1) ? 'check_on.jpg' : 'check_off.jpg';
			var utilization_int			 = ($(this).find('utilization-int:first').text() == 1) ? 'check_on.jpg' : 'check_off.jpg';
			
			var adoption_score			 = parseInt($(this).find('adoption-score:first').text());
			var exchange_score			 = parseInt($(this).find('exchange-score:first').text());
			var utilization_score		 = parseInt($(this).find('utilization-score:first').text());		
			
			var theimg_start = "<img src='assets/";
			var theimg_end   = "' style='padding-top: 3px;padding-left: 10px;' alt='' />";
			
			
			$('#data_table_tbody').append(
						"<tr class='colbody_top'>"+
							"<td class='name_hit' style='width: 180px !important;text-align: left;'><a href='?p=profile&name_id=" + clinic_id + "&sf=" + sf + "&measure-period-id="+measure_period_id +"&category=18'>" + clinic_name + "</a></td>"+
							"<!--<td style='display: none'></td>-->" + 
							"<td class='secondary_hit' style='text-align: center;' ><span style='display:none;'>" + adoption_score +"</span>" +
							"" + theimg_start + adoption_planning + theimg_end + "" + 
							"" + theimg_start + adoption_partial + theimg_end + "" + 
							"" + theimg_start + adoption_full + theimg_end + "" + 
							"" + "<img src='assets/dotted_divider.gif' style='float: right; margin-right: -5px;'/></td>"+
							"<td class='secondary_hit' style='text-align: center;' ><span style='display:none;'>" + utilization_score +"</span>" +
							"" + theimg_start + utilization_beg + theimg_end + "" + 
							"" + theimg_start + utilization_int + theimg_end + "" + 
							"" + theimg_start + utilization_adv + theimg_end + "" + 
							"" + "<img src='assets/dotted_divider.gif' style='float: right; margin-right: -5px;'/></td>"+
							"<td class='secondary_hit' style='text-align: center;' ><span style='display:none;'>" + exchange_score +"</span>" +
							"" + theimg_start + exchange_beg + theimg_end + "" + 
							"" + theimg_start + exchange_int + theimg_end + "" + 
							"" + theimg_start + exchange_adv + theimg_end + "" + 
							"" + "</td>"+
							
												
						"</tr>"
					);
				

			});
	$("#entry_table").tablesorter({
		//sortList: [[1,0]] // reshuffle the table to sort on the hidden "HIT points field"
		debug: false
	});
	//.tablesorterPager({container: $(".pagination_area")}); 		
	

	} else {
		$('#data_table_tbody').append(
			"<tr class='colbody_top'>"+
				"<td colspan='6' class='no_results'>"+
					"<b>We're sorry, there were no results found for your search.</b><br />"+
					"Here are a few ideas that will hopefully improve your search results:<br /><br />"+
					"1. Double check the spelling of your search.<br />"+
					"2. Try using fewer words.<br />"+
					"3. Try using just part of the word that you are looking for.<br />"+
				"</td>"+
			"</tr>"
		);
	}

}


/* ----- Get Measure Data 
------------------------------------------------------------------------------------- */
function displayDepressionLanding() { 
	$('.dd_mid_content').empty();
	
	$('.dd_mid_content').append("		"+	
						"<div class='dd_inner_top'><img alt='' src='assets/data_display/dd_inner_top.gif' /></div>" +
						"<div class='dd_inner_mid'>" +
						"	<h1>Depression</h1>"+
						"<div class='measure_text depression_landing_text'>" +
						"<b>What is Depression?</b><br/>"+
"<p>Depression is more than feeling sad or \"blue\".  Depression is an illness that affects a person's mood, thoughts and body.  Depression can interfere with daily life.  About one out of ten men and one out of four women will experience depression in their lifetime. </p>" +

"Symptoms are different for everyone, but people who are depressed may:" +
"<ul>" +
"	<li>feel hopeless</li>" +
"	<li>sleep too much or too little</li>" +
"	<li>eat too much or too little</li>" +
"	<li>lose interest in activities they used to enjoy.</li>" +
"</ul>" +
"<p>Even people with severe cases of depression can be treated.  For some people, talking with a therapist can help them feel better.  Others benefit from medication or need a combination of medication and therapy.  The first step is to visit a health care provider.  </p>" +

"<p>Here we offer two ways of looking at how successful health care providers are in treating adults with major depression:" +
"<ul>" + 
"<li><a href='?p=our_reports&sf=clinic&category=4&sub_category=7&name_id=&compare='>Remission at 6 Months</a> shows the number of patients who got better (remission) six months after starting treatment.</li>" +
"<li><a href='?p=our_reports&sf=clinic&category=4&sub_category=8&name_id=&compare='>Remission at 12 Months</a> shows the number of patients who got better (remission) 12 months after starting treatment.</li>" +
"<li><a href='?p=our_reports&sf=clinic&category=4&sub_category=3&name_id=&compare='>Utilization of the PHQ-9</a> shows the number of patients who completed the Patient Health Questionnaire 9, a tool we encourage health care providers to use to determine whether a patient with depression is getting better.</li></ul></p></div></div>" +

						"<div class='dd_inner_bottom'><img alt='' src='assets/data_display/dd_inner_bottom.gif' /></div>");
						
						$('#read_more_measure_text_button').click( function(){ $('#read_more_measure_text').toggle('fast', function(){ flipA++; button = (flipA%2)? $('#read_more_measure_text_button').attr('src', 'assets/buttons/read_less.gif') : $('#read_more_measure_text_button').attr('src', 'assets/buttons/read_more.gif'); } ); return false; } );
	
	
}



function getMeasureData(sf, category, sub_category){

	if(category == '18') { // HIT data runs on a different set of feeds.
		feed = 'feed=hit_measure_data_current/clinic&page_for_hit=' + $('#page_for_hit').val() + '';
		
				$('#data_table_loading').html("<div id='data_table_loading_inner'><img alt='Loading...' src='assets/loading.gif' /></div>");
		
			$.ajax({
				type: "POST", url: "actions/get_xml.php",
				data: feed,
				success: 	function(xml){ populateHITdata(sf, category, sub_category, xml, 1);},		
				error: 		function(){ $('#error_feedback').append(""); },
				complete: 	function(){ $('#data_table_loading').remove(); }
			});
		

	} else if (category == '4') { //depression exception
		
		if(sub_category == "8" || sub_category == "3" || sub_category == '7') {  //some depression runs on a different set of feeds too, but not all.\ 	
			feed = (category == 'all')? 'feed=medical_group' : 'feed=measure_data_current/'+category+'/'+sub_category+'';
			$('#data_table_loading').html("<div id='data_table_loading_inner'><img alt='Loading...' src='assets/loading.gif' /></div>");
		
			$.ajax({
				type: "POST", url: "actions/get_xml.php",
				data: feed,
				success: 	function(xml){ populateDataList(sf, category, sub_category, xml); measure_data_retrieved = 1;},		
				error: 		function(){ $('#error_feedback').append(""); },
				complete: 	function(){ $('#data_table_loading').remove(); }
			});
		} else { 
			displayDepressionLanding();
		}
		
		

		
	}
	else {
		feed = (category == 'all')? 'feed=medical_group' : 'feed=measure_data_current/'+category+'';
		feed = (sub_category)? 'feed=measure_component_current/'+sub_category+'' : feed;
		
		$('#data_table_loading').html("<div id='data_table_loading_inner'><img alt='Loading...' src='assets/loading.gif' /></div>");
		
		$.ajax({
			type: "POST", url: "actions/get_xml.php",
			data: feed,
			success: 	function(xml){ populateDataList(sf, category, sub_category, xml); measure_data_retrieved = 1;},		
			error: 		function(){ $('#error_feedback').append(""); },
			complete: 	function(){ $('#data_table_loading').remove(); }
		});
	}
}
/* ----- Get COST Measure Data 
------------------------------------------------------------------------------------- */
function getCostMeasureData(sf, category, sub_category){
	
	feed = (category == 'all')? 'feed=medical_group' : 'feed=measure_data_current/'+category+'';
	feed = (sub_category)? 'feed=measure_component_current/'+sub_category+'' : feed;
	
	$('#data_table_loading').html("<div id='data_table_loading_inner'><img alt='Loading...' src='assets/loading.gif' /></div>");
	
	$.ajax({
		type: "POST", url: "actions/get_xml.php",
		data: feed,
		success: 	function(xml){ populateDataList(sf, category, sub_category, xml); measure_data_retrieved = 1;},		
		error: 		function(){ $('#error_feedback').append(""); },
		complete: 	function(){ $('#data_table_loading').remove(); }
	});
}

/* ----- Get Comparison Data 
------------------------------------------------------------------------------------- */

function getComparisonData(sf, category, sub_category, compare){
	$('#data_table_loading').html("<div id='data_table_loading_inner'><img alt='Loading...' src='assets/loading.gif' /></div>");
	compare_ids = compare.split(',');	
	
	row = 1;
	
	if(category == 'all'){
		
		cats = new Array();
		cat_names = new Array();
		
		// if category = all
		// Find array of categories
		feed = 'feed=measure_list/'+sf+'';	
		$.ajax({
			type: "POST", url: "actions/get_xml.php",
			data: feed,
			success: 	function(xml){ 
				$('measure-category',xml).each(function(i){
					name = $(this).find('public-name:first').text();
					if(name != 'Patient Experience'){
						id = $(this).find('id:first').text();
						cats.push(id);
						cat_names.push(name);
					}
				});
				
				// loop through each category, set row to j, add the new row "after" previous row, and category = category
				for(j=0; j<cats.length; j++){
					row_color = (j%2)? " odd " : " even ";
					
					$('#compare_row_'+(row-1)+'').after(
						"<tr id='compare_row_"+row+"'>"+
							"<td id='compare_row_"+row+"_category' class='compare_sidebar_mid'>"+cat_names[j]+"</td>"+
							"<td id='compare_row_"+row+"_col_1_data' class='compare_main_mid graph_area "+row_color+"'></td>"+
							"<td id='compare_row_"+row+"_col_2_data' class='compare_main_mid graph_area "+row_color+"'></td>"+
							"<td id='compare_row_"+row+"_col_3_data' class='compare_main_mid graph_area "+row_color+"'></td>"+
						"</tr>"
					);
					
					// loop through the compare ids and send to getComparisonData2 for each, set col = i and row = 1
					for(i=0; i<(compare_ids.length-1); i++){ getComparisonData2(i, row, sf, cats[j], sub_category, compare_ids[i]); }	
						
					row++;
				}
				
			},		
			error: 		function(){ $('#error_feedback').append(""); },
			complete: 	function(){ }
		});		
		
	}
	else {

		$('#compare_row_0').after(
			"<tr id='compare_row_1'>"+
				"<td id='compare_row_1_category' class='compare_sidebar_mid'></td>"+
				"<td id='compare_row_1_col_1_data' class='compare_main_mid graph_area odd'></td>"+
				"<td id='compare_row_1_col_2_data' class='compare_main_mid graph_area odd'></td>"+
				"<td id='compare_row_1_col_3_data' class='compare_main_mid graph_area odd'></td>"+
			"</tr>"
		);
		
		// If a single category is selected
		// loop through the compare ids and send to getComparisonData2 for each, set col = i and row = 1
		for(i=0; i<(compare_ids.length-1); i++){ 
			getComparisonData2(i, row, sf, category, sub_category, compare_ids[i]); 
		}	
	}
	
}

function getComparisonData2(i, row, sf, category, sub_category, compare_id){
	if(category=='4') {

		if(sub_category == 3) { 
			feed = 'feed=clinic_measure_history/4/' + compare_id + '';
		} else if (sub_category == 7) { 
			feed = 'feed=clinic_depression_history/'+sub_category+'/' + compare_id + '';
		} else if (sub_category == 8) { 
			feed = 'feed=clinic_depression_history/'+sub_category+'/' + compare_id + '';
		} else { 
			feed = 'feed=clinic_measure_history/4/' + compare_id + '';
		}


	} else { 
	feed = (sf=='group')? 'feed=group_measure_history/'+category+'/'+compare_id+'' : 'feed=clinic_measure_history/'+category+'/'+compare_id+''
	if(sub_category!=''){
		feed = (sf=='group')? 'feed=group_component_history/'+sub_category+'/'+compare_id+'' : 'feed=clinic_component_history/'+sub_category+'/'+compare_id+'';
	}
	}
	$.ajax({
		type: "POST", url: "actions/get_xml.php",
		data: feed,
		success: 	function(xml){ populateComparison(1, compare_id, i, row, sf, category, sub_category, xml); },		
		error: 		function(xml){ populateComparison(0, compare_id, i, row, sf, category, sub_category, xml); },
		complete: 	function(){  }
	});	
}

function populateDepressionData(error ,sf, name_id, category, sub_category, blank_var, xml) {
if(xml) {
	
	var profile_title = "";

	if(sub_category == 3) { 
		profile_title = "Depression: Utilization of the PHQ-9";
	} else if (sub_category == 7) { 
		profile_title = "Depression: Remission at 6 Months";
	} else if (sub_category == 8) {
		profile_title = "Depression: Remission at 12 Months";
	} else { 
		profile_title = "Depression: Undefined";
	}

	 var the_placeholder = 'placeholder' + sub_category;
	 
	 
	 		

	 
		 
		 	if(sub_category == 3) {
		 		$('#profile_category_data_table').append( "" +
				"<tr class='colbody_top'><td colspan='2' class='category'><br/><h2>" + profile_title + "</h2></td></tr>");		
						$('#profile_category_data_table').append( "" +
				"<tr class='hidethis_on_add"+sub_category+"'><td colspan='2' class=''><br/>There is no current data for this particular measure.<br/><br/></td></tr>");			

		 	// do the flot graph for it!
		 	
		 	// instantiate two data lines d1 is state average, d2 is clinic average
				var d1 = [];
				var d2 = [];
				var xaxis_ticks = [];

			// array is date, value
			

		 		
		 		
		 	
	

				
				countervar = 3;
				var first_rate;
				var first_overall_rate;
				var year;
				var overall_rate;
		 		$('public-measure-summary',xml).each(function(i){
		 		$('.hidethis_on_add' +sub_category).hide();
		 		// while looping, append data to the data points, first explode the date by  " through "
		 		
				 	rate = roundNumber($(this).find('rate:first').text(), 3) * 100;
					overall_rate = roundNumber($(this).find('overall-rate:first').text(), 3) * 100;
					data_source = $(this).find('data-source:first').text();		
					measure_period = $(this).find('measure-period-id:first').text(); // string type
					measure_period_label = $(this).find('measure-period-name:first').text(); // string type
					
	
					if(countervar == 3) { 
						first_rate = Math.round(rate);
						first_overall_rate = Math.round(overall_rate);
						year = measure_period_label;
					} 				
						d1.push([countervar, rate]);							
						d2.push([countervar, overall_rate]);

						measure_period_label = measure_period_label.replace("through", "<br/>through<br/>");
						xaxis_ticks.push([countervar, measure_period_label]);
					
					countervar--;
				});
				
				
				

				

				if(xml) {
				$('#profile_category_data_table').append ("" + 

				"<tr class='colbody_top'><td class='current_report_year'><!-- Current Report Year -->"+
								"<div class='graphs'>"+
									"<table><tr>"+
									"<td style='width: 90px;'>"+
										"<span class='graphs_small_text'>Rate:</span> "+first_rate+"%<br />"+
										"<div style='line-height: 0px; position: relative; top: "+(105-first_overall_rate)+"px; left: 66px;'>*</div>"+
										"<div style='background: #000; line-height: 0px; font-size: 0px; height: 3px; position: relative; top: "+(100-overall_rate)+"px; margin-right: 30px;'></div>"+
										"<div style='border: 1px solid #4E6751; margin-right: 30px; height: 100px; background: #5E7761;'>"+
											"<div style='background: #fff; height: "+(100-first_rate)+"px;'></div>"+
										"</div>"+
										"<div class='year'>"+year+"</div>"+
										"<span class='graphs_small_text'>(* Avg: "+first_overall_rate+"%)" + 
										
									"</span><br />"+
									"</td>"+
									"</tr></table>"+
								"</div>"+
							"</td>" +				
				"<td class='historic_report_years'><br/><div class='flot_lgd_label'>Legend</div>" + 
				'<div id="flot_legend"><table style="font-size: smaller; color: rgb(84, 84, 84);"><tbody><tr><td class="legendColorBox"><img src="assets/d1.gif" /></td>' +
				'<td class="legendLabel">Clinic Average</td></tr><tr><td class="legendColorBox"><img src="assets/d2.gif" /></td><td class="legendLabel">State Average</td></tr></tbody></table></div>' + 
				"<div id='"+the_placeholder+"' class='graph_placeholder'></div></td></tr>"); 
				
				
				ticks_array = [];
				countervar = 3;
				
				
				$.each(xaxis_ticks, function(key, value) { 


					ticks_array.push([countervar,value[1]]);	
					countervar--;

				});
				
				
				
				


				
				    $.plot($("#" + the_placeholder), [
    /* Seperate data properties from axis and grid properties $.plot('jquery dom element'), [data array], [properties array] */
				        {
				            data: d1,           
						    label: "Clinic Average",
						    lines: {show: true, fill: false},
						    points: {show: true, fill: true, radius: 3, fillColor: "#a5c7bd"},
						    clickable: false, 
						    hoverable: true, 
						    shadowSize: 5,
						    color: "#a5c7bd"
				
				        },
				         {
				            data: d2,           
						    label: "State Average",
						    lines: { show: true, fill: false },
						    points: { show: true, fill: true, radius: 3, fillColor: "#635938" },
						    clickable: false, 
						    hoverable: true, 
						    shadowSize: 5,
						    color: "#635938"
				
				
				        }       
				    ], 
				    { 
				    xaxis: {
				    		/*mode: "time", */
				    		/*timeformat: "%m/%y",*/
				    		ticks: ticks_array
				    		
	 
				    },
				    yaxis:  {
				    		tickFormatter: function formatter(val, axis) { return val + "%" },
					    	ticks: 3,
					    	color: "#FFFFFF",
					    	max: 100
				    },
				    grid: {
							//backgroundColor: "#F6F3E8",
							backgroundColor: "#FFFFFF",
							tickColor: "#d3e8e2",
							borderWidth: 1,
							borderColor: "#A5C6BD",
							show: true,
							hoverable: true
							
				
					},
					legend: {
							show: false,
							labelBoxBorderColor: "#FFFFFF",
							//noColumns: 5,
							position: "se", // nw, ne, sw, se
						    margin: [10,10], // x and y margin
						    backgroundColor: "#FFFFFF",
						    backgroundOpacity: .5,
							container: $('#flot_legend')
							
				  	}

				}); 
				var previousPoint = null;
				    $("#" + the_placeholder).bind("plothover", function (event, pos, item) {
						$("#x").text(pos.x.toFixed(1));
				        $("#y").text(pos.y.toFixed(1));
				
				            if (item) {
				                if (previousPoint != item.datapoint) {
				                    previousPoint = item.datapoint;
				                    $("#tooltip").remove();
				                    var x = item.datapoint[0].toFixed(1), y = item.datapoint[1].toFixed(1);
				                    //showTooltip(item.pageX, item.pageY, item.series.label + " of " + x + " = " + y);
				                    showTooltip(item.pageX, item.pageY, y + "%");
				                }
				            }
				            else {
				                $("#tooltip").remove();
				                previousPoint = null;            
				            }
				
				    });
				

				}
				
			} else { 
			
				// if(profile_title != "Depression: Remission at 12 Months") { // commented out because 12 month data now exists.
			$('#profile_category_data_table').append(
					"<tr><td colspan='2' class='category'><h2>"+profile_title+"</h2></td></tr>"+
					"<tr class='hidethis_on_add"+sub_category+"'><td colspan='2' class=''>" +
					"<br/>There is no current data for this particular measure.<br/><br/></td></tr>");
			$('public-measure-summaries',xml).each(function(i){
			
			$('.hidethis_on_add' +sub_category).hide();
				$('#profile_category_data_table').append("<tr>"+
					"<td class='current_report_year_title'><h4>Most Recent Report</h4></td>"+
					"<td class='historic_report_years_title'><h4>Past Reports</h4><br/></td>"+
					"</tr>");
				first_rate = Math.round($(this).find('rate:first').text() *100);
				first_overall_rate = Math.round($(this).find('overall-rate:first').text() * 100);
				first_data_source = $(this).find('data-source:first').text();		
				first_year = $(this).find('measure-period-name:first').text();		
				//cat_id = 39;
					
				


				$('#profile_category_data_table').append(
							"<tr class='colbody_top'>"+
							"<td class='current_report_year'><!-- Current Report Year -->"+
								"<div class='graphs'>"+
									"<table><tr>"+
									"<td style='width: 90px;'>"+
										"<span class='graphs_small_text'>Rate:</span> "+first_rate+"%<br />"+
										"<div style='line-height: 0px; position: relative; top: "+(104-first_overall_rate)+"px; left: 66px;'>*</div>"+
										"<div style='background: #000; line-height: 0px; font-size: 0px; height: 3px; position: relative; top: "+(100-first_overall_rate)+"px; margin-right: 30px;'></div>"+
										"<div style='border: 1px solid #4E6751; margin-right: 30px; height: 100px; background: #5E7761;'>"+
											"<div style='background: #fff; height: "+(100-first_rate)+"px;'></div>"+
										"</div>"+
										"<div class='year'>"+first_year+"</div>"+
										"<span class='graphs_small_text'>(* Avg: "+first_overall_rate+"%)</span><br />"+
									"</td>"+
									"</tr></table>"+
								"</div>"+
							"</td>"+
							"<td class='historic_report_years'>"+
								"<div class='graphs'>"+
									"<table class='category_historic_table'><tr id='"+sub_category+"_historic'></tr></table>"+
								"</div>"+	
							"</td>"+
							"</tr>"
						);
						//alert($('public-measure-summary',xml).length);
						var temp_rate;
						var temp_overall_rate;
						var temp_year;
						var data_source;
					$('public-measure-summary',xml).each(function(i){
					
					temp_rate = Math.round($(this).find('rate:first').text() *100);
					temp_overall_rate = Math.round($(this).find('overall-rate:first').text() * 100);
					temp_data_source = $(this).find('data-source:first').text();		
					temp_year = $(this).find('measure-period-name:first').text();		
						
					if (i) { 
						$("#" + sub_category +"_historic").append("" +
						"<td style='width: 90px;'>"+
										"<span class='graphs_small_text'>Rate:</span> "+temp_rate+"%<br />"+
										"<div style='line-height: 0px; position: relative; top: "+(104-temp_overall_rate)+"px; left: 66px;'>*</div>"+
										"<div style='background: #000; line-height: 0px; font-size: 0px; height: 3px; position: relative; top: "+(100-temp_overall_rate)+"px; margin-right: 30px;'></div>"+
										"<div style='border: 1px solid #4E6751; margin-right: 30px; height: 100px; background: #5E7761;'>"+
											"<div style='background: #fff; height: "+(100-temp_rate)+"px;'></div>"+
										"</div>"+
										"<div class='year'>"+temp_year+"</div>"+
										"<span class='graphs_small_text'>(* Avg: "+temp_overall_rate+"%)</span><br />"+
									"</td>");
					}
				});
						
						
			});
			
		 //} remove this if
	 
	 }
	 
	 
	}  	
} // end populate profile data


/* ----- Get Profile Info / Data 
------------------------------------------------------------------------------------- */

function getProfileInfo(sf, category, sub_category, name_id){
		
	feed = (sf=='group')? 'feed=group_profile/'+name_id+'' : 'feed=clinic_profile/'+name_id+'';
	$('#data_table_loading').html("<div id='data_table_loading_inner'><img alt='Loading...' src='assets/loading.gif' /></div>");

	$.ajax({
		type: "POST", url: "actions/get_xml.php",
		data: feed,
		success: 	function(xml){ populateProfileInfo(sf, name_id, category, xml); getProfileData(sf, category, sub_category, name_id);  },		
		error: 		function(){ $('#error_feedback').append(""); },
		complete: 	function(){ $('#data_table_loading').remove(); }
	});	
}

function getProfileData(sf, category, sub_category, name_id){
	
	$('#profile_data_table_loading').html("<div id='data_table_loading_inner'><img alt='Loading...' src='assets/loading_white.gif' /></div>");
	$('#profile_category_data').append("<table id='profile_category_data_table'></table>");
	
	if(category=='all'){
		
		cats = new Array();
		cat_names = new Array();
		
		// if category = all
		// Find array of categories
		feed = 'feed=measure_list/'+sf+'';	
		$.ajax({
			type: "POST", url: "actions/get_xml.php",
			data: feed,
			success: 	function(xml){ 
				$('measure-category',xml).each(function(i){
					id = $(this).find('id:first').text();
					cats.push(id);
					name = $(this).find('public-name:first').text();
					cat_names.push(name);					
				});
				
				for(j=0; j<cats.length; j++){
					feed = (sf=='group')? 'feed=group_measure_history/'+cats[j]+'/'+name_id+'' : 'feed=clinic_measure_history/'+cats[j]+'/'+name_id+'';
					if(cats[j] == '18') { // conditionals for HIT
						
						feed = (sf=='group')? 'feed=hit_group_data/103/'+name_id+'' : 'feed=hit_clinic_data/103/'+name_id+'';

						$.ajax({
						type: "POST", url: "actions/get_xml.php",
						data: feed,
						success: 	function(xml){ populateProfileDataHIT(1, sf, name_id, cats[j], sub_category, '', xml); },		
						error: 		function(xml){ populateProfileDataHIT(0, sf, name_id, cats[j], sub_category, '', xml);  },
						complete: 	function(){ $('#profile_data_table_loading').remove(); }
					});	
					} else if (cats[j] == '16'){ // patient experience
					feed = (sf=='group')? 'feed=group_measure_history/'+cats[j]+'/'+name_id+'' : 'feed=clinic_measure_history/'+cats[j]+'/'+name_id+'';
						$.ajax({
						type: "POST", url: "actions/get_xml.php",
						data: feed,
						success: 	function(xml){ populateProfileDataPE(1, sf, name_id, cats[j], sub_category, '', xml); },		
						error: 		function(xml){ populateProfileDataPE(0, sf, name_id, cats[j], sub_category, '', xml);  },
						complete: 	function(){ $('#profile_data_table_loading').remove(); }
					});	
					} else if (cats[j] == '4'){ //  NEW DEPRESSION
				
					var loop_populate = new Array();				
					
					loop_populate.push(7);
					loop_populate.push(8);
					loop_populate.push(3);
					var feed="";
					
					//for(m=0; m<loop_populate.length;m++) { 	
					$.each(loop_populate, function(key, value) { 

									
						if(value == 3) { 
							feed = 'feed=clinic_measure_history/4/' + name_id + '';
						} else if (value == 7) { 
							feed = 'feed=clinic_depression_history/'+value+'/' + name_id + '';
						} else if (value == 8) { 
							feed = 'feed=clinic_depression_history/'+value+'/' + name_id + '';
						} else { 
							feed = 'feed=clinic_measure_history/4/' + name_id + '';
						}
						
						$.ajax({
							type: "POST", 
							url: "actions/get_xml.php?rand=",
							data: feed,
							success: 	function(xml){ populateDepressionData(1,sf,name_id,4,value,'',xml)},		
							error: 		function(xml){ populateDepressionData(1,sf,name_id,4,value,'',"");  },
							complete: 	function(){ $('#profile_data_table_loading').remove(); }
						});	
						

					});
						
					
					
					
					} else {
					$.ajax({
						type: "POST", url: "actions/get_xml.php",
						data: feed,
						success: 	function(xml){ populateProfileData(1, sf, name_id, cats[j], sub_category, '', xml); },		
						error: 		function(xml){ populateProfileData(0, sf, name_id, cats[j], sub_category, '', xml);  },
						complete: 	function(){ $('#profile_data_table_loading').remove(); }
					});	
					}
				}
				
			},		
			error: 		function(){ $('#error_feedback').append(""); },
			complete: 	function(){ }
		});
		
		
	}
	else if(category == '4'){ // depression exception

				var loop_populate = new Array();				
					
					loop_populate.push(7);
					loop_populate.push(8);
					loop_populate.push(3);
					
					var feed="";
					
					//for(m=0; m<loop_populate.length;m++) { 	
					$.each(loop_populate, function(key, value) { 
									
						if(value == 3) { 
							feed = 'feed=clinic_measure_history/4/' + name_id + '';
						} else if (value == 7) { 
							feed = 'feed=clinic_depression_history/'+value+'/' + name_id + '';
						} else if (value == 8) { 
							feed = 'feed=clinic_depression_history/'+value+'/' + name_id + '';
						} else { 
							feed = 'feed=clinic_measure_history/4/' + name_id + '';
						}
						
						$.ajax({
							type: "POST", 
							url: "actions/get_xml.php?rand=",
							data: feed,
							async: false,
							success: 	function(xml){ populateDepressionData(1,sf,name_id,4,value,'',xml)},		
							error: 		function(xml){ populateDepressionData(1,sf,name_id,4,value,'',"")},
							complete: 	function(){ $('#profile_data_table_loading').remove(); }
						});	
						

					});
						


	}
	else if(category == '18'){ // HIT exception

				 // conditionals for HIT
						
						feed = (sf=='group')? 'feed=hit_group_data/103/'+name_id+'' : 'feed=hit_clinic_data/103/'+name_id+'';

						$.ajax({
						type: "POST", url: "actions/get_xml.php",
						data: feed,
						success: 	function(xml){ populateProfileDataHIT(1, sf, name_id, 18, sub_category, '', xml); },		
						error: 		function(xml){ populateProfileDataHIT(0, sf, name_id, 18, sub_category, '', xml);  },
						complete: 	function(){ $('#profile_data_table_loading').remove(); }
					});	
					 
						


	}
	
	 else {
		feed = (sf=='group')? 'feed=group_measure_history/'+category+'/'+name_id+'' : 'feed=clinic_measure_history/'+category+'/'+name_id+'';
		if(sub_category!=''){
			feed = (sf=='group')? 'feed=group_component_history/'+sub_category+'/'+name_id+'' : 'feed=clinic_component_history/'+sub_category+'/'+name_id+'';
		}
		$.ajax({
			type: "POST", url: "actions/get_xml.php",
			data: feed,
			success: 	function(xml){ populateProfileData(1, sf, name_id, category, sub_category, '', xml); },		
			error: 		function(xml){ populateProfileData(0, sf, name_id, category, sub_category, '', xml); },
			complete: 	function(){ $('#profile_data_table_loading').remove(); }
		});	

	}
}


// Doing things with Feeds
// ----------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------


/* ----- Populate Measure Dropdown 
------------------------------------------------------------------------------------- */

function populateCategoryDropdown(xml){
	if($('#sf').val() != 'hospital') {
		$('#measure_list_dropdown').empty();
		$('#measure_list_dropdown').append("<option value='all'>All</option>");
		
		// Parse XML and append data to the dropdown
		$('measure-category',xml).each(function(i){		
			// Find top level (non component) data
			id = $(this).find('id:first').text();			
			name = $(this).find('public-name:first').text();
			$('#measure_list_dropdown').append("<option value='"+id+"'>"+name+"</option>");
	}	);
	}
}

/* ----- Populate Measure Sidebar 
------------------------------------------------------------------------------------- */

function populateCategorySidebar(xml){
	
	var page = $('#page').val();
	var sf = $('#sf').val();
	var category = $('#category').val();
	var sub_category = $('#sub_category').val();
	var name_id = $('#name_id').val();
	var compare = $('#compare').val();
	var search_phrase = $('#search_phrase').val();
	
	// Parse XML and append data to the sidebar
	$('measure-category',xml).each(function(i){
	
		// Find top level (non component) data
		id = $(this).find('id:first').text();			
		name = $(this).find('public-name:first').text();

		selected = (category == id)? " id='cat_"+id+"' class='selected' " : "";
				
		
		
		
		
		// if pat exp data, append new lists
		if(id=='16'){
			pe_page_change = (page=='profile')? "our_reports" : page;
			$('#sb_nav_bottom').after(
				"<br />"+
				//"<div id='sidebar_label'>Category / Condition:</div>"+
				"<div class='sb_top'><img alt='' src='assets/sidebar/sb_top.gif' /></div>"+
					"<ul id='sb_nav' class='sb_nav'>"+
						"<li "+selected+">"+
							"<a class='sb_link' id='sb_nav_"+id+"' href='?p="+pe_page_change+"&amp;sf="+sf+"&amp;search_phrase="+search_phrase+"&amp;category="+id+"&amp;name_id="+name_id+"&compare="+compare+"'>"+name+"</a>"+
						"</li>"+
					"</ul>"+
				"<div class='sb_bottom'><img alt='' src='assets/sidebar/sb_bottom.gif' /></div>"
			);
		}
		// if hit data, append new list
		else if(id=='18' && sf == 'clinic'){
			pe_page_change = (page=='profile')? "our_reports" : page;
			$('#sb_nav_bottom').after(
				"<br />"+
				//"<div id='sidebar_label'>Category / Condition:</div>"+
				"<div class='sb_top'><img alt='' src='assets/sidebar/sb_top.gif' /></div>"+
					"<ul id='sb_nav' class='sb_nav'>"+
						"<li "+selected+">"+
							"<a class='sb_link' id='sb_nav_"+id+"' href='?p="+pe_page_change+"&amp;sf="+sf+"&amp;search_phrase="+search_phrase+"&amp;category="+id+"&amp;name_id="+name_id+"&compare="+compare+"'>"+name+"</a>"+
						"</li>"+
					"</ul>"+
				"<div class='sb_bottom'><img alt='' src='assets/sidebar/sb_bottom.gif' /></div>"
			);
		}
		// if depression, append new hardcoded sub list
		else if(id=='4'){
			$('#sb_nav').append("<li "+selected+"><a class='sb_link' id='sb_nav_"+id+"' href='?p=our_reports&amp;sf="+sf+"&amp;search_phrase="+search_phrase+"&amp;category="+id+"&amp;name_id="+name_id+"&compare="+compare+"'>"+name+"</a></li>");
			if(selected) { 
				sub_cat_id = parseInt($('#sub_category').val());		
				sub_category_selected3 = (3 == sub_cat_id)? "class='selected'" : "";
				sub_category_selected7 = (7 == sub_cat_id)? "class='selected'" : "";
				sub_category_selected8 = (8 == sub_cat_id)? "class='selected'" : "";
			
				$("#cat_"+id+"").append("<ul id='sb_sub_nav'></ul>");				
				$("#sb_sub_nav").append("<li "+ sub_category_selected7 +"><a id='sb_sub_nav_7' href='?p="+page+"&amp;sf="+sf+"&amp;category="+id+"&amp;sub_category=7&amp;name_id="+name_id+"&compare="+compare+"'>Remission at 6 Months</a></li>");
				$("#sb_sub_nav").append("<li "+ sub_category_selected8 +"><a id='sb_sub_nav_8' href='?p="+page+"&amp;sf="+sf+"&amp;category="+id+"&amp;sub_category=8&amp;name_id="+name_id+"&compare="+compare+"'>Remission at 12 Months</a></li>");
				$("#sb_sub_nav").append("<li "+ sub_category_selected3 +"><a id='sb_sub_nav_3' href='?p="+page+"&amp;sf="+sf+"&amp;category="+id+"&amp;sub_category=3&amp;name_id="+name_id+"&compare="+compare+"'>Utilization of the PHQ-9</a></li>");
			}
			
			
			
		}
		// else, just append to main list
		else {
			$('#sb_nav').append("<li "+selected+"><a class='sb_link' id='sb_nav_"+id+"' href='?p="+page+"&amp;sf="+sf+"&amp;search_phrase="+search_phrase+"&amp;category="+id+"&amp;name_id="+name_id+"&compare="+compare+"'>"+name+"</a></li>");
		}
		
		
		// If this is the selected Category
		if(category == id){
				
			$("#cat_"+id+"").append("<ul id='sb_sub_nav'></ul>");
			
			// Find and Populate Component Measures
			$('component', $(this)).each(function(i){
				sub_cat_id = $(this).find('id').text();			
				name = $(this).find('public-name').text();
				
				sub_category_selected = (sub_category == sub_cat_id)? "class='selected'" : "";
				
				$("#sb_sub_nav").append("<li "+sub_category_selected+"><a id='sb_sub_nav_"+sub_cat_id+"' href='?p="+page+"&amp;sf="+sf+"&amp;category="+id+"&amp;sub_category="+sub_cat_id+"&amp;name_id="+name_id+"&compare="+compare+"'>"+name+"</a></li>");
			});
		}
		
	});
}

/* ----- Populate Data List 
------------------------------------------------------------------------------------- */

function populateDataList(sf, category, sub_category, xml){
	
	var count=0;

	// IF Category is ALL
	// --------------------------------------------------------------------------------	
	if(category == 'all'){
		
		$('#sort_by_rate').html('');
		
		// IF ON THE SEARCH PAGE
		// --------------------------------------------------------------------------------
		if( $('#page').val() == 'search' ){ 
			
			object_label = (sf=='group')? 'medical-group' : 'clinic';
			id_label = (sf=='group')? 'medical-group-identifier' : 'id';

			// Parse XML and append data to the dropdown
			$(object_label,xml).each(function(i){
				cat_id = $('#category').val();
				this_name_id = $(this).find(id_label).text();
				name = $(this).find('name:first').text();
				city = $(this).find('city:first').text();
				zipcode = $(this).find('zip-code:first').text();
				page = $('#page').val();
				goto_profile = (page=='cost_reports' ||page=='cost_landing' || page=='cost_search') ? 'cost_profile' : 'profile';
				if(name){				
					$('#data_table_tbody').append(
						"<tr class='colbody_top'>"+
							"<td class='name'><a class='data_list_name' href='?p=profile&amp;sf="+sf+"&amp;category="+cat_id+"&amp;name_id="+this_name_id+"'>"+name+"</a></td>"+
							"<td class='secondary'>"+city+"</td>"+
							"<td class='secondary'>"+zipcode+"</td>"+
							"<td class='graph_area'></td>"+
							"<td class='view_details'><a href='?p=" + goto_profile +"&amp;sub_category="+sub_category+"&amp;sf="+sf+"&amp;category="+cat_id+"&amp;name_id="+this_name_id+"'>view profile ></a></td>"+
							"<td class='compare_button_cell'><div class='compare_button'><input class='compare_checkbox' type='checkbox' name='' value='"+this_name_id+"' /></div></td>"+							
						"</tr>"
					);				
				}				
				count++;				
			});
		}	
		// IF NOT ON THE SEARCH PAGE
		// --------------------------------------------------------------------------------
		else {
			
			var object_label = (sf=='group')? 'medical-group' : 'active-clinic'; 
			var id_label = (sf=='group')? 'medical-group-identifier' : 'id'; 
			var page = $('#page').val();
			var goto_profile = (page=='cost_reports' ||page=='cost_landing' || page=='cost_search') ? 'cost_profile' : 'profile';
			// Parse XML and append data to the dropdown
			$(object_label,xml).each(function(i){
				cat_id = $('#category').val();
				this_name_id = $(this).find(id_label).text();
				name = $(this).find('name:first').text();
				city = $(this).find('city:first').text();
				zipcode = $(this).find('zip-code:first').text();
				sub_category = $('#sub_category').val();
				has_data = $(this).find('has-dds-data:first').text();
				
				if( ( sf=='group' && name ) || ( sf=='clinic' && has_data=='true' && name ) ){				
					$('#data_table_tbody').append(
						"<tr class='colbody_top'>"+
							"<td class='name'><a class='data_list_name' href='?p=" + goto_profile + "&amp;sf="+sf+"&amp;category="+cat_id+"&amp;name_id="+this_name_id+"&amp;sub_category="+sub_category +"'>"+name+"</a></td>"+
							"<td class='secondary'>"+city+"</td>"+
							"<td class='secondary'>"+zipcode+"</td>"+
							"<td class='graph_area'></td>"+
							"<td class='view_details'><a href='?p=" + goto_profile + "&amp;sf="+sf+"&amp;sub_category="+sub_category+"&amp;category="+cat_id+"&amp;name_id="+this_name_id+"'>view profile ></a></td>"+
							"<td class='compare_button_cell'><div class='compare_button'><input class='compare_checkbox' type='checkbox' name='' value='"+this_name_id+"' /></div></td>"+							
						"</tr>"
					);				
				}
				count++;		
			});	
		}
	
	}

	// IF Category is NOT ALL
	// --------------------------------------------------------------------------------		
	else {

		var id_label = (sf=='group')? 'medical-group-identifier' : 'clinic-id'; 
		var name_label = (sf=='group')? 'medical-group-name' : 'clinic-name';
		
		
		pe_count=0;
		
		// Parse XML and append data to the dropdown
		if(category == '4' && $('#sub_category').val() == "") {//need to display depression landing page
			
		} else {
		
		$('public-measure-summary',xml).each(function(i){
					
			clinic_name = $(this).find('clinic-name').text();
		
			cat_id = $(this).find('measure-id:first').text();
			this_name_id = $(this).find(id_label+':first').text();
			name = $(this).find(name_label+':first').text();
			city = (sf=='group')? $(this).find('medical-group-city:first').text() : $(this).find('clinic-city:first').text();
			zipcode = (sf=='group')? $(this).find('medical-group-zip:first').text() : $(this).find('clinic-zip:first').text();
			rate = Math.round($(this).find('rate:first').text() *100);
			overall_rate = Math.round($(this).find('overall-rate:first').text() * 100);
			sub_category = $('#sub_category').val();
			data_source = $(this).find('data-source:first').text();
			
			
			// Display asterisk if not DDS Data and viewing Diabetes or Vascular data
			//edited for cat 4
			//if( ( (category == '1' || category == '2' || category == '4') && data_source == 'DDS') || ( category !='1' && category !='2' && category != '4') ){
						if( ( (category == '1' || category == '2') && data_source == 'DDS') || ( category !='1' && category !='2') ){
				data_area = "<div class='rate_num left'>"+rate+"%</div>"+
							"<div class='average_bar left' style='position:relative; left: "+(overall_rate+3)+"px; line-height: 0px; width: 3px; height: 13px;'></div>"+
							"<div class='left'>"+
								"<div class='graph'>"+
									"<div class='rate' style='width: "+rate+"px;'></div></div>"+
								"</div>"+
							"<div class='clear'></div>"; 
			}
			else {
				data_area = "<div class='rate_num asterisk'>*</div>";
			}
			
			
			
			// If Category = Patient Experience, get multiple rates, and display
			// And remove compare function
			if( category == '16' ){
				
				// get patient experience specific data points
				access_comp_rate = Math.round( $(this).find('access-comp-rate:first').text() * 100);
				access_comp_rate_overall = Math.round( $(this).find('access-comp-rate-overall:first').text() * 100);
				access_comp_stars = $(this).find('access-comp-stars:first').text();
				access_comp_rate_graph = (access_comp_stars == '3')? "<div class='rate' style='background: #5bc95e; width: "+access_comp_rate+"px;'></div></div>" : "<div class='rate' style='background: #ffe972; width: "+access_comp_rate+"px;'></div></div>";
				
				$('#col_1_overall_average').html('<b>Average = '+access_comp_rate_overall+'%</b>');
				
				doc_comp_rate = Math.round( $(this).find('doc-comp-rate:first').text() * 100);
				doc_comp_rate_overall = Math.round( $(this).find('doc-comp-rate-overall:first').text() * 100);
				doc_comp_stars = $(this).find('doc-comp-stars:first').text();
				doc_comp_rate_graph = (doc_comp_stars == '3')? "<div class='rate' style='background: #5bc95e; width: "+doc_comp_rate+"px;'></div></div>" : "<div class='rate' style='background: #ffe972; width: "+doc_comp_rate+"px;'></div></div>";

				$('#col_2_overall_average').html('<b>Average = '+doc_comp_rate_overall+'%</b>');

				staff_comp_rate = Math.round( $(this).find('staff-comp-rate:first').text() * 100);
				staff_comp_rate_overall = Math.round( $(this).find('staff-comp-rate-overall:first').text() * 100);
				staff_comp_stars = $(this).find('staff-comp-stars:first').text();
				staff_comp_rate_graph = (staff_comp_stars == '3')? "<div class='rate' style='background: #5bc95e; width: "+staff_comp_rate+"px;'></div></div>" : "<div class='rate' style='background: #ffe972; width: "+staff_comp_rate+"px;'></div></div>";

				$('#col_3_overall_average').html('<b>Average = '+staff_comp_rate_overall+'%</b>');

				rating_9_10_rate = Math.round( $(this).find('rating-9-10-rate:first').text() * 100);
				rating_9_10_rate_overall = Math.round( $(this).find('rating-9-10-rate-overall:first').text() * 100);
				rating_9_10_stars = $(this).find('rating-9-10-stars:first').text();
				rating_9_10_rate_graph = (rating_9_10_stars == '3')? "<div class='rate' style='background: #5bc95e; width: "+rating_9_10_rate+"px;'></div></div>" : "<div class='rate' style='background: #ffe972; width: "+rating_9_10_rate+"px;'></div></div>";
				
				$('#col_4_overall_average').html('<b>Average = '+rating_9_10_rate_overall+'%</b>');


				// redefine data_area
				if(access_comp_rate=='-100'){ data_area1 = "<div class='rate_num asterisk'>*</div>"; }
				else {
				data_area1 = "<div class='pe_rate_num'>"+access_comp_rate+"%</div>"+
							"<!--div class='average_bar left' style='position:relative; left: "+(access_comp_rate_overall+3)+"px; line-height: 0px; width: 3px; height: 13px;'></div-->"+
							"<div class='left'><div class='graph'>"+access_comp_rate_graph+"</div><div class='clear'></div>";
				}
				if(doc_comp_rate=='-100'){ data_area2 = "<div class='rate_num asterisk'>*</div>"; }
				else {
				data_area2 = "<div class='pe_rate_num'>"+doc_comp_rate+"%</div>"+
							"<!--div class='average_bar left' style='position:relative; left: "+(doc_comp_rate_overall+3)+"px; line-height: 0px; width: 3px; height: 13px;'></div-->"+
							"<div class='left'><div class='graph'>"+doc_comp_rate_graph+"</div><div class='clear'></div>";
				}
				if(staff_comp_rate=='-100'){ data_area3 = "<div class='rate_num asterisk'>*</div>"; }
				else {				
				data_area3 = "<div class='pe_rate_num'>"+staff_comp_rate+"%</div>"+
							"<!--div class='average_bar left' style='position:relative; left: "+(staff_comp_rate_overall+3)+"px; line-height: 0px; width: 3px; height: 13px;'></div-->"+
							"<div class='left'><div class='graph'>"+staff_comp_rate_graph+"</div><div class='clear'></div>";
				}
				if(rating_9_10_rate=='-100'){ data_area4 = "<div class='rate_num asterisk'>*</div>"; }
				else {				
				data_area4 = "<div class='pe_rate_num'>"+rating_9_10_rate+"%</div>"+
							"<!--div class='average_bar left' style='position:relative; left: "+(rating_9_10_rate_overall+3)+"px; line-height: 0px; width: 3px; height: 13px;'></div-->"+
							"<div class='left'><div class='graph'>"+rating_9_10_rate_graph+"</div><div class='clear'></div>";							
				}
				
				pe_count++;
				$('#data_table_tbody').append(
					"<tr class='colbody_top'>"+
						"<td class='pe_name'><a class='data_list_name' href='?p=profile&amp;sf="+sf+"&amp;category=all&amp;name_id="+this_name_id+"'>"+clinic_name+"<br />"+city+""+zipcode+"</a><br /><a href='?p=profile&amp;sf="+sf+"&amp;category=all&amp;name_id="+this_name_id+"'>view profile ></a></td>"+
						"<!--td class='pe_graph_area' style='font-size: 14px;'>#"+pe_count+"</td-->"+
						"<td class='pe_graph_area'>"+data_area1+"</td>"+
						"<td class='pe_graph_area'>"+data_area2+"</td>"+
						"<td class='pe_graph_area'>"+data_area3+"</td>"+
						"<td class='pe_graph_area'>"+data_area4+"</td>"+
					"</tr>"
				);	
			}

			// If Category = anything other than patient experience, display normally
			else {
			
				if( (sf=='clinic' && name) || (sf=='group' && name && clinic_name=='') ){			
										$('#data_table_tbody').append(
						"<tr class='colbody_top'>"+
							"<td class='name'><a class='data_list_name' href='?p=profile&amp;sf="+sf+"&amp;category="+cat_id+"&amp;name_id="+this_name_id+"&amp;sub_category="+sub_category +"''>"+name+"</a></td>"+
							"<td class='secondary'>"+city+"</td>"+
							"<td class='secondary'>"+zipcode+"</td>"+
							"<td class='graph_area'>"+
								data_area+
							"</td>"+
							"<td class='view_details'><a href='?p=profile&amp;sf="+sf+"&amp;category="+cat_id+"&amp;name_id="+this_name_id+"'>view profile ></a></td>"+
							"<td class='compare_button_cell'><div class='compare_button'><input class='compare_checkbox' type='checkbox' name='' value='"+this_name_id+"' /></div></td>"+
						"</tr>"
					);
					
					
					/*$('#data_table_tbody').append(
						"<tr class='colbody_top'>"+
							"<td class='name'><a class='data_list_name' href='?p=profile&amp;sf="+sf+"&amp;category="+cat_id+"&amp;name_id="+this_name_id+"&amp;sub_category="+sub_category+"'>"+name+"</a></td>"+
							"<td class='secondary'>"+city+"</td>"+
							"<td class='secondary'>"+zipcode+"</td>"+
							"<td class='graph_area'>"+
								data_area+
							"</td>"+							
							"<td class='view_details'><a href='?p=profile&amp;sf="+sf+"&amp;category="+cat_id+"&amp;sub_category="+sub_category+"&amp;name_id="+this_name_id+"'>view profile ></a></td>");
							if(category == 4) { 
							//$('#data_table_tbody').append("<td></td>");
							} else { 
														$('#data_table_tbody').append("<td class='compare_button_cell'><div class='compare_button'><input class='compare_checkbox' type='checkbox' name='' value='"+this_name_id+"' /></div></td>"+
						"</tr>");	
						}*/
								
				}
			
			}
			
			count++;
		});
		}
		// Footnotes
		if(sf=='group' && (category == '1')){
			$('#data_table_tfoot').append(
				"<tr class='colbody_top'>"+
					"<td colspan='6' class='footnote'>"+
						"* HealthScores shown here for diabetes are based on data provided by the medical group. No data was provided by this medical group. To view this medical group's score based on health plan data, click on the medical group's View Profile button."+
					"</td>"+
				"</tr>"
			);
		}
		if(sf=='group' && (category == '2')){
			$('#data_table_tfoot').append(
				"<tr class='colbody_top'>"+
					"<td colspan='6' class='footnote'>"+
						"* HealthScores shown here for vascular disease are based on data provided by the medical group. No data was provided by this medical group. To view this medical group's score based on health plan data, click on the medical group's View Profile button."+
					"</td>"+
				"</tr>"
			);
		}
		if(sf=='clinic' && (category == '16')){
			$('#data_table_tfoot').append(
				"<tr class='colbody_top'>"+
					"<td colspan='6' class='footnote'>"+
						"* Not enough patient responses were available to report this measure."+
					"</td>"+
				"</tr>"
			);
		}	
		
		
	}

	// If there were no results
	// --------------------------------------------------------------------------------	
	if(!count){
		$('#data_table_tbody').append(
			"<tr class='colbody_top'>"+
				"<td colspan='6' class='no_results'>"+
					"<b>We're sorry, there were no results found for your search.</b><br />"+
					"Here are a few ideas that will hopefully improve your search results:<br /><br />"+
					"1. Double check the spelling of your search.<br />"+
					"2. Try using fewer words.<br />"+
					"3. Try using just part of the word that you are looking for.<br />"+
				"</td>"+
			"</tr>"
		);
	}
$("#entry_table").tablesorter({ 
			

	    }); 		
}

/* ----- Populate Comparison Table 
------------------------------------------------------------------------------------- */

function populateComparison(success, compare_id, col, row, sf, category, sub_category, xml) {
	
	$('#data_table_loading').remove();
	//
	col = col+1;
	
	if(success){
		i=0;
		shown=0;
		
		// Parse XML and append data to the dropdown
		$('public-measure-summary',xml).each(function(i){
			
			data_source = $(this).find('data-source:last').text();
			cat_id = $(this).find('measure-id:last').text();
			measure_period_id = $(this).find('measure-period-id:last').text();
			current_measure_period_id = $(this).find('current-measure-period-id:last').text();
			
			
			
			//measure_period_name = $(this).find('measure-period-name').text();			
			//year = measure_period_name.split('Report');
			//year = year[0].replace(/^\s*|\s*$/g,''); // Remove white space
				
			
			
			
			cat_name = $(this).find('measure-name:last').text();
			if(sub_category!=''){ cat_name = $(this).find('component-name:last').text(); }
			this_name_id = (sf=='group')? $(this).find('medical-group-identifier:last').text() : $(this).find('clinic-id:last').text();
			
			name = (sf=='group')? $(this).find('medical-group-name:last').text() : $(this).find('clinic-name:last').text();
			if(category==4) { // depression data is not appropriately labeled as a clinic.
				name = $(this).find('medical-group-name:last').text();
			}
			var rates = [];
			
			if(i==0) {
				rate = Math.round($(this).find('rate:first').text() *100);
				i++;

			}
			
						// exception for depression data rate
			/*		
			 if(cat_id == '4') {
				// rate = Math.round($(this).find('rate:first').text() *100);										
				rate = Math.round($(this).find('six-month-remission-rate:first').text() *100);
				overall_rate = Math.round($(this).find('six-month-remission-rate-overall:first').text() * 100);
			}
			*/
			
			if(cat_id != '16'){
				//if((measure_period_id == current_measure_period_id)){ // Depression Period is an exception as it does not show the correct measure period as of yet.
					shown=1;
					$('#compare_row_'+row+'_category').html(cat_name);			
					$('#compare_col_'+col+'_title').html(name);
					$('#compare_row_'+row+'_col_'+col+'_data').html("<div class='rate_num left'>"+rate+"%</div><div class='graph left'><div class='rate' style='width: "+rate+"px;'></div></div><div class='clear'></div>");
				//}
				
				// If data is not available for the current year (2008)
					if( measure_period_id != current_measure_period_id && shown==0 ){
						$('#compare_row_'+row+'_category').html(cat_name);			
						$('#compare_col_'+col+'_title').html(name);
						$('#compare_row_'+row+'_col_'+col+'_data').html("<div class='rate_num'>n/a</div>");
					}
			}
			
			
		}
		);
	}
	else{
		
		//$('#compare_row_1_category').html('');
		
		feed = (sf=='group')? 'feed=group_profile/'+compare_id+'' : 'feed=clinic_profile/'+compare_id+'';
		
		$.ajax({
			type: "POST", url: "actions/get_xml.php",
			data: feed,
			success: 	function(xml){ 
				object_label = (sf=='group')? 'medical-groups' : 'clinic';
				$(object_label,xml).each(function(i){
					name = $(this).find('name:first').text();
					$('#compare_col_'+col+'_title').html(name);
				});
			},		
			error: 		function(){ $('#error_feedback').append(""); },
			complete: 	function(){ }
		});	
		
		$('#compare_row_'+row+'_col_'+col+'_data').html("<div class='rate_num'>n/a</div>");
	}
	$("#entry_table").tablesorter({ 
			

	    }); 
	
}

/* ----- Populate Profile Info 
------------------------------------------------------------------------------------- */

function populateProfileInfo(sf, name_id, category, xml){	
		
		//alert($('#show_affiliations').html());
		//aff_text = (sf=='group')? 'Clinics' : 'Medical Group';		
		//$('#show_affiliations').html(aff_text);
		
		$('#show_overview').click(function(){
			$('#profile_affiliations').hide(); 	$('#show_affiliations').removeClass('selected');	
			$('#profile_location').hide();		$('#show_location').removeClass('selected');
			$('#profile_overview').show();		$('#show_overview').addClass('selected');
			
			$('#profile_category_data').show();
			
			return false;
		});
		$('#show_affiliations').click(function(){
			$('#profile_location').hide();		$('#show_location').removeClass('selected');
			$('#profile_overview').hide();		$('#show_overview').removeClass('selected');
			$('#profile_affiliations').show();	$('#show_affiliations').addClass('selected');

			$('#profile_category_data').hide();

			return false;
		});
		$('#show_location').click(function(){
			$('#profile_overview').hide();		$('#show_overview').removeClass('selected');
			$('#profile_affiliations').hide();	$('#show_affiliations').removeClass('selected');
			$('#profile_location').show();		$('#show_location').addClass('selected');

			$('#profile_category_data').hide();

			if(!map_has_been_created){
				showMap(sf, name_id, category, xml);
			}
			return false;
		});		


	var object_label = (sf=='group')? 'medical-groups' : 'clinic'; 


	// Parse XML and append data to the dropdown
	$(object_label, xml).each(function(i){				
		
		name = $(this).find('name:first').text();
		
		addressline1 = $(this).find('address-line1:first').text();
		addressline2 = $(this).find('address-line2:first').text();
		city = $(this).find('city:first').text();
		state = $(this).find('state:first').text();
		zipcode = $(this).find('zip-code:first').text();

		web = $(this).find('website').text();		
		web_format = web.split('.');
		web = (web_format[0]=='www')? "http://"+web : web;		
		web = (web!='')? "Web: <a target='_blank' href='"+web+"'>"+web+"</a>" : "";
		
		main_phone = $(this).find('main-phone').text();		
		main_phone = main_phone.replace(/-/g,'');
		main_phone = main_phone.split('');
		main_phone = (main_phone!='')? "Main Phone: "+main_phone[0]+main_phone[1]+main_phone[2]+"-"+main_phone[3]+main_phone[4]+main_phone[5]+"-"+main_phone[6]+main_phone[7]+main_phone[8]+main_phone[9] : "";	
		
		tf_phone = $(this).find('toll-free-phone').text();
		tf_phone = tf_phone.replace(/-/g,'');
		tf_phone = tf_phone.split('');
		tf_phone = (tf_phone!='')? "Toll Free: "+tf_phone[0]+tf_phone[1]+tf_phone[2]+"-"+tf_phone[3]+tf_phone[4]+tf_phone[5]+"-"+tf_phone[6]+tf_phone[7]+tf_phone[8]+tf_phone[9] : "";
		

		// 
		// Overview
		// -------------------------------------------------------		
		$('#profile_name').append(""+name+"");
		$('#profile_overview').append(
			"<table>"+
			"<tr>"+
				"<td colspan='2'>"+web+"</td>"+""+
			"</tr>"+
			"<tr>"+
				"<td>"+main_phone+"</td>"+"<td>"+tf_phone+"</td>"+
			"</tr>"+		
			"</table>"	
		);
		
		
		// 
		// Affiliations
		// -------------------------------------------------------		
		affiliations_title = (sf=='group')? "<h3 class='affiliation_title'>Affiliated Clinics:</h3>" : "<h3 class='affiliation_title'>Affiliated Group:</h3>";
		
		$('#profile_affiliations').append(affiliations_title+"<table id='profile_affiliation_table'></table>");
		
		// 
		// If viewing a GROUP PROFILE, 
		// find all "active clinics" and report them as affiliations
		// -------------------------------------------------------
		$('active-clinic', xml).each(function(j){
			
			id = $(this).find('id').text();			
			name = $(this).find('name').text();
			city = $(this).find('city').text();
			state = $(this).find('state').text();
			zipcode = $(this).find('zip-code').text();
			county = $(this).find('county-name').text();
			
			$('#profile_affiliation_table').append(
				"<tr>"+
					"<td class='profile_affiliation_name'><a href='?p=profile&sf=clinic&category="+category+"&name_id="+id+"'>"+name+"</a></td>"+
					"<td class='profile_affiliation_link'><a href='?p=profile&sf=clinic&category="+category+"&name_id="+id+"'>view profile ></a></td>"+
				"</tr>"+	
				"<tr style='background: #E1EAE6;'>"+
					"<td class='profile_affiliation_info' colspan='2'>"+city+", "+state+" "+zipcode+"</td>"+
				"</tr>"
			);			
		});

		// 
		// If viewing a CLINIC PROFILE, 
		// find the "medical-group-name" and report it as this clinic's affiliation
		// -------------------------------------------------------
		$('clinic', xml).each(function(j){
			
			id = $(this).find('medical-group-identifier').text();			
			name = $(this).find('medical-group-name').text();
			city = $(this).find('city').text();
			state = $(this).find('state').text();
			zipcode = $(this).find('zip-code').text();
			county = $(this).find('county-name').text();
			
			$('#profile_affiliation_table').append(
				"<tr>"+
					"<td class='profile_affiliation_name'><a href='?p=profile&sf=group&category="+category+"&name_id="+id+"'>"+name+"</a></td>"+
					"<td class='profile_affiliation_link'><a href='?p=profile&sf=group&category="+category+"&name_id="+id+"'>view profile ></a></td>"+
				"</tr>"+	
				"<tr style='background: #E1EAE6;'>"+
					"<td class='profile_affiliation_info' colspan='2'>"+city+", "+state+" "+zipcode+"</td>"+
				"</tr>"
			);			
		});		

	});		
}


/* -- PE Exception Profile  -- */
function populateProfileDataPE(success, sf, name_id, category, sub_category, category_name, xml) {
		if(success) { 
			$('public-measure-summaries',xml).each(function(i){	
				clinic_name = $(this).find('clinic-name').text();
				cat_id = $(this).find('measure-id:first').text();
				//this_name_id = $(this).find(id_label+':first').text();
				//name = $(this).find(name_label+':first').text();
				city = (sf=='group')? $(this).find('medical-group-city:first').text() : $(this).find('clinic-city:first').text();
				zipcode = (sf=='group')? $(this).find('medical-group-zip:first').text() : $(this).find('clinic-zip:first').text();
				rate = Math.round($(this).find('rate:first').text() *100);
				overall_rate = Math.round($(this).find('overall-rate:first').text() * 100);
			// get patient experience specific data points
				access_comp_rate = Math.round( $(this).find('access-comp-rate:first').text() * 100);
				access_comp_rate_overall = Math.round( $(this).find('access-comp-rate-overall:first').text() * 100);
				access_comp_stars = $(this).find('access-comp-stars:first').text();
				access_comp_rate_graph = (access_comp_stars == '3')? "<div class='rate' style='background: #5bc95e; width: "+access_comp_rate+"px;'></div></div>" : "<div class='rate' style='background: #ffe972; width: "+access_comp_rate+"px;'></div></div>";
				
				$('#col_1_overall_average').html('<b>Average = '+access_comp_rate_overall+'%</b>');
				
				doc_comp_rate = Math.round( $(this).find('doc-comp-rate:first').text() * 100);
				doc_comp_rate_overall = Math.round( $(this).find('doc-comp-rate-overall:first').text() * 100);
				doc_comp_stars = $(this).find('doc-comp-stars:first').text();
				doc_comp_rate_graph = (doc_comp_stars == '3')? "<div class='rate' style='background: #5bc95e; width: "+doc_comp_rate+"px;'></div></div>" : "<div class='rate' style='background: #ffe972; width: "+doc_comp_rate+"px;'></div></div>";

				$('#col_2_overall_average').html('<b>Average = '+doc_comp_rate_overall+'%</b>');

				staff_comp_rate = Math.round( $(this).find('staff-comp-rate:first').text() * 100);
				staff_comp_rate_overall = Math.round( $(this).find('staff-comp-rate-overall:first').text() * 100);
				staff_comp_stars = $(this).find('staff-comp-stars:first').text();
				staff_comp_rate_graph = (staff_comp_stars == '3')? "<div class='rate' style='background: #5bc95e; width: "+staff_comp_rate+"px;'></div></div>" : "<div class='rate' style='background: #ffe972; width: "+staff_comp_rate+"px;'></div></div>";

				$('#col_3_overall_average').html('<b>Average = '+staff_comp_rate_overall+'%</b>');

				rating_9_10_rate = Math.round( $(this).find('rating-9-10-rate:first').text() * 100);
				rating_9_10_rate_overall = Math.round( $(this).find('rating-9-10-rate-overall:first').text() * 100);
				rating_9_10_stars = $(this).find('rating-9-10-stars:first').text();
				rating_9_10_rate_graph = (rating_9_10_stars == '3')? "<div class='rate' style='background: #5bc95e; width: "+rating_9_10_rate+"px;'></div></div>" : "<div class='rate' style='background: #ffe972; width: "+rating_9_10_rate+"px;'></div></div>";
				
				$('#col_4_overall_average').html('<b>Average = '+rating_9_10_rate_overall+'%</b>');


				// redefine data_area
				if(access_comp_rate=='-100'){ data_area1 = "<div class='rate_num asterisk'>*</div>"; }
				else {
				data_area1 = "<div class='pe_rate_num'>"+access_comp_rate+"%</div>"+
							"<!--div class='average_bar left' style='position:relative; left: "+(access_comp_rate_overall+3)+"px; line-height: 0px; width: 3px; height: 13px;'></div-->"+
							"<div class='left'><div class='graph'>"+access_comp_rate_graph+"</div><div class='clear'></div>";
				}
				if(doc_comp_rate=='-100'){ data_area2 = "<div class='rate_num asterisk'>*</div>"; }
				else {
				data_area2 = "<div class='pe_rate_num'>"+doc_comp_rate+"%</div>"+
							"<!--div class='average_bar left' style='position:relative; left: "+(doc_comp_rate_overall+3)+"px; line-height: 0px; width: 3px; height: 13px;'></div-->"+
							"<div class='left'><div class='graph'>"+doc_comp_rate_graph+"</div><div class='clear'></div>";
				}
				if(staff_comp_rate=='-100'){ data_area3 = "<div class='rate_num asterisk'>*</div>"; }
				else {				
				data_area3 = "<div class='pe_rate_num'>"+staff_comp_rate+"%</div>"+
							"<!--div class='average_bar left' style='position:relative; left: "+(staff_comp_rate_overall+3)+"px; line-height: 0px; width: 3px; height: 13px;'></div-->"+
							"<div class='left'><div class='graph'>"+staff_comp_rate_graph+"</div><div class='clear'></div>";
				}
				if(rating_9_10_rate=='-100'){ data_area4 = "<div class='rate_num asterisk'>*</div>"; }
				else {				
				data_area4 = "<div class='pe_rate_num'>"+rating_9_10_rate+"%</div>"+
							"<!--div class='average_bar left' style='position:relative; left: "+(rating_9_10_rate_overall+3)+"px; line-height: 0px; width: 3px; height: 13px;'></div-->"+
							"<div class='left'><div class='graph'>"+rating_9_10_rate_graph+"</div><div class='clear'></div>";							
				}
				
	
				$('#profile_category_data_table').append(
					"<tr><td colspan='2' class='category'><br/><h2>Patient Experience Data</h2></td></tr><tr><td colspan='2'><table id='profile_pe_table'>" +
						"<thead>" +
						"<tr class=''>" +
						"<th class='col_titles no_border' style='border-left: #5E7761 solid 1px;'>Getting Care<br /> When Needed<br /><a title='This measure reports on the timeliness of appointments, care, and information. An example is seeing your doctor within 15 minutes of your appointment time or getting an answer to your medical question the same day you asked it.' class='with-tooltip' href='#'>info</a></th>" + 
						"<th class='col_titles no_border'>How Well Doctors Communicate<br /><a title='This measure reports how well doctors listen to their patients and explain things in a way they can understand. An example is a doctor spending enough time with you and showing respect for what you have to say.' class='with-tooltip' href='#'>info</a></th>" +
						"<th class='col_titles no_border'>Courteous and Helpful Office Staff<br /><a title=\"This measure reports whether the doctor's office staff was polite and helpful. An example is a receptionist at your doctor's office treating you with courtesy and respect.\" class='with-tooltip' href='#'>info</a></th>" +
						"<th class='col_titles no_border' style='border-right: #5E7761 solid 1px;'>Doctors with an Exceptional Rating<br /><a title='This measures reports the percentage of patients who rated their doctor as a 9 or a 10 on a 0-10 rating scale where 10 = &quot;best doctor possible&quot;. This measure shows the average response for all patients surveyed on the clinic reported.' class='with-tooltip' href='#'>info</a></th></tr>" + 
						"</thead><tbody>"+ 
						"<tr class='colbody_top' style='border-bottom: 1px solid #5E7761;'>"+
						"<td class='pe_graph_area'>"+data_area1+"</td>"+
						"<td class='pe_graph_area'>"+data_area2+"</td>"+
						"<td class='pe_graph_area'>"+data_area3+"</td>"+
						"<td class='pe_graph_area'>"+data_area4+"</td>"+
					   "</tr></table></td></tr>");	
		
		

			
			
			}); // close each
 	    } // close success
} // close populateProfileDataPE function
/* -- HIT Exception Profile -- */
function populateProfileDataHIT(success, sf, name_id, category, sub_category, category_name, xml) {
	if(success) { 
	$('.hit_grid').jqm();
				$('.hit_grid_jqm').click(function() { 
					$('.hit_grid').jqmShow();	
					//return false;
				});
				$('.hit_grid_jqm_close').click(function() { 
					$('.hit_grid').jqmHide();	
					//return false;
				});
		$('public-measure-summaries',xml).each(function(i){	

			
			var clinic_id          		 = $(this).find('clinic-id:first').text();
			var clinic_name        		 = $(this).find('clinic-name:first').text();
			
			if(sf == 'group') {
				var clinic_name        	 = $(this).find('medical-group-name:first').text();
				var clinic_id          	 = $(this).find('summary-id:first').text();
			}
			var measure_period_id		 = $(this).find('measure-period-id:first').text();
			
			var adoption_full			 = ($(this).find('adoption-full:first').text() == 1) ? 'check_on.jpg' : 'check_off.jpg';
			var adoption_partial		 = ($(this).find('adoption-partial:first').text() == 1) ? 'check_on.jpg' : 'check_off.jpg';
			var adoption_planning		 = ($(this).find('adoption-planning:first').text() == 1) ? 'check_on.jpg' : 'check_off.jpg';
			
			var exchange_adv			 = ($(this).find('exchange-adv:first').text() == 1) ? 'check_on.jpg' : 'check_off.jpg';
			var exchange_beg			 = ($(this).find('exchange-beg:first').text() == 1) ? 'check_on.jpg' : 'check_off.jpg';
			var exchange_int			 = ($(this).find('exchange-int:first').text() == 1) ? 'check_on.jpg' : 'check_off.jpg';
			
			var utilization_adv			 = ($(this).find('utilization-adv:first').text() == 1) ? 'check_on.jpg' : 'check_off.jpg';
			var utilization_beg			 = ($(this).find('utilization-beg:first').text() == 1) ? 'check_on.jpg' : 'check_off.jpg';
			var utilization_int			 = ($(this).find('utilization-int:first').text() == 1) ? 'check_on.jpg' : 'check_off.jpg';
			
			var adoption_score			 = parseInt($(this).find('adoption-score:first').text());
			var exchange_score			 = parseInt($(this).find('exchange-score:first').text());
			var utilization_score		 = parseInt($(this).find('utilization-score:first').text());		
			
			var theimg_start = "<img src='assets/";
			var theimg_end   = "' style='padding-top: 3px;padding-left: 10px;' alt='' />";
			
			$('#profile_category_data_table').append("<tr class='colbody_top'><td colspan='2' class='category'><br/><h2>Health Information Technology</h2></td></tr><tr><td colspan='2'>" +
			"<table id='entry_table'>" +
			"<thead>" + 
			"<tr class='unmoving_row'>" +
				"<th class='no_border' style='width: 170px;'>Clinic Name</th>" +
				"<th class='col_titles no_border' style='text-align: center'>" +
				"<a class='with-tooltip AUE' style='text-decoration: underline' title='Information about you and the care you need is recorded in an EHR instead of a paper medical record.'>Adopt</a></th>" +
				"<th class='col_titles no_border' style='text-align: center'><a class='with-tooltip AUE' style='text-decoration: underline' title='Your doctor uses the EHR to order lab tests, track your health problems and improve your care.'>Use</a></th>" +
				"<th class='col_titles no_border' style='text-align: center'><a class='with-tooltip AUE' style='text-decoration: underline' title='Your information is sent and received in a secure manner among the doctors involved in your care.'>Exchange</a></th>" +
			"</tr>" +
			"</thead>"


			);
			$('#entry_table').append(
						"<tr class='colbody_top'>"+
							"<td class='name_hit' style='width: 180px !important;text-align: left;'><a href='?p=profile&name_id=" + clinic_id + "&sf=" + sf + "&measure-period-id="+measure_period_id +"'>" + clinic_name + "</a></td>"+
							"<!--<td style='display: none'></td>-->" + 
							"<td class='secondary_hit' style='text-align: center;' ><span style='display:none;'></span>" +
							"" + theimg_start + adoption_planning + theimg_end + "" + 
							"" + theimg_start + adoption_partial + theimg_end + "" + 
							"" + theimg_start + adoption_full + theimg_end + "" + 
							"" + "<img src='assets/dotted_divider.gif' style='float: right;'/><div class='clear'></div></td>"+
							"<td class='secondary_hit' style='text-align: center;' ><span style='display:none;'></span>" +
							"" + theimg_start + utilization_beg + theimg_end + "" + 
							"" + theimg_start + utilization_int + theimg_end + "" + 
							"" + theimg_start + utilization_adv + theimg_end + "" + 
							"" + "<img src='assets/dotted_divider.gif' style='float: right;'/><div class='clear'></div></td>"+
							"<td class='secondary_hit' style='text-align: center;' ><span style='display:none;'></span>" +
							"" + theimg_start + exchange_beg + theimg_end + "" + 
							"" + theimg_start + exchange_int + theimg_end + "" + 
							"" + theimg_start + exchange_adv + theimg_end + "" + 
							"" + "<div class='clear'></div></td>"+
							
												
						"</tr>"
					);
			
		$('#profile_category_data_table').append("</table></td></tr>");
							
	
		});
	}
	
$(".with-tooltip").simpletooltip();
}


function populateProfileData(success, sf, name_id, category, sub_category, category_name, xml) {
		
	if(success){	
		count=0;
		// Parse XML and append data to the dropdown
		$('public-measure-summary',xml).each(function(i){
			count++;
					
			data_source = $(this).find('data-source').text();
			measure_period_name = $(this).find('measure-period-name').text();
			
			current_measure_period_id = $(this).find('current-measure-period-id').text();
			measure_period_id = $(this).find('measure-period-id').text();
			
			//alert(current_measure_period_id+" : "+measure_period_id);
			
			year = measure_period_name.split('Report');
			year = year[0];
			
			cat_id = $(this).find('measure-id:first').text();
			cat_name = (sub_category=='')? $(this).find('measure-name:first').text() : $(this).find('component-name:first').text();
			this_name_id = $(this).find('medical-group-identifier:first').text();
			name = $(this).find('medical-group-name:first').text();
			overall_rate = Math.round($(this).find('overall-rate:first').text() *100);
			rate = Math.round($(this).find('rate:first').text() *100);
			//alert(cat_id);
			// if it's depression data, report the 6 month historical data
			if(cat_id == 4) {
		
			overall_rate = Math.round($(this).find('six-month-remission-rate-overall:first').text() *100);
			rate = Math.round($(this).find('six-month-remission-rate:first').text() *100);
			}
	
			//alert(count+" - "+measure_period_name);
			
			
			// Supress Patient Exp data (cat_id 16)
			
			if(name && count==1 && cat_id != '16'){			
				$('#profile_category_data_table').append(
					"<tr><td colspan='2' class='category'><h2>"+cat_name+"</h2></td></tr>"+
					"<tr>"+
					"<td class='current_report_year_title'><h4>Most Recent Report</h4></td>"+
					"<td class='historic_report_years_title'><h4>Past Reports</h4></td>"+
					"</tr>"
				);
				
				// IF VIEWING CURRENT REPORT YEAR
				if(cat_id == 1 && $('#sub_category').val() == '3' || cat_id == 1 && $('#sub_category').val() == '' ) { 
										avg_append = "<tr><td colspan='2'><span class='graphs_small_text'><br/>**Starting with our 2010 report, the Hemoglobin (A1c) goal has changed. This happened because new medical evidence emerged suggesting that an A1c level of less than 8 constitutes high quality diabetes care. Information in the Past Reports section is based on the old goal of an A1c  level less than 7, therefore we don't recommend comparisons between these two periods of time.</span></td></tr>";
										avg_append_ast = "**";
									} else { 
										avg_append = "";
										avg_append_ast = "";
									}

				if(current_measure_period_id == measure_period_id || cat_id =="4"){ // depression data is an exception with dated data used as most recent
								
					$('#profile_category_data_table').append(
						"<tr class='colbody_top'>"+
						"<td class='current_report_year'><!-- Current Report Year -->"+
							"<div class='graphs'>"+
						
								"<table><tr>"+
								"<td style='width: 90px;'>"+
									"<span class='graphs_small_text'>Rate:</span> "+rate+"%<br />"+
									"<div style='line-height: 0px; position: relative; top: "+(104-overall_rate)+"px; left: 66px;'>*</div>"+
									"<div style='background: #000; line-height: 0px; font-size: 0px; height: 3px; position: relative; top: "+(100-overall_rate)+"px; margin-right: 30px;'></div>"+
									"<div style='border: 1px solid #4E6751; margin-right: 30px; height: 100px; background: #5E7761;'>"+
										"<div style='background: #fff; height: "+(100-rate)+"px;'></div>"+
									"</div>"+
									"<div class='year'>"+year+ " "  + avg_append_ast + "</div>"+
									"<span class='graphs_small_text'>(* Avg: "+overall_rate+"%)"+
									
								"</span><br />"+
								"</td>"+
								"</tr></table>"+
							"</div>"+
						"</td>"+
						"<td class='historic_report_years'>"+
							"<div class='graphs'>"+
								"<table class='category_historic_table'><tr id='"+cat_id+"_historic'></tr></table>"+
							"</div>"+	
						"</td>"+
						"</tr>" + 
						"" + avg_append
					);
				}
				
				else {
					$('#profile_category_data_table').append(
						"<tr class='colbody_top'>"+
						"<td class='current_report_year'><!-- Current Report Year -->"+
							"<div class='graphs'>"+
								"<table><tr>"+
								"<td style='width: 90px;'>"+
								"</td>"+
								"</tr></table>"+
							"</div>"+
						"</td>"+
						"<td class='historic_report_years'>"+
							"<div class='graphs'>"+
								"<table class='category_historic_table'><tr id='"+cat_id+"_historic'></tr></table>"+
							"</div>"+	
						"</td>"+
						"</tr>"
					);
					$("#"+cat_id+"_historic").append(
						"<td style='width: 90px;'>"+
							"<span class='graphs_small_text'>Rate:</span> "+rate+"%<br />"+
							"<div style='line-height: 0px; position: relative; top: "+(104-overall_rate)+"px; left: 66px;'>*</div>"+
							"<div style='background: #000; line-height: 0px; font-size: 0px; height: 3px; position: relative; top: "+(100-overall_rate)+"px; margin-right: 30px;'></div>"+
							"<div style='border: 1px solid #4E6751; margin-right: 30px; height: 100px; background: #5E7761;'>"+
								"<div style='background: #fff; height: "+(100-rate)+"px;'></div>"+
							"</div>"+
							"<div class='year'>"+year+"</div>"+
							"<span class='graphs_small_text'>(* Avg: "+overall_rate+"%)</span><br />"+
						"</td>"
					);					
				}
				
				
			}
			else {
				$("#"+cat_id+"_historic").append(
					"<td style='width: 90px;'>"+
						"<span class='graphs_small_text'>Rate:</span> "+rate+"%<br />"+
						"<div style='line-height: 0px; position: relative; top: "+(104-overall_rate)+"px; left: 66px;'>*</div>"+
						"<div style='background: #000; line-height: 0px; font-size: 0px; height: 3px; position: relative; top: "+(100-overall_rate)+"px; margin-right: 30px;'></div>"+
						"<div style='border: 1px solid #4E6751; margin-right: 30px; height: 100px; background: #5E7761;'>"+
							"<div style='background: #fff; height: "+(100-rate)+"px;'></div>"+
						"</div>"+
						"<div class='year'>"+year+"</div>"+
						"<span class='graphs_small_text'>(* Avg: "+overall_rate+"%)</span><br />"+
					"</td>"
				);
				
			}
		});
	}

	else {
	
		// If the return was in error
		if(typeof(cat_name) != 'undefined') { 
		

		$('#profile_category_data_table').append(
			"<tr class='colbody_top'>"+
				"<td class='category_current'>"+
					"<h2 class='category_data'><br/>" +
					//"+cat_name+" Rate N/A</h2>"+
				"</td>"+
				"<td class='category_average'>"+
					"<h3 class='category_data'></h3>"+
				"</td>"+
				"<td class='category_historic'>"+
					"<h3 class='category_data'></h3>"+
				"</td>"+
			"</tr>" 
		);
		}
		
	}
	$("#entry_table").tablesorter({ 
			

	    }); 
}

function showMap(sf, name_id, category, xml){
	
	map_has_been_created=1;
	
	var object_label = (sf=='group')? 'medical-groups' : 'clinic'; 

	// Parse XML and append data to the dropdown
	$(object_label, xml).each(function(i){				
		
		name = $(this).find('name:first').text();
		
		addressline1 = $(this).find('address-line1:first').text();
		addressline2 = $(this).find('address-line2:first').text();
		city = $(this).find('city:first').text();
		state = $(this).find('state:first').text();
		zipcode = $(this).find('zip-code:first').text();

		web = $(this).find('website').text();
		main_phone = $(this).find('main-phone').text();
		tf_phone = $(this).find('toll-free-phone').text();


		// 
		// Create Map
		// -------------------------------------------------------
		//alert(addressline1+' '+addressline2+' '+city+' '+state+' '+zipcode);
		
		showAddress(addressline1+' '+addressline2+' '+city+' '+state+' '+zipcode);
		$('#map_link').append("<br /><a target='_blank' href='http://maps.google.com/maps?q="+addressline1+" "+addressline2+" "+city+" "+state+" "+zipcode+"'>Find this Location on Google Maps >> </a><br /><br />");
		
	});
}