﻿Type.registerNamespace('EM.CMS.Modules.StyledAutoComplete');

EM.CMS.Modules.StyledAutoComplete.StyledAutoCompleteBehavior = function(element) {
    EM.CMS.Modules.StyledAutoComplete.StyledAutoCompleteBehavior.initializeBase(this, [element]);

    this._headerElement = null;
    this._footerElement = null;
}

EM.CMS.Modules.StyledAutoComplete.StyledAutoCompleteBehavior = function(element) {
    EM.CMS.Modules.StyledAutoComplete.StyledAutoCompleteBehavior.initializeBase(this, [element]);
}

EM.CMS.Modules.StyledAutoComplete.StyledAutoCompleteBehavior.prototype =
{
  /*initialize : function()
  {
  EM.CMS.Modules.StyledAutoComplete.StyledAutoCompleteBehavior.callBaseMethod(this, 'initialize');
  },

	dispose : function()
  {
  EM.CMS.Modules.StyledAutoComplete.StyledAutoCompleteBehavior.callBaseMethod(this, 'dispose');
  },*/

  get_contextPageId: function() {
    return this._contextPageId;
  },

  set_contextPageId: function(value) {
    this._contextPageId = value;
  },

  get_language: function() {
    return this._language;
  },

  set_language: function(value) {
    this._language = value;
  },

  get_positioningMode: function() {
    return this._positioningMode;
  },

  set_positioningMode: function(value) {
    this._positioningMode = value;
  },

  get_itemTemplate: function() {
    return this._itemTemplate;
  },

  set_itemTemplate: function(value) {
    this._itemTemplate = value;
  },

  get_headerTemplate: function() {
    return this._headerTemplate;
  },

  set_headerTemplate: function(value) {
    this._headerTemplate = value;
  },

  get_footerTemplate: function() {
    return this._footerTemplate;
  },

  set_footerTemplate: function(value) {
    this._footerTemplate = value;
  },

  get_completionListHeaderCssClass: function() {
    return this._completionListHeaderCssClass;
  },
  set_completionListHeaderCssClass: function(value) {
    if (this._completionListHeaderCssClass != value) {
      this._completionListHeaderCssClass = value; this.raisePropertyChanged('completionListHeaderCssClass');
    }
  },

  get_completionListFooterCssClass: function() {
    return this._completionListFooterCssClass;
  },
  set_completionListFooterCssClass: function(value) {
    if (this._completionListFooterCssClass != value) {
      this._completionListFooterCssClass = value; this.raisePropertyChanged('completionListFooterCssClass');
    }
  },

  get_completionListItemsHolderCssClass: function() {
    return this._completionListItemsHolderCssClass;
  },
  set_completionListItemsHolderCssClass: function(value) {
    if (this._completionListItemsHolderCssClass != value) {
      this._completionListItemsHolderCssClass = value; this.raisePropertyChanged('completionListItemsHolderCssClass');
    }
  },

  get_WebServiceCallCompleted: function() {
    return this.WebServiceCallCompleted;
  },

  set_WebServiceCallCompleted: function(value) {
    this.WebServiceCallCompleted = value;
  },

  _onMethodComplete: function(result, context) {
    /// <summary>
    /// Handler invoked when the webservice call is completed.
    /// </summary>
    /// <param name="result" type="Object" DomElement="false" mayBeNull="true" />
    /// <param name="context" type="String" DomElement="false" mayBeNull="true" />        
    /// <returns /> 
    this._webRequest = null; // clear out our saved WebRequest object
    this._update(context, result, /* cacheResults */true);
    if (this.WebServiceCallCompleted) {
      var methodName = this.WebServiceCallCompleted;
      eval(methodName + "(" + result.length + ")");
    }
  },

  _update: function(prefixText, completionItems, cacheResults) {

    if (cacheResults && this.get_enableCaching()) {
      if (!this._cache) {
        this._cache = {};
      }
      this._cache[prefixText] = completionItems;
    }

    if (completionItems && completionItems.length) {
      this._completionListElement.innerHTML = '';

      this._selectIndex = -1;
      var _firstChild = null;

      //Create Header;
      this._headerElement = document.createElement('div');
      this._headerElement.innerHTML = this._getHeaderHtml(completionItems[0]);
      if (this._completionListHeaderCssClass) {
        Sys.UI.DomElement.addCssClass(this._headerElement, this._completionListHeaderCssClass);
      }
      this._completionListElement.appendChild(this._headerElement);
      //Header Created

      var itemsHolder = null;
      itemsHolder = document.createElement('div');
      Sys.UI.DomElement.addCssClass(itemsHolder, this._completionListItemsHolderCssClass);


      for (var i = 0; i < completionItems.length; i++) {
        var itemElement = null;

        if (this._completionListElementID) {
          // the completion element has been created by the user and li won't necessarily work
          itemElement = document.createElement('div');
        } else {
          itemElement = document.createElement('li');
        }

        // set the first child if it is null
        if (_firstChild == null) {
          _firstChild = itemElement;
        }

        if (this._itemTemplate && Array.isInstanceOfType(completionItems[i])) {
          itemElement.innerHTML = this._getItemHtml(completionItems[i]);
          this._usingItemTemplate = true;
          itemElement._text = completionItems[i][0];
        }
        else {
          itemElement.appendChild(document.createTextNode(this._getTextWithInsertedWord(completionItems[i])));
          this._usingItemTemplate = false;
        }

        // itemElement.__item = '';

        if (this._completionListItemCssClass) {
          Sys.UI.DomElement.addCssClass(itemElement, this._completionListItemCssClass);
        } else {
          var itemElementStyle = itemElement.style;
          itemElementStyle.padding = '0px';
          itemElementStyle.textAlign = 'left';
          itemElementStyle.textOverflow = 'ellipsis';
          // workaround for safari since normal colors do not
          // show well there.
          if (Sys.Browser.agent === Sys.Browser.Safari) {
            itemElementStyle.backgroundColor = 'white';
            itemElementStyle.color = 'black';
          } else {
            itemElementStyle.backgroundColor = this._textBackground;
            itemElementStyle.color = this._textColor;
          }
        }
        itemsHolder.appendChild(itemElement);
        //this._completionListElement.appendChild(itemElement);
      }
      this._completionListElement.appendChild(itemsHolder);

      //Create Footer
      this._footerElement = document.createElement('div');
      this._footerElement.innerHTML = this._getFooterHtml(completionItems[0]);
      if (this._completionListFooterCssClass) {
        Sys.UI.DomElement.addCssClass(this._footerElement, this._completionListFooterCssClass);
      }
      this._completionListElement.appendChild(this._footerElement);
      //Footer Created

      this._popupBehavior.set_positioningMode(eval(this._positioningMode));

      var elementBounds = $common.getBounds(this.get_element());
      //The width will be set by the itemsHolder style
      //this._completionListElement.style.width = Math.max(1, elementBounds.width - 2) + 'px';
      this._completionListElement.scrollTop = 0;

      this.raisePopulated(Sys.EventArgs.Empty);

      var eventArgs = new Sys.CancelEventArgs();
      this.raiseShowing(eventArgs);
      if (!eventArgs.get_cancel()) {
        this._popupBehavior._visible = false;
        this.showPopup();
        // Check if the first Row is to be selected by default and if yes highlight it and updated selectIndex.
        if (this._firstRowSelected && (_firstChild != null)) {
          this._highlightItem(_firstChild);
          this._selectIndex = 0;
        }
      }
    } else {
      this._hideCompletionList();
    }
  },

  _getHeaderHtml: function(content) {
    var args = [this._headerTemplate];
    var length = content.length;
    for (var i = 0; i < length; i++) {
      args.push(content[i]);
    }
    return String.format.apply(null, args);
  },

  _getItemHtml: function(content) {
    var args = [this._itemTemplate];
    var length = content.length;
    for (var i = 0; i < length; i++) {
      args.push(content[i]);
    }
    return String.format.apply(null, args);
  },

  _getFooterHtml: function(content) {
    var args = [this._footerTemplate];
    var length = content.length;
    for (var i = 0; i < length; i++) {
      args.push(content[i]);
    }
    return String.format.apply(null, args);
  },

  _setText: function(item) {
    //fix to take the right text when some of item's level 1 children is under the mouse
    if (item.parentNode._text) {
      item = item.parentNode
    }
    if (item._text) {
      var text = null;

      if (this._usingItemTemplate) {
        while (!item._text) {
          item = item.parentNode;
        }

        text = this._getTextWithInsertedWord(item._text);
      }
      else {
        text = (item && item.firstChild) ? item.firstChild.nodeValue : null;
      }

      this.raiseItemSelected(new AjaxControlToolkit.AutoCompleteItemEventArgs(item, text));

      this._timer.set_enabled(false);

      var element = this.get_element();
      var control = element.control;
      if (control && control.set_text) {
        control.set_text(text);
        $common.tryFireEvent(control, "change");
      }
      else {
        element.value = text;
        $common.tryFireEvent(element, "change");
      }
      this._currentPrefix = this._currentCompletionWord();
      this._hideCompletionList();
    }
  },

  _highlightItem: function(item) {
    /// <summary>
    /// Highlights the specified item
    /// </summary>
    /// <param name="item" type="Sys.UI.DomElement" DomElement="true" mayBeNull="false" />
    /// <returns />

    var children = this._completionListElement.childNodes[1].childNodes;

    // Unselect any previously highlighted item
    for (var i = 0; i < children.length; i++) {
      var child = children[i];
      if (child._highlighted) {
        if (this._completionListItemCssClass) {
          if (this._highlightedItemCssClass) {
            Sys.UI.DomElement.removeCssClass(child, this._highlightedItemCssClass);
          }
          Sys.UI.DomElement.addCssClass(child, this._completionListItemCssClass);
        } else {
          if (Sys.Browser.agent === Sys.Browser.Safari) {
            child.style.backgroundColor = 'white';
            child.style.color = 'black';
          } else {
            child.style.backgroundColor = this._textBackground;
            child.style.color = this._textColor;
          }
        }
        this.raiseItemOut(new AjaxControlToolkit.AutoCompleteItemEventArgs(child, child.firstChild.nodeValue, child._value));
      }
    }

    //REMOVED BECAUSE OF BUG ON KEYUP AND KEYDOWN
    // Highlight the new item
    if (this._highlightedItemCssClass) {
      Sys.UI.DomElement.removeCssClass(item, this._completionListItemCssClass);
      Sys.UI.DomElement.addCssClass(item, this._highlightedItemCssClass);
    } else {
      if (Sys.Browser.agent === Sys.Browser.Safari) {
        item.style.backgroundColor = 'lemonchiffon';
      } else {
        item.style.backgroundColor = 'highlight';
        item.style.color = 'highlighttext';
      }

    }
    item._highlighted = true;
    this.raiseItemOver(new AjaxControlToolkit.AutoCompleteItemEventArgs(item, item.firstChild.nodeValue, item._value));
  },

  _onTimerTick: function(sender, eventArgs) {
    /// <summary>
    /// Handler invoked when a timer tick occurs
    /// </summary>
    /// <param name="sender" type="Object" mayBeNull="true"/>
    /// <param name="eventArgs" type="Sys.EventArgs" mayBeNull="true" />        
    /// <returns />

    // turn off the timer until another key is pressed.
    this._timer.set_enabled(false);
    if (this._servicePath && this._serviceMethod) {
      var text = this._currentCompletionWord();

      if (text.trim().length < this._minimumPrefixLength) {
        this._currentPrefix = null;
        this._update('', null, /* cacheResults */false);
        return;
      }
      // there is new content in the textbox or the textbox is empty but the min prefix length is 0
      if ((this._currentPrefix !== text) || ((text == "") && (this._minimumPrefixLength == 0))) {
        this._currentPrefix = text;
        if ((text != "") && this._cache && this._cache[text]) {
          this._update(text, this._cache[text], /* cacheResults */false);
          return;
        }
        // Raise the populating event and optionally cancel the web service invocation
        var eventArgs = new Sys.CancelEventArgs();
        this.raisePopulating(eventArgs);
        if (eventArgs.get_cancel()) {
          return;
        }

        // Create the service parameters and optionally add the context parameter
        // (thereby determining which method signature we're expecting...)
        var params = { prefixText: this._currentPrefix
                              , count: this._completionSetCount
                              , contextPageId: this._contextPageId
                              , language: this._language
        };

        if (this._useContextKey) {
          params.contextKey = this._contextKey;
        }

        if (this._webRequest) {
          // abort the previous web service call if we 
          // are issuing a new one and the previous one is 
          // active.
          this._webRequest.get_executor().abort();
          this._webRequest = null;
        }
        // Invoke the web service
        this._webRequest = Sys.Net.WebServiceProxy.invoke(this.get_servicePath(), this.get_serviceMethod(), false, params,
                                            Function.createDelegate(this, this._onMethodComplete),
                                            Function.createDelegate(this, this._onMethodFailed),
                                            text);
        $common.updateFormToRefreshATDeviceBuffer();
      }
    }
  },

  //    Do not hide the autocomplete for test purposes
  //      _hideCompletionList: function() {
  //      },

  _onCompletionListBlur: function(ev) {
    //this._hideCompletionList();

  },

  _onKeyDown: function(ev) {
    /// <summary>
    /// Handler for the textbox keydown event.
    /// </summary>
    /// <param name="ev" type="Sys.UI.DomEvent" DomElement="false" mayBeNull="false" />
    /// <returns />      
    ///debugger;
    this._timer.set_enabled(false);
    // the last key press occured so we need to "reset" the timer.
    var k = ev.keyCode ? ev.keyCode : ev.rawEvent.keyCode;
    if (k === Sys.UI.Key.esc) {
      this._hideCompletionList();
      ev.preventDefault();
    }
    else if (k === Sys.UI.Key.up) {
      if (this._selectIndex > 0) {
        this._selectIndex--;
        this._handleScroll(this._completionListElement.childNodes[1].childNodes[this._selectIndex], this._selectIndex);
        this._highlightItem(this._completionListElement.childNodes[1].childNodes[this._selectIndex]);
        ev.stopPropagation();
        ev.preventDefault();
      }
      else {
        this._selectIndex = (this._completionListElement.childNodes[1].childNodes.length - 1);
        this._handleScroll(this._completionListElement.childNodes[1].childNodes[this._selectIndex], this._selectIndex);
        this._highlightItem(this._completionListElement.childNodes[1].childNodes[this._selectIndex]);
        ev.stopPropagation();
        ev.preventDefault();
      }
    }
    else if (k === Sys.UI.Key.down) {
      if (this._selectIndex < (this._completionListElement.childNodes[1].childNodes.length - 1)) {
        this._selectIndex++;
        this._handleScroll(this._completionListElement.childNodes[1].childNodes[this._selectIndex], this._selectIndex);
        this._highlightItem(this._completionListElement.childNodes[1].childNodes[this._selectIndex]);
        ev.stopPropagation();
        ev.preventDefault();
      }
      else {
        this._selectIndex = 0;
        this._handleScroll(this._completionListElement.childNodes[1].childNodes[this._selectIndex], this._selectIndex);
        this._highlightItem(this._completionListElement.childNodes[1].childNodes[this._selectIndex]);
        ev.stopPropagation();
        ev.preventDefault();
      }
    }
    else if (k === Sys.UI.Key.enter) {
      if (this._selectIndex !== -1) {
        //this._setText(this._completionListElement.childNodes[this._selectIndex]);
        if (this._completionListElement.childNodes[1].childNodes[this._selectIndex].childNodes[0].href) {
          document.location = this._completionListElement.childNodes[1].childNodes[this._selectIndex].childNodes[0].href;
        }
        ev.preventDefault();
      } else {
        // close the popup
        this.hidePopup();
      }
    }
    else if (k === Sys.UI.Key.tab) {
      if (this._selectIndex !== -1) {
        this._setText(this._completionListElement.childNodes[this._selectIndex]);
      }
    }
    else {
      this._timer.set_enabled(true);
      // start the timer to retrieve results since now it is an actual key
    }
  },

  _onListMouseOver: function(ev) {
    /// <summary>
    /// Handler for the mouseover event on the autocomplete flyout.
    /// </summary>
    /// <param name="ev" type="Sys.UI.DomEvent" DomElement="false" mayBeNull="false" />
    /// <returns />      
    var item = ev.target;
    if (item !== this._completionListElement &&
           item !== this._headerElement &&
           item !== this._footerElement) {
      var children = this._completionListElement.childNodes[1].childNodes;
      // make sure the selected index is updated
      for (var i = 0; i < children.length; ++i) {
        if (item === children[i]) {
          this._highlightItem(item);
          this._selectIndex = i;
          break;
        }
        //fix to highlight item when some of his level 1 children is under the mouse
        if (item.parentNode === children[i]) {
          this._highlightItem(item.parentNode);
          this._selectIndex = i;
          break;
        }
      }
    }
  }
}

EM.CMS.Modules.StyledAutoComplete.StyledAutoCompleteBehavior.registerClass('EM.CMS.Modules.StyledAutoComplete.StyledAutoCompleteBehavior', AjaxControlToolkit.AutoCompleteBehavior);
if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();