var locations = [];
var resultsContainer; 
var resultsTitle; 
var defaultURL;
var defaultTitle = "Shade Bar Locations";


function showAllLocations()
{
  setLocationsList(defaultTitle, refreshLocations());
}

function refreshLocations()
{
  var regions = "<ul>";
  jQuery.each(locations, function(i)
  {
    regions += "<li>" + makeUrl(this.code, this.name, this.suburb) + "</li>"; 
  });  
  regions += "</ul>";
  return regions;
}


function searchByRegionCode(region_code)
{
  var regions = "";
  var hasLocation = false;

  regions = "<ul>";
  jQuery.each(locations, function(i)
  {
    if(this.regionCode == region_code)
    {
      regions += "<li>" + makeUrl(this.code, this.name, this.suburb) + "</li>"; 
      hasLocation = true;
    }
  });  
  regions += "</ul>";  
  
  if(!hasLocation)
  {
    regions = "<ul><li>No Locations in region</li></ul>";
  }
  setLocationsList(defaultTitle, regions)
}


function setLocationsList(regionTitle, regions)
{     
  $("." + resultsContainer).html(regions);
  $("." + resultsTitle).html(regionTitle);
}

/*
function checkForSubmit(e, textbox)
{
  if (e.keyCode == 13)
    searchPostcodes(textbox);
}
*/

function makeUrl(centreCode, centreName, centreSuburb)
{
  return "<< <a href='" + defaultURL + "?code=" + centreCode + "' title='More information about " + centreName + "'>" + centreName + "</a>";
}


function searchPostcodes(searchText)
{
  
  //var searchText = document.getElementById(textbox).value;
  
  var regions = "";
  var hasLocation = false;

  regions = "<ul>";
  
  jQuery.each(locations, function(i)
  {
    if(this.postCode == searchText || this.suburb.toLowerCase().match(searchText.toLowerCase()) != null || this.name.toLowerCase().match(searchText.toLowerCase()) != null)
    {
      regions += "<li>" + makeUrl(this.code, this.name, this.suburb) + "</li>"; 
      hasLocation = true;
    }
  });  
  regions += "</ul>";  
  
  if(!hasLocation)
  {
    regions = refreshLocations();
    regions = "<ul><li>There are no centres that match your search exactly. Please review the complete list below...</li></ul>" + regions;
  }
  setLocationsList(defaultTitle, regions);
  //setPostcodeSearchResults(regions);
}

/*
function setPostcodeSearchResults(regions)
{
  var searchResults = document.getElementById("postcodeSearchResults");
  if (searchResults != null)
    searchResults.innerHTML = regions;
}
*/
