/* oTextbox: The input element in which the user enters data
 * field: The name of the field
 * searchfield: The name of the searchfield
 * bTypeAhead: Wether suggestions are also given in the textbox itself.
 */
function AutoSuggestControl(oTextbox, field, searchField, bTypeAhead, sURL) {    
    this.cur = -1;
    this.layer = null;
//    this.provider = new Ajax();
    this.textbox = oTextbox;
    this.typeahead = bTypeAhead;
    this.field = field;
    this.searchField = searchField;
    // The hidden form field whose value is actually sent to the engine once a suggestion has been selected.
    this.oHiddenKeyField = document.getElementById(searchField);
    this.sURL = sURL;
    this.init();
	this.currentSuggestions;
	this.submitValue = false;
}

// Autosuggests one or more suggestions for what the user has typed.
AutoSuggestControl.prototype.autosuggest = function (suggestions) {
	if (suggestions[0][0] == "autosuggest_submit_value") {
		if (suggestions[0][1] == "true") {
			this.submitValue = true;
		} else {
			this.submitValue = false;
		}
		// 'autosuggest_submit_value' is altijd het eerste element, dus die schrappen we met shift()
		suggestions.shift();
	}
	// Make sure there's at least one suggestion
	this.currentSuggestions = suggestions;
    if (suggestions) {
        this.showSuggestions(suggestions);
    } else {
        this.hideSuggestions();
    }
};

// Creates the dropdown layer to display multiple suggestions.
AutoSuggestControl.prototype.createDropDown = function () {

    var oThis = this;

    // Create the layer and assign styles
    this.layer = document.createElement("div");
    this.layer.className = "cx_suggestions";
    this.layer.style.visibility = "hidden";
    //this.layer.style.width = this.textbox.offsetWidth;
    
    this.layer.onmousedown = 
    this.layer.onmouseup = 
    this.layer.onmouseover = function (oEvent) {
        oEvent = oEvent || window.event;
        oTarget = oEvent.target || oEvent.srcElement;
		// When the user clicks on the a suggestion, get the text (innerHTML) and place it into a textbox and put the key in the hidden field
        if (oEvent.type == "mousedown") {
            oThis.textbox.value = oTarget.firstChild.nodeValue;
			oThis.oHiddenKeyField.value = oThis.getKey(oThis.textbox.value);
			oThis.hideSuggestions();
			new Ajax.Request(oThis.sURL + "&" + oThis.field + "=" + oThis.textbox.value 
					+ "&" + oThis.oHiddenKeyField.id + "=" + encodeURIComponent(oThis.oHiddenKeyField.value), { onSuccess: function(transport) { oThis.evalChangedElements(transport); }});
        } else if (oEvent.type == "mouseover") {
            oThis.highlightSuggestion(oTarget);
        } else {
            oThis.textbox.focus();
        }
    };    
    
    document.body.appendChild(this.layer);
};

// Gets the left coordinate of the textbox.
AutoSuggestControl.prototype.getLeft = function () {

    var oNode = this.textbox;
    var iLeft = 0;
    
    while(oNode.tagName != "BODY") {
        iLeft += oNode.offsetLeft;
        oNode = oNode.offsetParent;        
    }
    
    return iLeft;
};

// Gets the top coordinate of the textbox.
AutoSuggestControl.prototype.getTop = function () {

    var oNode = this.textbox;
    var iTop = 0;
    
    while(oNode.tagName != "BODY") {
        iTop += oNode.offsetTop;
        oNode = oNode.offsetParent;
    }
    
    return iTop;
};

// Handles three keydown events.
AutoSuggestControl.prototype.handleKeyDown = function (oEvent) {
	var oThis = this;
    switch(oEvent.keyCode) {
        case 38: //up arrow
            this.previousSuggestion();
            break;
        case 40: //down arrow 
            this.nextSuggestion();
            break;
        case 13: //enter
            this.hideSuggestions();
			// keep eventhandler of standard.js 
			this.oHiddenKeyField.value = this.getKey(this.textbox.value);
			var url = this.sURL + "&" + this.field + "=" + this.textbox.value 
				+ "&" + this.oHiddenKeyField.id + "=" + encodeURIComponent(this.oHiddenKeyField.value);
			new Ajax.Request(url, { onSuccess: function(transport) { oThis.evalChangedElements(transport); }});
            CX.keyDown(oEvent);
            break;
    }

};

