
var Fredhopper = {};

Fredhopper.Autocompleter = Class.create();
Object.extend(Object.extend(Fredhopper.Autocompleter.prototype, Autocompleter.Base.prototype), {
  initialize: function(element, update, suggestUrl, options) {
    this.baseInitialize(element,update, options);
    this.options.asynchronous  = true;
    this.options.onComplete    = this.onComplete.bind(this);
    this.options.defaultParams = this.options.parameters || null;
    this.url                   = suggestUrl;
    this.entries               = [];
    this.hidesuggestions       = false;
  },

  getUpdatedChoices: function() {
    //entry = encodeURIComponent(this.options.paramName) + '=' +
    //  encodeURIComponent(this.getToken());
    entry = this.options.paramName + '=' +
      escape(escape(this.getToken()));

    this.options.parameters = this.options.callback ?
      this.options.callback(this.element, entry) : entry;

	//this.options.parameters += '&location=home&local=nl';
    if(this.options.defaultParams)
      this.options.parameters += '&' + this.options.defaultParams;
      //alert(this.options.parameters);
    new Ajax.Request(this.url, this.options);
  },

  onComplete: function(request) {
  	//alert(request.responseText);
    this.updateChoices(request.responseText);
  },

  getEntry: function(index)  {
    return this.entries[index];
  },

  updateChoices: function(choices) {
    if(!this.changed && this.hasFocus) {
      result = eval( "(" + choices + ")" );

      suggestHtml = '<div class="suggest-outer">';
      // Show button
      //suggestHtml += '<span class="showwhenhidden" id="showSuggestions"><div class="suggest-toplinks"><a href="#" onclick="showElement(\'hideSuggestions\'); showElement(\'suggestions\'); hideElement(\'showSuggestions\'); return false;" class="suggestshowlink suggest-showlink">Zeigen</a></div></span>';
      // Hide button
      suggestHtml += '<span><div class="suggest-toplinks"><a href="#" class="suggesthidelink suggest-hidelink">Nicht zeigen</a></div></span>';
      suggestHtml += '<div id="suggestions">';

      // Indicates if this is the first suggestion block
      var first = true;

      // Download the data
      this.entryCount = 0;
      for (resultGroup = 0; resultGroup < result.suggestionGroups.length; resultGroup++) {
        // Only render if it contains any suggestions
        if (result.suggestionGroups[resultGroup].suggestions.length <= 0)
          continue;

      	var indexName = result.suggestionGroups[resultGroup].indexName;
      	var indexTitle = result.suggestionGroups[resultGroup].indexTitle;

      	// manipulate the titles if empty
      	// TODO: Internationalisierung
		if (resultGroup == 0) {
			indexTitle = "Suchvorschl&auml;ge";
		}
		if (resultGroup == 1) {
			indexTitle = 'Kategorien f&uuml;r "<strong>'+this.element.value+'</strong>"';
		}
		if (resultGroup == 2) {
			indexTitle = 'Artikelnummer';
		}

      	// Add divider if not first entry
      	if (first)
      	  first = false;
      	else
      	  suggestHtml += '<div class="separator"></div>';

        suggestHtml += '<div class="suggest-header-div"><span class="suggest-header">'+indexTitle+'</span></div><ul class="CSS-CLASS">';
	    for (sugNr = 0; sugNr < result.suggestionGroups[resultGroup].suggestions.length; sugNr++) {
	      obj = result.suggestionGroups[resultGroup].suggestions[sugNr];
	      this.entryCount += 1;
	      suggestHtml += this.renderSuggestionHtml(indexName, obj);
	    }
  	    suggestHtml += '</ul>';
      }

	  suggestHtml += "</div></div>";

	  //alert(suggestHtml);

	  this.update.innerHTML = suggestHtml;

      Element.cleanWhitespace(this.update);
      Element.cleanWhitespace(this.update.down());

      this.entries = document.getElementsByClassName("suggestoption", this.update);
      this.entryCount = this.entries.length;

      var me = this;

      var hidelink = document.getElementsByClassName("suggesthidelink", this.update);
      if(hidelink[0])
      {
       	hidelink[0].onclick = function() {
      	  me.element.focus();
        };
      }

      for (var i = 0; i < this.entryCount; i++) {
        var entry = this.getEntry(i);
        entry.autocompleteIndex = i;
        this.addObservers(entry);
      }

      this.stopIndicator();
      this.index = -1;

      if(this.entryCount==1 && this.options.autoSelect) {
        this.selectEntry();
        this.hide();
      } else {
        this.render();
      }
    }
  },

  /**
   * The method renders generically all fields. Special fields are:
   *   - searchterm: searchterm that is triggered by the suggestion
   *   - secondId: second ID to which the suggestion links
   *   - fasParams: explicit FAS parameter string (if URL can't be built automatically)
   *   - image: image of the suggestion
   *   - nrResults: number of items that the execution of this suggestion would lead to
   */
  renderSuggestionHtml: function (indexName, obj) {
    var suggestHtml = "";

    action = "";
    optionsHtml = "";
    hasImage = false;

    // Validate if the entry is in image mode (table)
    if ('image' in obj) {
      hasImage = true;
      optionsHtml += '<td><img src="'+obj.image+'" width="30" align="left" /></td><td>';
    }

    // Iterate over each attribute, and render it
    for (attribute in obj) {
		if (attribute == 'searchterm') {
			// suchergebnis
			//action = 'autocompleter.element.value=\''+obj.searchterm+'\';document.getElementById(\'thesearchform\').submit()';

			//action = configuration.actionRedirect + '?search=' + escape(obj.searchterm);
			action = configuration.actionRedirect;
			if (action.indexOf(';jsessionid') != -1) {
			  var jsessionid = action.substring(action.indexOf(";jsessionid"), action.length);
			  action = action.substring(0, action.indexOf(";jsessionid"));
				action = action + escape(obj.searchterm) + '/' + jsessionid;
			}
			else {
				action = action + escape(obj.searchterm);
			}
			optionsHtml += '<span class="search-term"><strong>'+obj.searchterm+'</strong></span>';
		}
		else if (attribute == "nrResults" ) {
			// Suchergebnistreffer ( Produkte )
			optionsHtml += '<span class="nr-search-results">'+obj.nrResults+' Treffer</span>';
		}
		else if (attribute == "count" ) {
			// Suchergebnistreffer ( Kategorien )
			optionsHtml += '<span class="nr-search-results">'+obj[attribute]+'</span>';
		}
		else if (attribute == "fhLocation") {
			var prefix = configuration.fredhopperCatalogPrefix;
			var categorycode = obj[attribute].substring(obj[attribute].lastIndexOf(prefix)+prefix.length,obj[attribute].length-1);
			action = configuration.actionListView+'?categorycode='+escape(categorycode.toUpperCase());
		}
		else if (attribute == "mlValue") {
			// Kategoriename
			//action = redirectUrl + 'search=' + escape(obj.searchterm);
			optionsHtml += '<span class="search-term">'+obj[attribute]+'</span>';
		}
		else if (attribute == "lowestCatId") {
			// Kategorieid
			//action = configuration.actionFastSearch+'?search='+this.element.value+'&categorycode='+escape(obj[attribute]);
		}
		else if (attribute == "hint") {
			var hint = obj[attribute];
			if(hint.indexOf('_-') == -1) {
				if(hint.indexOf('_') > 0) {
					action = configuration.checkArticle + '?productCode='+hint.substring(0,hint.length-3);
				}
				else {
					action = configuration.checkArticle + '?productCode='+hint;
				}
				document.forms['simpleSearchForm'].action=configuration.checkArticle;
			}
			else {
				action = "#";
			}
			optionsHtml += '<span class="search-term">'+hint+'</span>';
		}

    }


    // Build the final HTML

    suggestHtml += '<li class="suggestoption">';
    if(action!="")
    	suggestHtml += '<a href="'+action+'">';
    if (hasImage)
      suggestHtml += '<table><tr>'+optionsHtml+'</tr></table>';
    else
      suggestHtml += optionsHtml;
	if(action!="")
		suggestHtml += '</a>';
    suggestHtml += '</li>';

    return suggestHtml;
  }
});

