/**
 * An autosuggest textbox control.
 * @class
 * @scope public
 */
function AutoSuggestControl(oTextbox, oProvider) {
       
    /**
     * Suggestion provider for the autosuggest feature.
     * @scope private.
     */
    this.provider /*:SuggestionProvider*/ = oProvider;
    
    /**
     * The textbox to capture.
     * @scope private
     */
    this.textbox /*:HTMLInputElement*/ = oTextbox;
    
    //initialize the control
    this.init();
}

/**
 * Autosuggests one or more suggestions for what the user has typed.
 * If no suggestions are passed in, then no autosuggest occurs.
 * @scope private
 * @param aSuggestions An array of suggestion strings.
 */
AutoSuggestControl.prototype.autosuggest = function (aSuggestions, bTypeAhead) {
    
    //make sure there's at least one suggestion
    if (aSuggestions.length > 0) {
        if (bTypeAhead) {
            this.typeAhead(aSuggestions[0]);
        }
        this.showSuggestions(aSuggestions);
    } else {
        this.hideSuggestions();
    }
};


/**
 * Handles keyup events.
 * @scope private
 * @param oEvent The event object for the keyup event.
 */
AutoSuggestControl.prototype.handleKeyUp = function (oEvent /*:Event*/) {

    var iKeyCode = oEvent.keyCode;

    //make sure not to interfere with non-character keys
    if (iKeyCode == 8 || iKeyCode == 46) {
        this.provider.ProvideSuggestions(this, false);
    } else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode <= 46) || (iKeyCode >= 112 && iKeyCode <= 123)) {
        //ignore
    } else {
        //***HERE*** request suggestions from the suggestion provider
        this.provider.ProvideSuggestions(this, true)
    }
};

AutoSuggestControl.prototype.handleKeyDown = function (oEvent) {
    switch(oEvent.keyCode) {
        case 38: //up arrow
            this.previousSuggestion();
            break;
        case 40: //down arrow
            this.nextSuggestion();
            break;
        case 13: //enter
        	//***Action here***
        	if(this.layer.style.visibility=="hidden")
        	{
        		//Ffe nix doen
        	}
            this.hideSuggestions();
            break;
    }
};

/**
 * Initializes the textbox with event handlers for
 * auto suggest functionality.
 * @scope private
 */
AutoSuggestControl.prototype.init = function () {

    //save a reference to this object
    var oThis = this;
    
    //assign the onkeyup event handler
    this.textbox.onkeyup = function (oEvent) {
    
        //check for the proper location of the event object
        if (!oEvent) {
            oEvent = window.event;
        }    
        
        //call the handleKeyUp() method with the event object
        oThis.handleKeyUp(oEvent);
    };
    
    this.textbox.onkeydown = function (oEvent) {

        if (!oEvent) {
            oEvent = window.event;
        }

        oThis.handleKeyDown(oEvent);
    };

    this.textbox.onblur = function () {
        oThis.hideSuggestions();
        try {
          oThis.provider.onblur(oThis.textbox);
        } catch (err) {
          //Do nothing
        }
        
    };

    this.createDropDown();
};

/**
 * Selects a range of text in the textbox.
 * @scope public
 * @param iStart The start index (base 0) of the selection.
 * @param iLength The number of characters to select.
 */
AutoSuggestControl.prototype.selectRange = function (iStart /*:int*/, iLength /*:int*/) {

    //use text ranges for Internet Explorer
    if (this.textbox.createTextRange) {
        var oRange = this.textbox.createTextRange(); 
        oRange.moveStart("character", iStart); 
        oRange.moveEnd("character", iLength - this.textbox.value.length);      
        oRange.select();
        
    //use setSelectionRange() for Mozilla
    } else if (this.textbox.setSelectionRange) {
        this.textbox.setSelectionRange(iStart, iLength);
    }     

    //set focus back to the textbox
    this.textbox.focus();      
}; 

/**
 * Inserts a suggestion into the textbox, highlighting the 
 * suggested part of the text.
 * @scope private
 * @param sSuggestion The suggestion for the textbox.
 */
AutoSuggestControl.prototype.typeAhead = function (sSuggestion /*:String*/) {

    //check for support of typeahead functionality
    if (this.textbox.createTextRange || this.textbox.setSelectionRange){
        var iLen = this.textbox.value.length; 
        
        if(this.sIgnore != '')
        {
          this.textbox.value = sSuggestion.substr(0, sSuggestion.indexOf(this.sIgnore)); 
        } else {
          this.textbox.value = sSuggestion;
        }
        
        this.selectRange(iLen, sSuggestion.length);
    }
};

//Drop downbox stuff:
function AutoSuggestControl(oTextbox, oProvider, bDynamicSize, sIgnoreFrom) {
  	this.cur = -1;
    this.layer = null;
    this.provider = oProvider;
    this.textbox = oTextbox;
    this.bDynSize = bDynamicSize;
    this.sIgnore = sIgnoreFrom;
    this.init();
}