// Handles keyup events.
AutoSuggestControl.prototype.handleKeyUp = function (oEvent /*:Event*/) {
	var oThis = this;
	if (this.textbox.value == null || this.textbox.value == "") {
		this.oHiddenKeyField.value = "";
		new Ajax.Request(this.sURL + "&" + this.field + "=&" + this.oHiddenKeyField.id + "=", { onSuccess: function(transport) { oThis.evalChangedElements(transport); }});
	} else {
		if (this.submitValue) {
			this.oHiddenKeyField.value = this.textbox.value;
		}
		var iKeyCode = oEvent.keyCode;
		var URL = "/engine?service=application&cmd=getlookuplist&field=" + this.field + "&value=" + encodeURIComponent(this.textbox.value) + "&ajax=true";
		//var url = this.sURL + "&value=" + encodeURIComponent(this.textbox.value) 
	    // For backspace (8) and delete (46), shows suggestions without typeahead
	    if (iKeyCode == 8 || iKeyCode == 46) {
	        var oAutosuggestControl = this;
	    	new Ajax.Request(URL, { onSuccess: function(transport) { var arr = transport.responseText.evalJSON(); oAutosuggestControl.autosuggest(arr) }});
	     	// Make sure not to interfere with non-character keys
	    } else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123)) {
	        //ignore
	    } else {
	        //request suggestions from the suggestion provider with typeahead
	        var oAutosuggestControl = this;
	    	new Ajax.Request(URL, { onSuccess: function(transport) { var arr = transport.responseText.evalJSON(); oAutosuggestControl.autosuggest(arr) }});
	    }
	}
};

AutoSuggestControl.prototype.evalChangedElements = function(transport) {
    var xAjaxString = transport.responseText;
    if (xAjaxString != '') {
        if (xAjaxString == "RELOAD:/engine") {
          location.href = "/engine";
        } else if (xAjaxString == "EXPIRED") {
  		  location.href = "/engine";  
        } else if (xAjaxString.isJSON()) {
          var xAjaxObject = xAjaxString.evalJSON();
          var action = xAjaxObject["action"];
          var elementList = xAjaxObject["elements"];
          var popup = xAjaxObject["popup"];
          var js = xAjaxObject["js"];
          if (elementList) {
            for (var i = 0; i < elementList.length; i++) {
              var elementPair = elementList[i];
              var element = $(elementPair[0]);
              var newHTML = elementPair[1];
              if (element) {
                switch(action) {
                  case "replace":
                    element.replace(newHTML);
                    if (newHTML != '') {
                      // The replaced element always has the same id.
                      var freshElement = elementPair[0];
                    }
                    break;
                  case "before":
                    element.insert({"before":newHTML});
                    break;
                  case "after":
                    element.insert({"after":newHTML});
                    break;
                  case "remove":
                    element.remove();
                    break;
                  case "update":
                    element.update(newHTML);
                    break;
                }
              } else {
                CX.sendNotification('AJAX-ERROR: HTML element ' + elementPair[0] + ' not found in DOM.');
              }
            }
          }
          if (popup) {
            CX.dialogWindow = CX.openPopupBox("popup","Message", 400, 150, "cx_popup", null);
            var ok = "CX.closeDialog()";
            var html = popup + "<div align=\"center\"><form name=\"cx_dialogForm\"><input id=\"cx_dialog-yes\" type=\"button\" name=\"OK\" value=\"OK\" onclick=\"" + ok + "\"></form></div>";
            CX.dialogWindow.getContent().innerHTML = html;
          }
          eval(js);
        } else {
            CX.sendNotification('AJAX-ERROR: Response for request "' + url + '" was not valid JSON', xAjaxString);
            location.href = "/engine";
        }
    } else {
        /* 
         * Dit hoeft niet erg te zijn. Er kan een calculated veld zijn dat wel van waarde
         * verandert door een autosubmit maar niet in het scherm staat. Dus geen html. Dus geen 
         * notifier.
         * 
         * CX.sendNotification('AJAX-ERROR: Application engine returned an empty string');
         */ 
    }
    document.body.style.cursor = 'default';
};

