/* Office selection functionality for profile page */

// Global variable to store officeId/zip cache so we don't make multiple
// identical Ajax calls against the server.
var _officeCache = {};

// True if we're waiting on an AHAH response.
var _waitingForOfficeOptions = false;

function getOfficeOptions() {
  var brandId = $('#brand').val();
  var officeZip = $('#office_zip').val();

  // Only proceed if data is something we can use.
  if (officeZip.length == 5 && brandId > 0) {
    // First check the office cache.
    if (_officeCache[brandId] != undefined
      && _officeCache[brandId][officeZip] != undefined) {
      // Found something in the cache, so push it into the select.
      $('#officeId').html(_officeCache[brandId][officeZip]);
      $('#officesRow').show();
    } else {
      // Results not cached, so lets ask the server via Ajax (actually AHAH).
      _waitingForOfficeOptions = true;
      $.get('/ajax.php',
        {func:'getOfficeOptions', brandId:brandId, officeZip:officeZip},
        function(data) {
          _waitingForOfficeOptions = false;
          if (_officeCache[brandId] == undefined) {
            // Prime brandId level of cache.
            _officeCache[brandId] = {};
          }
          _officeCache[brandId][officeZip] = data;
          $('#officeId').html(data);
          $('#officesRow').show();
        }
      );
    }
  } else {
    $('#officesRow').hide();
  }
}

// Executes when page is done loading.
$(document).ready(function(){
  // Disable office fill in records so that form validation skips them.
  $('.officeFillInRow input, .officeFillInRow select').attr('disabled', 'disabled');

  // Attach function as onChange event to brand select and zip text field.
  $('#brand').change(getOfficeOptions);
  $('#office_zip').keyup(getOfficeOptions);

  // If user selects 'Not found', then we show the fill-in field.
  $('#officeId').change(function(){
    if ($(this).val() == '0') {
      $('.officeFillInRow').show();
      $('.officeFillInRow input, .officeFillInRow select').attr('disabled', '');
    } else {
      $('.officeFillInRow').hide();
      $('.officeFillInRow input, .officeFillInRow select').attr('disabled', 'disabled');
    }
  });
})