// javascript powering the Provider Search

function runSearch(country, state) {

    try {

      if (country != 'NONE') {	

	var options = {action: 'search', country: country};
	if (state)
	  options = Object.extend(options, {state: state});

	// Searching: run an AJAX query to get search text
	new Ajax.Request('db/providerDriver.php', 
			 { method: 'get', 
			     parameters: options, 
			     onSuccess: function(transport) {

			       var resultsBox = $('resultsBlock');
			       resultsBox.show();
			       resultsBox.innerHTML = transport.responseText || "Error ocurred.";
			     
			       // make the results pageable
			       var options = {
				 pagedElements: $$('.providerResult'), 
				 nextButton: $('nextButton'),
				 prevButton: $('prevButton'),
				 statusBar: $('viewingResults')
			       }
			     
			       resultsBox.pageable = new Pageable(resultsBox, options);
			     
			       var msgBox = $('foundResults');
			       msgBox.innerHTML = 'Found ' + resultsBox.pageable.numItems() + ' providers.';
			   }
			 });      
      } // end if (country)
  
    } catch (e) {
      alert('An exception has occurred in this script. ' +
	    'Please alert MedForward technical support immediately ' +
	    'at support@medforward.com with the following information:' +
	    "\n\tError name: " + e.name +
	    "\n\tError message: " + e.message + '.' );
      
    }
}

// Let's people know that we're searching
function updateStatusBox() {
  
  var msgBox = $('foundResults');
  msgBox.show();
  msgBox.innerHTML = 'Searching...';
}

window.onload = function() {

  // Register this function to start anytime any AJAX call occurs
  Ajax.Responders.register({onCreate: updateStatusBox});

  $('select_state').onchange = function(event) {

    var state = this.value;
    var country = $('select_country').value;

    runSearch(country, state);    
  }

  // Run the search as soon as they choose a country
  $('select_country').onchange = function(event) {        

      // See if they selected a country
      var country = this.value;

      if (country == 'United States') {
	$('selectState').style.display = 'block'; 
	$('resultsBlock').hide();
	$('foundResults').hide();
	$('viewingResults').hide();
	$('nextButton').hide();
	$('prevButton').hide();
      }
      else {
	$('selectState').hide();
	runSearch(country, null);
      }

  }
  
}