var name_field = "lastname";
var search_type = "p"; //this is for individual search
var page = 0;
var delayed = undefined; 
var delayed2 = undefined;
var npi_history = new Array();

$(document).ready(function(){

	initNPInation();

});


function historyRow(npi, name, loc)
{
  var now = new Date();
  var hours = now.getHours();
  var minutes = now.getMinutes();
  var seconds = now.getSeconds()
  var timeValue = "" + ((hours >12) ? hours -12 :hours)
  if (timeValue == "0") timeValue = 12;
  timeValue += ((minutes < 10) ? ":0" : ":") + minutes
  timeValue += ((seconds < 10) ? ":0" : ":") + seconds
  timeValue += (hours >= 12) ? " P.M." : " A.M."

  var row = '<div class="history_row"><div class="history_npi">'+npi+'</div><div class="history_name">'+name+'</div><div class="history_location">'+loc+'</div><div class="history_date">'+ timeValue +'</div></div>';

  return row;
}

function initNPInation() {
	
	// any time the state dropdown is changed, we clear the zipcode, so it doesn't trigger the state dropdown value
	$("#state").change(function()
	    {
	        $('#zipcode').val('');
	});
	
	// hide the amzn widget
	$('#Player_cdb767ed-7258-4230-9a80-fa5f80018902').hide();
	
	//init the autocomplete for the various form elements














	$('#city').autocomplete('city_lookup.php', 
	                        {minChars: 2, extraParams: {state: function() { 
		                                                                  return $("#state").val(); 
																		  } 
		                    } 
	});
	
	$('#firstname').autocomplete('firstname_lookup.php',
							{minChars: 2, extraParams: {state: function() { 
																		  return $("#state").val(); 
																		  }, 
														firstname: function() { 
																		  return $("#firstname").val(); 
																		  }, 
														lastname: function() { 
																		  return $("#lastname").val(); 
																		  }
							}
	});

	$('#lastname').autocomplete('lastname_lookup.php',
							{minChars: 2, extraParams: {state: function() { 
																		  return $("#state").val(); 
																		  },  
														firstname: function() { 
																		  return $("#firstname").val(); 
																		  }, 
														lastname: function() { 
																		  return $("#lastname").val(); 
																		  }
							}
	});

	$('#organization').autocomplete('org_lookup.php',
							{minChars: 2, extraParams: {state: function() { 
																		  return $("#state").val(); 
																		  }, 
														 org: function() {
																		  return $("#organization").val(); 
																		  }
							}				
	});

	 $('#firstname, #lastname, #organization, #city, #zipcode').keyup(function(){
	 		
			if ($('#zipcode').val().length >= 5) {
			       $('#state').val(returnStateAbbrvFromZipInteger(parseInt($('#zipcode').val().slice(0,3))));   
			}
			
			if ($('#state').val() != "" && $('#' + name_field).val().length >= 2) {
				 $('#intro').fadeOut(300);
		         $('#Player_cdb767ed-7258-4230-9a80-fa5f80018902').fadeIn(1600);
		         $('.results_row').remove();
				 $('.no_results_row').remove();
				 $('#spinner').show(); 
				 populateLookup();
		    }	
      });

	
	
	// default search on load is individual search
	$('.entity_type:first').trigger("click");
		
	initRadioButtonChange();
	initReverseLookup();
}


function populateLookup() 
{   
		$.get("list_populator.php", {city: $('#city').val(), 
									 state: $('#state').val(), 
									 search_type: search_type, 
									 page: page, 
									 firstname: $('#firstname').val(), 
									 lastname: $('#lastname').val(), 
									 organization: $('#organization').val()
									 }, 
				function(data) {
           						if(data) {
                 							$('#spinner').fadeOut(500, function () {
                     																$(this).after(data);
                 																	$('.results_name').click(function(o) {
																				var clicked_id = $(this).parent().parent().attr('id');
																				pageTracker._trackPageview("/lookup/" + clicked_id);
                       

																						

																								$('#Player_cdb767ed-7258-4230-9a80-fa5f80018902').hide();
																								$("#dialog").dialog('destroy');
																								
                       	  																		$("#dialog").dialog({
																										bgiframe: true,
																										height: 500,
                       																					width: 500, 
																										modal: true,
                                       																	title: "NPI " + clicked_id,
																										close: function() {$('#Player_cdb767ed-7258-4230-9a80-fa5f80018902').show();}
	         	   																					});
																									$("#dialog > p").html('<center>Retrieving info...<br /><img src="ajax-loader2.gif"/></center>');
																									$.get("get_detail.php",{npi: clicked_id, 
																															state: $('#state').val(), 
																															search_type: search_type
																															}, function(data) {
																																	$("#dialog > p").html(data);
																															
	
	
                                																	var name = $('#' + clicked_id + ' .results_name:first').text();
                                																	var city = $('#' + clicked_id + ' .address:first').text();
                                																	npi_history[clicked_id] = 1;
                                																	$('#history_scroller').prepend(historyRow(clicked_id, name, city));  
																															});
																							});
                 																	});
           						} else {
                  							$('.results_row, .no_results_row').remove();
                  							$('#spinner').hide(300, function () {
																			$(this).after("<b class='no_results_row'>No results found.</b>");
																			}
										);
           						}
 					});
}