//Hide dropdownbox itself
AutoSuggestControl.prototype.hideSuggestions = function () {
    this.layer.style.visibility = "hidden";
};

//Hide dropdown highlight
AutoSuggestControl.prototype.highlightSuggestion = function (oSuggestionNode) {
    for (var i=0; i < this.layer.childNodes.length; i++) {
        var oNode = this.layer.childNodes[i];
        if (oNode == oSuggestionNode) {
            oNode.className = "current"
        } else if (oNode.className == "current") {
            oNode.className = "";
        }
    }
};

//Create the drop down control:
AutoSuggestControl.prototype.createDropDown = function () {

    var sTmpstr;

    this.layer = document.createElement("div");
    this.layer.className = "suggestions";
    this.layer.style.visibility = "hidden";
    
    if(this.bDynSize != true)
    {
      if (!IE) {sTmpstr = this.textbox.offsetWidth + 'px';} else {sTmpstr = (this.textbox.offsetWidth - 2) + 'px';}
      this.layer.style.width = sTmpstr;
    }
    
    document.body.appendChild(this.layer);

    var oThis = this;

    this.layer.onmousedown = this.layer.onmouseup =
    this.layer.onmouseover = function (oEvent) {
        oEvent = oEvent || window.event;
        oTarget = oEvent.target || oEvent.srcElement;

        if (oEvent.type == "mousedown") {
            var sCurVal = oTarget.firstChild.nodeValue;
            
            if(this.sIgnore != '')
            {
              oThis.textbox.value = sCurVal.substr(0, sCurVal.indexOf(oThis.sIgnore)); 
            } else {
              oThis.textbox.value = sCurVal;
            }
       
            oThis.hideSuggestions();
        } else if (oEvent.type == "mouseover") {
            oThis.highlightSuggestion(oTarget);
        } else {
            oThis.textbox.focus();
        }
    };
};

AutoSuggestControl.prototype.getLeft = function () {

    var oNode = this.textbox;
    var iLeft = 0;

    try {
      while(oNode.tagName != "BODY") {
        iLeft += oNode.offsetLeft;
        oNode = oNode.offsetParent;
      }
    } catch(err) {
      var i =0;
    }
    

    return iLeft;
};

AutoSuggestControl.prototype.getTop = function () {

    var oNode = this.textbox;
    var iTop = 0;
    
    try {
      while(oNode.tagName != "BODY") {
          iTop += oNode.offsetTop;
          oNode = oNode.offsetParent;
      }
    } catch(err) {
      var i =0;
    }

    return iTop;
};

AutoSuggestControl.prototype.showSuggestions = function (aSuggestions) {

  var sTmpstr;

  if(this.textbox.value.length==0)
    {
        this.hideSuggestions();	
    } else {
	    var oDiv = null;
	    this.layer.innerHTML = "";
	
	    for (var i=0; i < aSuggestions.length; i++) {
	        oDiv = document.createElement("div");
	        oDiv.appendChild(document.createTextNode(aSuggestions[i]));
	        this.layer.appendChild(oDiv);
	    }
	   
	    sTmpstr = this.getLeft();
	    if (!IE) {sTmpstr = sTmpstr + 'px';}
	    this.layer.style.left = sTmpstr;
	    sTmpstr = (this.getTop()+this.textbox.offsetHeight);
	    if (!IE) {sTmpstr = sTmpstr + 'px';}
	    this.layer.style.top = sTmpstr;
	    this.layer.style.visibility = "visible";
    }
};

AutoSuggestControl.prototype.nextSuggestion = function () {
    var cSuggestionNodes = this.layer.childNodes;

    if (cSuggestionNodes.length > 0 && this.cur < cSuggestionNodes.length-1) {
        var oNode = cSuggestionNodes[++this.cur];
        this.highlightSuggestion(oNode);
        var sCurVal = oNode.firstChild.nodeValue;
        
        if(this.sIgnore != '')
        {          
          this.textbox.value = oNode.firstChild.nodeValue.substr(0, sCurVal.indexOf(this.sIgnore)); 
        } else {
          this.textbox.value = oNode.firstChild.nodeValue;
        }
    }
};

AutoSuggestControl.prototype.previousSuggestion = function () {
    var cSuggestionNodes = this.layer.childNodes;

    if (cSuggestionNodes.length > 0 && this.cur > 0) {
        var oNode = cSuggestionNodes[--this.cur];
        this.highlightSuggestion(oNode);
        var sCurVal = oNode.firstChild.nodeValue;
        
        if(this.sIgnore != '')
        {          
          this.textbox.value = oNode.firstChild.nodeValue.substr(0, sCurVal.indexOf(this.sIgnore)); 
        } else {
          this.textbox.value = oNode.firstChild.nodeValue;
        }
    }
};