/* Be sure to include AutoSuggestControl.js and SearchProvider.js above this file... */

var tagPickerSearchProvider = SearchProvider.extend(
  function()
  {
    tagPickerSearchProvider.superclass.constructor.call( this );
  },
  {
    startSearch: function (bTypeAhead)
    {
      var oThis = this;

      if( this.lastSearchRequest !== null )
      {
        this.lastSearchRequest.abort();
      }
      this.lastSearchRequest = $.ajax({ url      : '/tag/tagPicker.html',
                                        data     : { SearchString: this.currentSearchText },
                                        dataType : 'json',
                                        success  : function( serverResponse )
                                        {
                                          oThis.processSearchResults.call( oThis, serverResponse );
                                        },
                                        error    : function( oXHR, sTextStatus )
                                        {
                                          oThis.failedSearch.call( oThis, oXHR, sTextStatus );
                                        }
                                      });
      this._bTypeAhead = bTypeAhead;
    },
    processSearchResults: function( serverResponse )
    {
      this.lastSearchRequest = null;
      var aSuggestions = [], key;

      if( serverResponse.exact_match == 0 )
      {
        aSuggestions.push({
          "id": "0",
          "text": "<span class=\"ui-state-highlight\" style=\"display: block;\">" + serverResponse.searchString + "</span>"
        });
      }
      for( key in serverResponse.page_data )
      {
        if( Object.prototype.hasOwnProperty.call( serverResponse.page_data, key ))
        {
          aSuggestions.push({
            "id": key,
            "text": serverResponse.page_data[key]
          });
        }
      }

      /**
       * DEFECT10408
       * Making it so that it looks like at least one result was
       * returned -- whatever the user typed in.  This is because when
       * the field blurs, that text is automatically added as a tag.
       * So instead of confusing the end user with various behaviors
       * depending on the search results, the behavior is consistent
       * even when the text entered is not otherwise found as an
       * existing tag.
       */
      if( aSuggestions.length == 0 )
      {
        this.oAutoSuggestControl.setNoResultsMessage( this.currentSearchText );
      }

      this.returnResults(aSuggestions, this._bTypeAhead);
    },
    failedSearch: function( oXHR, sTextStatus )
    {
      this.lastSearchRequest = null;
      if( sTextStatus !== 'abort' )
      {
        alert( 'Tag search failed -- data: ' + sTextStatus );
      }
    }
  }
);

if( typeof initTagPicker == 'undefined' )
{
  function initTagPicker(instanceId, idFieldPrefix, valueFieldPrefix, defaultValue, defaultColor, focusedColor, noResultsMessage)
  {
    if( typeof instanceId == 'undefined' )
    {
      instanceId = ""; /* If this parameter is undefined (or omitted), only one Tag Picker can exist on the page... */
    }
    if( typeof idFieldPrefix == 'undefined' ) /* Pass an empty string for this parameter if you don't care about stuffing the ID of the selected Tag anywhere... */
    {
      idFieldPrefix = "TagId"; /* If this parameter is undefined (or omitted), it gets this default value... */
    }
    if( typeof valueFieldPrefix == 'undefined' )
    {
      valueFieldPrefix = "tagPicker"; /* If this parameter is undefined (or omitted), it gets this default value... */
    }
    if( typeof defaultValue == 'undefined' )
    {
      defaultValue = "Type Tag Here"; /* If this parameter is undefined (or omitted), it gets this default value... */
    }
    if( typeof defaultColor == 'undefined' )
    {
      defaultColor = "#999"; /* If this parameter is undefined (or omitted), it gets this default value... */
    }
    if( typeof focusedColor == 'undefined' )
    {
      focusedColor = "#000"; /* If this parameter is undefined (or omitted), it gets this default value... */
    }
    if( typeof noResultsMessage == 'undefined' )
    {
      noResultsMessage = "This is a new Tag"; /* Pass an empty string for this parameter if you want to use AutoSuggestControl's default value... */
    }
    var recentId;
    var recentValue;
    if( idFieldPrefix != '' )
    {
      var tagIdField = document.getElementById(idFieldPrefix + instanceId);
    }
    var picker = document.getElementById(valueFieldPrefix + instanceId);
    picker.value = defaultValue;
    picker.style.color = defaultColor;
    picker.autoSuggestControl = new AutoSuggestControl(picker, new tagPickerSearchProvider());
    if( typeof noResultsMessage == "string" && noResultsMessage != "" )
    {
      picker.autoSuggestControl.setNoResultsMessage(noResultsMessage);
    }
    picker.updateHandler = {
      handleUpdate: function(sId, sValue, bDeleteValue)
      {
        if( bDeleteValue || typeof sId != "string" )
        {
          if( idFieldPrefix != "" )
          {
            tagIdField.value = recentId;
          }
          picker.value = recentValue;
        }
        else
        {
          if( idFieldPrefix != "" )
          {
            tagIdField.value = sId;
          }
          picker.value = sValue;
        }
      }
    };
    picker.onfocus = function()
    {
      picker.autoSuggestControl.newSearch();
      if( picker.value.replace(/^\s*|\s*$/, "") == defaultValue )
      {
        picker.value = "";
        picker.style.color = focusedColor;
      }
      if( idFieldPrefix != "" )
      {
        recentId = tagIdField.value;
      }
      recentValue = picker.value;
    };
    picker.onchange = function()
    {
      picker.value = '';
      picker.blur();
      if( picker.value.replace(/^\s*|\s*$/, "") == "" )
      {
        picker.value = defaultValue;
        picker.style.color = defaultColor;
      }
    };
    picker.onblur = function()
    {
      picker.autoSuggestControl.abortSearch();
      picker.autoSuggestControl.toggleWatermarkText( false );
      if( picker.value.replace(/^\s*|\s*$/, "") == "" )
      {
        picker.value = defaultValue;
        picker.style.color = defaultColor;
      }
    };
  }
}

/* Remember to call initTagPicker(...) after including this file... */