// Hides the suggestion dropdown.
AutoSuggestControl.prototype.hideSuggestions = function () {
    this.layer.style.visibility = "hidden";
};

// Highlights the given node in the suggestions dropdown.
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 = "";
        }
    }
};

// Initializes the textbox with event handlers for auto suggest functionality.
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);
    };
    
    //assign onkeydown event handler
    this.textbox.onkeydown = function (oEvent) {
    
        //check for the proper location of the event object
        if (!oEvent) {
            oEvent = window.event;
        }    
        
        //call the handleKeyDown() method with the event object
        oThis.handleKeyDown(oEvent);
    };
    
    //assign onblur event handler (hides suggestions)    
    this.textbox.onblur = function () {
        oThis.hideSuggestions();
    };
    
    //create the suggestions dropdown
    this.createDropDown();
};

// Highlights the next suggestion in the dropdown and places the suggestion into the textbox.
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);
        this.textbox.value = oNode.firstChild.nodeValue; 
    }
};

// Highlights the previous suggestion in the dropdown and places the suggestion into the textbox.
AutoSuggestControl.prototype.previousSuggestion = function () {
    var cSuggestionNodes = this.layer.childNodes;

    if (cSuggestionNodes.length > 0 && this.cur > 0) {
        var oNode = cSuggestionNodes[--this.cur];
        this.highlightSuggestion(oNode);
        this.textbox.value = oNode.firstChild.nodeValue;   
    }
};

AutoSuggestControl.prototype.getKey = function (value) {
	if (this.submitValue) {
		return value;
	} else {
		if (this.currentSuggestions.length == 1) return this.currentSuggestions[0][0];
		for (i=0;i< this.currentSuggestions.length;i++) {
			if (this.currentSuggestions[i][1].toUpperCase() == value.toUpperCase())
				return this.currentSuggestions[i][0];
		}
		return "";
	}
}

// Selects a range of text in the textbox.
AutoSuggestControl.prototype.selectRange = function (iStart, iLength) {

    // 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);
    }     

    this.textbox.focus();      
}; 

// Builds the suggestion layer contents, moves it into position, and displays the layer.
AutoSuggestControl.prototype.showSuggestions = function (aSuggestions) {
    
    var oDiv = null;
    this.layer.innerHTML = "";  //clear contents of the layer
		// Work-around for IE6 only
    if (oBrowser.isIE && oBrowser.version == 6) {
	    this.layer.innerHTML = '<iframe src="about:blank" scrolling="no" frameborder="0" id="cx_shimframe"></frame>';
    }  
    for (var i=0; i < aSuggestions.length; i++) {
      oDiv = document.createElement("div");
      oDiv.appendChild(document.createTextNode(aSuggestions[i][1]));
      this.layer.appendChild(oDiv);
      if (i == 0 && this.typeahead) {
         this.typeAhead(aSuggestions[i][1]);
      }        
    }

    this.layer.style.left = this.getLeft() + "px";
    this.layer.style.top = (this.getTop()+this.textbox.offsetHeight) + "px";
    this.layer.style.visibility = "visible";
    if (oBrowser.isIE && oBrowser.version == 6) {
			// HACK: used fixed height
			document.getElementById('cx_shimframe').style.height = 256;
		  document.getElementById('cx_shimframe').style.width = this.layer.style.width;
    }
};

// Inserts a suggestion into the textbox, highlighting the suggested part of the text.
AutoSuggestControl.prototype.typeAhead = function (sSuggestion) {

    //check for support of typeahead functionality
    if (this.textbox.createTextRange || this.textbox.setSelectionRange){
        var iLen = this.textbox.value.length; 
        this.textbox.value = sSuggestion; 
        this.selectRange(iLen, sSuggestion.length);
    }
};


