// global vars
var preselect_state_id = ''; // use once and discard!
var preselect_city_id  = ''; // use once and discard!
var allow_empty = true;
var default_address_text = '';

jQuery(document).ready(function() {

  // clear existing selects and options
  clearSelectOptions('state_select');
  clearSelectOptions('city_select');

  // preselect options
  preselect_state_id = jQuery("input:hidden[name='_state_id']").get(0).value;
  var cid = jQuery("input:hidden[name='_city_id']");
  if (cid.length > 0) {
    preselect_city_id  = cid.get(0).value;
  }
  loadStates(getSelectedOptionValue(jQuery('#country_select').get(0)), preselect_state_id);
  preselect_state_id = ''; // use once

  jQuery('#country_select').bind("change", function(event) {
    // update states
    clearSelectOptions('state_select');
    clearSelectOptions('city_select');
    var country_id = getSelectedOptionValue(event.target);
    loadStates(country_id, '');
  });

  jQuery('#state_select').bind("change", function(event) {
    // update cities
    clearSelectOptions('city_select');
    var state_id = getSelectedOptionValue(event.target);
    jQuery.post('/ajaxWidget/cityOptions', { state_id: state_id, city_id: preselect_city_id, allow_empty: allow_empty, default_address_text: default_address_text }, function(data) {
      updateSelectOptions('city_select', data);
      preselect_city_id = ''; // use once
    }, 'html');
  });
});

function loadStates(country_id, preselect_state_id)
{
  jQuery.post('/ajaxWidget/stateOptions', { country_id: country_id, state_id: preselect_state_id, allow_empty: allow_empty, default_address_text: default_address_text }, function(data) {
    updateSelectOptions('state_select', data);
  }, 'html');
}

function getSelectedOptionValue(select)
{
  return jQuery(select).find('option:selected').attr('value');
}

function updateSelectOptions(select_id, data)
{
  var select = jQuery('#'+select_id);
  clearSelectOptions(select_id);
  select.html(data);
  select.change();
}

function clearSelectOptions(select_id)
{
  jQuery('#'+select_id).empty();
}

