/* AJAX search-by-vehicle support Javascript */

// vehicle_search namespace

var vehicle_search = new function() {

  this.SEARCH_URL = "";
  this.SEARCH_REL = "/cgi-bin/suscon/ajax/search_by_vehicle";

  this.set_search_url = function(url) {
    this.SEARCH_URL = url;
  };

  this.get_search_rel = function() { return this.SEARCH_REL };

  this.refine_search = function(element, options) {
    this._search("refine", "", options);
  };

  this._search = function(stype, ctype, extra_params, async) {
    async = typeof(async) != 'undefined' ? async : true;
    var url, params, success, field, dtype;


    url = this.SEARCH_URL;

    params = { s     : stype,
               make  : this.make_value(),
               year  : this.year_value(),
               model : this.model_value() };

    if (ctype == "update") {
      dtype = "json";
      field = { "model" : this.model_field(), "years" : this.year_field() }[stype];
      success = function(data) { 
        this.update_options_callback(field, data) };
    } 
    else {
      dtype = "html";
      success = function(html) { 
        jQuery('#search_facets').html($('#search_facets_updated', html).html()); 
        jQuery('#ajax-search-by-vehicle-result-target').html(html); 
      };
    }

    if (extra_params) {
      jQuery.each(extra_params, function(name, value) {
        params[name] = value;
      });
    }

    var options = {
      url : url,
      async : async,
      cache : false,
      data : params,
      dataType : dtype,
//      complete : function() {alert("complete")},
      success : success,
      failure : this._ajax_failure,
      context : this
    };
    jQuery.ajax(options);
  };

  this.update = function(element) {
    var name = element.name;

    var update_dispatch = { 
      "vehicle_make"  : this.update_make,
      "vehicle_year"  : this.update_year,
      "vehicle_model" : this.update_model 
    };

    // dispatch to handler function
    try {
      // disable search
      this.submit_button().disabled = true;

      update_dispatch[name].call(this, element);
    }
    catch (e) {
      //console.log('ERROR: dispatch ' + e.message);
    }
  };

  this.update_make = function(element, async) {
    //console.log('vehicle search update make called');

    // reset years field
    this.reset_select_field(this.year_field());

    // reset model field
    this.reset_select_field(this.model_field());

    this.submit_button().disabled = true;
    
    if (element.selectedIndex == 0)
      return;

    // update years options
    this._search("years", "update", null, async);
  };

  this.update_year = function(element, async) {
    //console.log('vehicle search update year called');

    // reset model field
    this.reset_select_field(this.model_field());

    this.submit_button().disabled = true;

    if (element.selectedIndex == 0)
      return;

    // update years options
    this._search("model", "update", null, async);
  };

  this.update_model = function(element) {
    //console.log('vehicle search update model called');

    if (element.selectedIndex == 0)
      return;

    // enable search
    this.submit_button().disabled = false;
  };

  this.reset_select_field = function(element) {
    //console.log('vehicle search reset select field called');
    element.options.length = 1;
    element.disabled = true;
  };

  this.update_options_callback = function(element, data, textStatus, jqXHR) {
    var i, opt_len;
    //console.log('update_options_callback -- success -- got ' + data.length);

    for(i = 0; i < data.length; i++) {
      opt_len = element.options.length;
      element.options[opt_len] = new Option(data[i].text, data[i].value);
    }
    element.disabled = false;
  }; 

  this._ajax_failure = function(jqXHR, textStatus, errorThrown) {
    //console.log('ajax failure');
    alert("AJAX Error: " + textStatus);    
  };

  this._form = function() {
    return document.getElementById('ajax-search-by-vehicle-form');
  };

  this.make_field = function() {
    return document.getElementById('ajax-search-by-vehicle-make');
  };

  this.make_value = function() {
    return $(this.make_field()).val();
  };

  this.year_field = function() {
    return document.getElementById('ajax-search-by-vehicle-year');
  };

  this.year_value = function() {
    return $(this.year_field()).val();
  }

  this.model_field = function() {
    return document.getElementById('ajax-search-by-vehicle-model');
  };

  this.model_value = function() {
    return $(this.model_field()).val();
  }

  this.submit_button = function() {
    return document.getElementById('ajax-search-by-vehicle-search');
  };

  //---------------------------------------------------------------
  this._sessionVars = {};

  this.getIndexByValue = function(array, value) {
    var i;
    len = array.length;
    for (i = 0; i < array.length; i++) {
      if (array[i].value == value) return i;
    }
    return null;
  }

  this.set_session_vars = function(make, year, model) {
    this._sessionVars.make = make;
    this._sessionVars.year = year;
    this._sessionVars.model = model;
  };

  this.init_form = function() {
    //console.log('init_form--document is ready...aparently');
    var i, f;
    var self = vehicle_search;

    if (self._sessionVars.make) {
      self.update_make(self.make_field(), false);
      // the form already builds and selects this field
    }
    if (self._sessionVars.year) {
      f = self.year_field();
      i = self.getIndexByValue(f.options, self._sessionVars.year);
      f.selectedIndex = i ? i : -1;
      self.update_year(f, false);
    }
    if (self._sessionVars.model) {
      f = self.model_field();
      i = self.getIndexByValue(f.options, self._sessionVars.model);
      f.selectedIndex = i ? i : -1;
      self.update_model(f);
    }
  };

  this.reset_form = function() {
    var f = this.make_field();
    f.selectedIndex = 0;
    this.update_make(f);
  };

};

// set form init handler
jQuery(document).one("ready", vehicle_search.init_form);