function initReverseLookup()
{
	
	$("#reverse_search").keyup(function(){
		if (($("input[name='entity_type']:checked").val() == "upin" && $("#reverse_search").val().length == 6) || 
	       ($("input[name='entity_type']:checked").val() == "npi" && $("#reverse_search").val().length == 10)) {
				var query_counter = new Array;

				if (query_counter[$("#reverse_search").val()] == 1) {
					// do nothing
				} else { 
					query_counter[$("#reverse_search").val()] = 1;
					$('#intro').remove();
	             	$('#Player_cdb767ed-7258-4230-9a80-fa5f80018902').fadeIn(1600);
					$('.results_row').remove();
					$('.no_results_row').remove();	
					$('#spinner').show();	
					$.get("reverse_lookup.php", {number: $('#reverse_search').val(), 
												type: $("input[name='entity_type']:checked").val()
												}, function(data) {
													if(data) {
	                										$('#spinner').fadeOut(500, function () {
	                      																	$(this).after(data);
	                  																		$('.results_name').click(function(o) {
																															var clicked_id = $(this).parent().parent().attr('id');
																																
pageTracker._trackPageview("/reverse_lookup/" + $("input[name='entity_type']:checked").val() + "/" + clicked_id);
																															

																																				$('#Player_cdb767ed-7258-4230-9a80-fa5f80018902').hide();
																																				$("#dialog").dialog('destroy');
						                        	  																							$("#dialog").dialog({
																																									bgiframe: true,
																																									height: 500,
						                        																													width: 500, 
																																									modal: true,
						                                        																									title: "NPI " + clicked_id,
																																									close: function() {$('#Player_cdb767ed-7258-4230-9a80-fa5f80018902').show();}
								         	   																														});
																																				$("#dialog > p").html('<center>Retrieving info...<br /><img src="ajax-loader2.gif"/></center>');
																																				$.get("get_detail.php",{npi: clicked_id, 
																																										state: $('#state2').text().substr(0,2), 
																																										search_type: $('#search_type2').html()}, 
																																						function(data) {

																																							        $("#dialog > p").html(data);
						                                																											var name = $('#' + clicked_id + ' .results_name:first').text();
						                                 																											var city = $('#' + clicked_id + ' .address:first').text();
						                                 																												npi_history[clicked_id] = 1;
						                                 																												$('#history_scroller').prepend(historyRow(clicked_id, name, city));  
																																									});

																															});

	                  																		});
	            									} else {
	                  									  $('.results_row, .no_results_row').remove();
	                   									  $('#spinner').hide(300, function () {
																						$(this).after("<b class='no_results_row'>No results found.</b>");
														  });            
													}
	  				});
	    	}
		}
	  });
}



function initRadioButtonChange() 
{
  $('.entity_type').click(function(){
    $('#reverse_search, .search input').val('');
    switch($(this).val()) {
        case 'ind':
          $('.reverse_search, .organization').hide();
          $('.search, .individual').show();
          name_field = "lastname";
          search_type = "p";
	break;
	case 'org':
          $('.reverse_search, .individual').hide();
          $('.search, .organization').show();
          name_field = "organization";
          search_type = "o";
	break;
	case 'upin':
          $('.search').hide();
          $('#reverse_search_label').html('upin');
          $('.reverse_search').show();
          name_field = false;
          search_type = "upin";
	break;
	case 'npi':
	   $('.search').hide();
           $('#reverse_search_label').html('npi');
           $('.reverse_search').show();
           name_field = false;
           search_type = "npi";
	break;


    }
  });
}


