// the following code should be included either before </body> in a <script src=""> tag or
// *directly* after the closing </form> tag for car_search

function updateFitlers(data, callback) {
  $H(data).each(function (pair) {
    // 3. loop through data keys, ignore "total"
    if (pair.key == 'total') {
      // it's total, let's put this in the #total span
      $$('#car_search h2').length && $$('#car_search h2').pop().update('Total found: ' + pair.value);
    } else {
      // 4. find select box with matching name and -
      var select = $$('#car_search select[name=' + pair.key + ']')[0];

      if (select) {
        // 4.1. store current selected value
        var selected = select.value;

        // 4.2. update options
        var options = [];
        pair.value.each(function (item) {
          options.push('<option value="' + item.value + '">' + item.label + '</option>');
        });

        // 4.3. set value to old selected value if exists
        select.update(options.join('')).setValue(selected);
      }
    }
  });

  if (callback != undefined) callback();
}

// 'Select' change event handler. Fires an Ajax call, the response to which will be to
// update the select options and 'total found' in the search panel (see #updateFitlers())
// Before this, additional pseudo-handler to detect whether the 'make' option has been
// reset to 'any'; if so, the range is also reset to 'any'.
function selectChange(event, callback) {
  // If this is a 'change' event on the 'make' select...
  if (event != null && event.type == 'change' && event.findElement('select#make') != undefined) {
    var make_value = $$('#car_search select[name=make]').invoke('getValue');
    if (make_value == 'Any') {
      $$('#car_search select[name=range]').invoke('setValue', 'Any');
    }
  }

  // Fire ajax call
  new Ajax.Request('/buyer/GetDropdowns', {
    // 1. send ajax request with form serialized
    parameters: $('car_search').serialize(),
    method: 'post',
    onSuccess: function(response) {
      updateFitlers(response.responseText.evalJSON(), callback);
    }
  });
}

function getQuery(s) {
  var query = {};

  s.replace(/\b([^&=]*)=([^&=]*)\b/g, function (m, a, d) {
    d = decodeURIComponent(d.replace(/\+/g, ' '));          // Note explicit 'unescaping' of '+' --> ' '
    if (typeof query[a] != 'undefined') {
      query[a] += ',' + d;
    } else {
      query[a] = d;
    }
  });

  return query;
}

// finally bind handlers
document.observe("dom:loaded", function() {
  // observers
  $$('#car_search select').invoke('observe', 'change', selectChange);
  $('car_search').observe('reset', function () {
    setTimeout(selectChange, 13); // wait for the reset to finish - then update - seems odd to do it this way tho
  });

  // read the query string to see if we need to prepopulate the select boxes
  var query = getQuery(window.location.search);
  $H(query).each(function (pair) {
    $$('#car_search select[name=' + pair.key + ']').invoke('setValue', pair.value);
  });

  // Only invoked on DOM load - some magic that invokes #updateFitlers() ???
  selectChange(null, function () {
  });
});

