$(function(){
  function replaceWithSelect($inputs)
  {
    $inputs.each(function()
    {
      var select = $("<select>")[0];
          select.id           = this.id;
          select.name         = this.name;
          select.presel_value = this.value;
          select.className    = this.className;
    console.log(this.name + " presel_value = " + this.value );
      $(this).replaceWith(select);
    });
  }

  // fills select with options from the server
  function fillSelect(select, params) {
    var $select = $(select);
    var type = $select[0].name.split("_")[0];
    $select.load("/common/get_select_options/" + type, params, function()
    {
      //console.log("fillSelect(" + $select[0].name + "," + $select[0].presel_value + ")");
      if (this.presel_value)
      {
        $(this).val(this.presel_value);
        this.presel_value = null;
      }
      $(this).change();
    });
  }

  replaceWithSelect($("[name^=country],[name^=subcountry],[name^=city]"));
  $("[name^=country],[name^=subcountry]").change(function(){
    var name_num = this.name.split("_");
    var name = name_num[0];
    var num  = "";
    if (name_num.length > 1)
    {
      num = "_" + name_num[1];
    }


    var params = {
      country:    $("#country"    + num).val(),
      subcountry: $("#subcountry" + num).val()
    }
    switch (name)
    {
      case "country":
        $("#subcountry" + num + ",#city" + num).empty();
        // do not fetch anything if at least country isn't entered
        if (! params.country ) return;

        fillSelect("#subcountry" + num, params);
        break;
      case "subcountry":
        $("#city" + num).empty();
        // do not fetch anything if at least country isn't entered
        if (! params.country ) return;
        fillSelect("#city" + num, params);
        break;
    }
  });

  // fill in all the countries,
  // will trigger the subcountires and citis to be populated as well
  $("[name^=country]").each(function() { fillSelect(this); } );
});

