(function(){
  ff.ColorSearch = function(farbfinder, options)
  {
    this._initialize(farbfinder, options);
  }
  
  ff.ColorSearch.prototype = jQuery.extend(ff.ColorSearch.prototype,
  {
    _initialize: function(farbfinder, options)
    {
      this._options = jQuery.extend
      ({
        color_search_field: '#color_search',
        headline:  '#container_schritt_2_headline',
        color_select_field: '#color_list',
        baujahr_select_field: '#color_baujahr',
        fetch_color_spaces_url: ff.SERVICE_URL + '/jsonService/colorSpaces',
        query_url:  ff.SERVICE_URL + '/jsonService/queryColor',
        back_button: '#step_2_back_button',
        form: '#color_search_form',
        error_container: '#step_2_error_message',
        loader_container: '#step_2_loader',
        link_hersteller_beschreibung: '.link_hersteller_beschreibung'
      }, options);

      this._farbfinder = farbfinder;

      this._foundColors = [];
      this._manufacturer = { id: null, name: null };

      this._baujahr_select_field = jQuery(this._options.baujahr_select_field);
      this._back_button = jQuery(this._options.back_button);
      this._form = jQuery(this._options.form);
      this._errorContainer = jQuery(this._options.error_container);
      this._loaderContainer = jQuery(this._options.loader_container);
      this._linkHerstellerBeschreibung = jQuery(this._options.link_hersteller_beschreibung);
      this._colorSearchField = jQuery(this._options.color_search_field);
      this._colorSelectField = jQuery(this._options.color_select_field);
      
      this._headline = jQuery(this._options.headline);
      this._headlineHtml = this._headline[0].innerHTML;
    },
    setManufacturer: function(manufacturer)
    {
      this._manufacturer = manufacturer;
      this._resetDisplay();
    },
    getManufacturer: function()
    {
      return this._manufacturer;
    },
    startup: function()
    {
      this._fetchColorSpaces();

      var self = this;

      this._linkHerstellerBeschreibung.bind('click keypress', function(ev)
      {
        jQuery(self).trigger('linkHerstellerBeschreibungClicked');
      });

      this._back_button.bind('click keypress', function(ev)
      {
        jQuery(self).trigger('stepBack');
      });
      
      this._form.bind('submit', {self: this}, function(ev)
      {
        ev.preventDefault();
        var self = ev.data.self;
        var manufacturer = self.getManufacturer();
        if(!jQuery('#color_search').attr('value') && jQuery('#color_list').val() < 1)
        {
          alert("Bitte bestimmen Sie ein Suchkritierum.");
        }
        else
        {
          ev.data.self._query(manufacturer.id, jQuery(this).serialize());
        }
      });
      
      this._colorSearchField.bind('change focus blur keyup', function(ev)
      {
        if(self._colorSearchField.val().length > 0)
        {
          self._colorSelectField.attr('disabled', true);
        }
        else
        {
          self._colorSelectField.attr('disabled', false);
        }
      });

      this._colorSelectField.bind('change focus blur keyup', function(ev)
      {
        if(self._colorSelectField.val()>0)
        {
          self._colorSearchField.attr('disabled', true);
        }
        else
        {
          self._colorSearchField.attr('disabled', false);
        }
      });
    },
    _query: function(manufacturer_id, params)
    {
      var self = this;
      this._resetDisplay();
      this._showLoaderContainer();
      this._queryString = this._options.query_url + '?manufacturer_id=' + manufacturer_id + '&' + params + '&callback=?';
      jQuery.getJSON(this._queryString, {}, function()
      {
        var result = arguments[0];
        self._hideLoaderContainer();

        if(result.records < 1)
        {
          self._showErrorContainer();
        }
        else
        {
          var farbe = jQuery('#color_search').val()
            ? jQuery('#color_search').val()
          : (jQuery('#color_list').val() > 0 ? jQuery('#color_list option[value='+jQuery('#color_list').val()+']').text() : 'Alle');

          farbe += jQuery('#color_baujahr').val() > 0 ?
            ' / Baujahr: ' + jQuery('#color_baujahr').val() : '';
          
          
          self._headline.html('Farbe/Kategorie: ' + farbe);
          jQuery(self).trigger('colorsFound', { query_string: self._queryString, color_search: self, 'result': result });
        }
      });
    },
    _fetchColorSpaces: function()
    {
      var self = this;
      jQuery.getJSON(this._options.fetch_color_spaces_url + '/?callback=?', {}, function()
      {
        self._color_spaces = arguments[0];
        self._updateColorSelectField(self._color_spaces);
      });
    },
    _updateColorSelectField : function(color_spaces)
    {
      var self = this;
      this._colorSelectField.empty().append(jQuery(document.createElement('option')).attr({id:0}).html());

      var option = jQuery(document.createElement('option'));
      option.attr({
        value : 0
      });
      option.html('&ndash;');
      this._colorSelectField.append(option);
      
      jQuery(color_spaces).each(function(i, color_space)
      {
        var option = jQuery(document.createElement('option'));
        option.attr({
          value : color_space.id
        });
        option.html(color_space.name);

        self._colorSelectField.append(option);
      });
    },
    _resetDisplay: function()
    {
      this._hideErrorContainer();
      this._hideLoaderContainer();
      jQuery.ajax({
        success: function(transport)
        {
          //console.log(arguments);
          jQuery('#farbcode_hersteller_beschreibung').html(transport);
         
        },
        url: ff.REQUEST_URI + '?farbfinder_action=get_hersteller_info&name=' + this.getManufacturer().name
      });
    },
    _hideErrorContainer: function()
    {
      this._errorContainer.css({'opacity': 0, 'display': 'none'});
    },
    _hideLoaderContainer: function()
    {
      this._loaderContainer.css({'display': 'none'});
    },
    _showErrorContainer: function()
    {
      this._errorContainer.css({display: 'block'}).fadeTo(1000, 1);
    },
    _showLoaderContainer: function()
    {
      this._loaderContainer.css({'display': 'block'});
    },
    resetHeadline: function()
    {
      this._headline.html(this._headlineHtml);
    }
  });
})();


