/*
$Id: filters.js, v 1.0.0 2010/12/02 12:39:36 veter Exp $
vim: set ts=2 sw=2 sts=2 et:
*/

function func_clear_selectbox(selectbox_obj) {

  if (!selectbox_obj) return false;
 
  while (selectbox_obj.options.length > 0) {
    selectbox_obj.removeChild(selectbox_obj.options[0]);
  }
 
  selectbox_obj.options[0] = new Option("", "");

  selectbox_obj.disabled = "disabled";
//  selectbox_obj.style.backgroundColor = "lightgray";
 
  return true;
}

function func_fill_selectbox(selectbox_obj, data) {

  k = 1;
  for (i in data) {

    selectbox_obj.options[k++] = new Option(data[i]['value'], data[i]['id']);

  }

  selectbox_obj.disabled = '';
//  selectbox_obj.style.backgroundColor = "";

  $("#" + selectbox_obj.id + "_loading").hide();
}

$(".filter_values").change( 
  function() {

  if (filters[this.id]) {

    filterid = filters[this.id];

  } else {

    $("#" + selectbox_obj.id + "_loading").hide();

    return false;

  }

  selectbox_obj = document.getElementById(filterid);

  if (!selectbox_obj) {

    $("#" + selectbox_obj.id + "_loading").hide();

    return false;

  }

  func_clear_selectbox(selectbox_obj)

  $("#" + filterid + "_loading").show();

  tmp_filterid = filterid;

  while (tmp_filterid = filters[tmp_filterid]) {

    selectbox_tmp_obj = document.getElementById(tmp_filterid);

    if (selectbox_tmp_obj) {

      func_clear_selectbox(selectbox_tmp_obj);

    }

  }

  if (!ajax_mode) {
  // If filters have less than 100 values

    if (values[this.value]) {

      func_fill_selectbox(selectbox_obj, values[this.value]);
    } else {

      $("#" + selectbox_obj.id + "_loading").hide();

      return false;
    }

  } else {
  // If filters have a lot of possible values

      $.get(
        url, 
        {
          section: 'product_filters',
          mode: 'get_subfilter',
          productid: productid,
          valueid: this.value
        }, 
        function(data) {
        $(".small_waiting").hide();

          if (!data) {
            return false;
          }

          for (filterid in data) {

            selectbox_obj = document.getElementById(filterid);

            func_clear_selectbox(selectbox_obj)

            if (!selectbox_obj) {
              return false;
            }

            func_fill_selectbox(selectbox_obj, data[filterid]);

          }
        },
        "json"
      );
    }
  }
);


