var gHost = location.protocol + '//' + location.host; //'http://HostName';

$(document).ready(function() {
  checkActivity();

  $("#frm_countries").bind("change", function() {
    changeRegionsByCountry(this.options[this.selectedIndex].value);
  });

  $("#frm_regions").bind("change", function() {
    changeLocationsByRegion(this.options[this.selectedIndex].value);
  });
});

function changeRegionsByCountry(countryID) {
  dropIndex($('#frm_regions'), 1);
  dropIndex($('#frm_locations'), 1);

  if (countryID != 0) {
    $('#frm_regions').append('<option selected>Loading...</option>');
    if (loadOptions($('#frm_regions'), "/js/data/regions_by_country.php?country=" + countryID)) {
      $('#frm_regions').removeAttr("disabled");
    } else {
      $('#frm_regions').append('<option selected>Error!</option>');
    }
  }
}

function changeLocationsByRegion(regionID) {
  dropIndex($('#frm_locations'), 1);

  if (regionID != 0) {
    $('#frm_locations').append('<option selected>Loading...</option>');
    if (loadOptions($('#frm_locations'), "/js/data/locations_by_region.php?region=" + regionID)) {
      $('#frm_locations').removeAttr("disabled");
    } else {
      $('#frm_locations').append('<option selected>Error!</option>');
    }
  }
}

function loadOptions(aObjToLoad, aPath) {
  var vRes = 0;
  var vOptions = '';
  var vData = $.ajax({
    type: "GET",
    url: gHost + aPath,
    dataType: "xml",
    async: false
  }).responseText;

  //alert(vData);
  var vRoot = $.xml2json(vData);
  for (var i=0; i<vRoot.item.length; i++) {
    var vId = vRoot.item[i].id;
    var vName = vRoot.item[i].name;
    vOptions += '<option value="' + vId + '">' + vName + '</option>';
  }

  if (vOptions != '') {
    aObjToLoad.html(vOptions);
    vRes = 1;
  }

  return vRes;
}

function dropIndex(aObj, isDisabled) {
  aObj.find('option:first').attr('selected', 'selected');
  if (isDisabled) {
    aObj.attr('disabled', 'disabled');
  }
}

function checkActivity() {
  if ($('#frm_countries').selectedIndex == 'undefined') {
    dropIndex($('#frm_regions'), 1);
    dropIndex($('#frm_locations'), 1);
  }
}

