var country_selector_key;
var state_selector_key;

function hide_state_selector() {
  var state_selector = $(state_selector_key);
  state_selector.removeClass('required');
  state_selector.parents('div').eq(0).hide();
}

/**
 * The states have been sent, update the selector.
 * @param string response
 */
function got_states(response) {
  var states = eval("(" + response + ")");
  var state_selector = $(state_selector_key);
  var el_state_selector = state_selector.get(0);
  if (!states || states.length == 0) {
    hide_state_selector();
  }
  else {
    // add fields to the selector:
    var state_name, option;
    for (var state_code in states) {
      state_name = states[state_code];
      option = document.createElement('option');
      option.value = state_code;
      option.text = state_name;
      el_state_selector.options[el_state_selector.options.length] = option;
    }
    // make it required if necessary:
    if (state_required) {
      state_selector.addClass('required');
    }
    // select the user's state:
    state_selector.val(user_state);
    // show the state selector field:
    state_selector.parents('div').eq(0).show();
  }
  // restore the 'Please Select' option:
  el_state_selector.options[0].text = 'Please Select';
  state_selector.css('background-color', 'White');
}

/**
 * Update the state selector.
 */
function update_state_selector() {
  // empty the state selector:
  var country_selector = $(country_selector_key).get(0);
  var state_selector = $(state_selector_key).get(0);
  state_selector.options.length = 1;
  if (!country_selector.selectedIndex) {
    hide_state_selector();
  }
  else {
    state_selector.options[0].text = 'Please Wait';
    $(state_selector_key).css('background-color', '#eee');
  }
  // get the states:
  var country_code = $(country_selector_key).val();
  if (country_code) {
    var url = "/ajax/geo/get-states/" + country_code;
    $.get(url, got_states);
  }
}

/**
 * Sets up the country and state selectors for AJAX. 
 * @param string country_selector_id
 * @param string state_selector_id
 */
function init_country_state(country_selector_id, state_selector_id) {
  country_selector_key = '#' + country_selector_id;
  state_selector_key = '#' + state_selector_id;
  $(country_selector_key).change(update_state_selector);
  update_state_selector();
}

