var gHost = location.protocol + '//' + location.host; //'http://HostName';

$(document).ready(function() {
  //checkActivity();

  $("#frm_ctrl_countries").bind("change", function() {
    changeCities(this.options[this.selectedIndex].value);
  });
});

function changeCities(countryID) {
  if (countryID != 0) {
    dropIndex($('#frm_ctrl_cities'), 1);
    $('#frm_ctrl_cities').append('<option selected>Loading...</option>');
    if (loadOptions($('#frm_ctrl_cities'), "/js/data/cities_by_country.php?country=" + countryID)) {
      $('#frm_ctrl_cities').removeAttr("disabled");
      $('#frm_ctrl_categories').removeAttr("disabled");
    } else {
      $('#frm_ctrl_cities').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_ctrl_countries').selectedIndex == undefined) {
    dropIndex($('#frm_ctrl_cities'), 1);
    dropIndex($('#frm_ctrl_categories'), 1);
  }
*/
}

