LoadInProgress = false
var overedElement1 = "";
var overedElement2 = "";
var killBox
var curOpenObj
var LargerOffsetDropDownTFW = 0
var LargerOffsetDropDownHotel = 0
var TFWTypeID = "";

/* List of suggestions formatted to fit textbox (without html)*/
eSuggestions = [];
completeSuggestions = [];
/**
 * An autosuggest textbox control.
 * @class
 * @scope public
 */
function AutoSuggestControl(oTextbox /*:HTMLInputElement*/, 
                            oProvider /*:SuggestionProvider*/, 
                            oType /*:Hotel or TFW*/, TFWType) {

	 /**
     * The currently selected suggestions.
     * @scope private
     */   
    this.cur /*:int*/ = -1;

    /**
     * The dropdown list layer.
     * @scope private
     */
    this.layer = null;
    
    /**
     * Suggestion provider for the autosuggest feature.
     * @scope private. (For html formatted name)
     */
    this.provider /*:SuggestionProvider*/ = oProvider;
	
	/**
     * The textbox to capture.
     * @scope private
     */
    this.textbox /*:HTMLInputElement*/ = oTextbox;
    
    this.TypeEng /*:Type of engine call*/ = oType;
        
    this.offsetBoxWidth /* offset to control the dropdown width */ = eval("LargerOffsetDropDown" + this.TypeEng)
    
    this.NewTFWType = TFWType
    TFWTypeID = TFWType;
    
    //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.
 * @param bTypeAhead If the control should provide a type ahead suggestion.
 */
AutoSuggestControl.prototype.autosuggest = function (aSuggestions /*:2D Array*/, dSuggestions, compSuggestions, bTypeAhead /*:boolean*/) {
   
   var oThis = this;
   
    /* We need to reinitialize this variable*/
	this.cur = -1;
    //make sure there's at least one suggestion
    
    if (aSuggestions.length > 0) {
    
		if (bTypeAhead){
			this.typeAhead(aSuggestions[0]);
			this.typeAhead(dSuggestions[0]);
			this.typeAhead(compSuggestions[0][0][0]);
		}
		eSuggestions = dSuggestions;
		completeSuggestions = compSuggestions;
    
		if(aSuggestions.length == '1'){
			oThis.textbox.value = eSuggestions[0];
			eval("oThis.select" + oThis.TypeEng + "Value(0)");
			oThis.hideSuggestions();
		}else{
			this.showSuggestions(aSuggestions);	
		}
    } else {
        this.hideSuggestions();
    }
};

/**
 * Creates the dropdown layer to display multiple suggestions.
 * @scope private
 */
AutoSuggestControl.prototype.createDropDown = function () {
	
    var oThis = this;
	//create the layer and assign styles
    this.layer = document.createElement("div");
    this.layer.className = "suggestions";
	this.layer.style.visibility = "hidden";
	this.layer.style.zIndex = 4;
	this.layer.style.overflow = 'hidden';
	this.layer.style.height = 150
    
    this.layer.onmouseover = function (oEvent) {
		clearTimeout(killBox)
	}
	this.layer.onmouseout = function (oEvent) {
		curOpenObj = oThis
        killBox = setTimeout("CloseLayer(curOpenObj)",100);         
	}
    oOutsideDiv=document.body.appendChild(this.layer);
	
	oObjDiv = document.createElement("div");
    oObjDiv.style.width = this.textbox.offsetWidth + this.offsetBoxWidth - 16;
    
    //when the user clicks on the a suggestion, get the text (innerHTML)
    //and place it into a textbox
    
    oObjDiv.onmouseout =
    oObjDiv.onmousedown = 
    oObjDiv.onmouseup =  
    oObjDiv.onmouseover = function (oEvent) {
        oEvent = oEvent || window.event;
        oTarget = oEvent.target || oEvent.srcElement;
        
		if (oEvent.type == "mousedown") {
            for( var x = 0; x < oTarget.attributes.length; x++ ) {
				if( oTarget.attributes[x].nodeName.toLowerCase() == 'id' ) {
					
					var hotelid = oTarget.attributes[x].nodeValue;				
					var isSearchText = hotelid.indexOf('searchText');
					
					if (isSearchText == -1){
						//We do nothing
					}else{
						hotelid = hotelid.substring(10);
					}
					oThis.textbox.value = eSuggestions[hotelid];
					eval("oThis.select" + oThis.TypeEng + "Value(hotelid)")
					//oThis.selectTFWValue(hotelid);
				}
			}
			oThis.hideSuggestions();
			
			
        } else if (oEvent.type == "mouseover") {
           	oThis.highlightSuggestion(oTarget);
           	
         
        } else {
			if(!oThis.textbox.disabled)
				oThis.textbox.focus();
        }
    };
    
	oInsideDiv = oOutsideDiv.appendChild(oObjDiv);
	
};

function CloseLayer(obj)
{
	//alert(obj)
	if(obj){
		obj.hideSuggestions()
		if (document.getElementById(obj.textbox.id + "EmptyValue")){
			emptyValueRef = document.getElementById(obj.textbox.id + "EmptyValue");
			obj.textbox.value = emptyValueRef.innerHTML;
		}
	}
}

/**
 * Gets the left coordinate of the textbox.
 * @scope private
 * @return The left coordinate of the textbox in pixels.
 */
AutoSuggestControl.prototype.getLeft = function () /*:int*/ {

    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.
 * @scope private
 * @return The top coordinate of the textbox in pixels.
 */
AutoSuggestControl.prototype.getTop = function () /*:int*/ {

    var oNode = this.textbox;
    var iTop = 0;
    
    while(oNode.tagName != "BODY") {
        iTop += oNode.offsetTop;
        oNode = oNode.offsetParent;
    }
    
    return iTop;
};

/**
 * Handles three keydown events.
 * @scope private
 * @param oEvent The event object for the keydown event.
 */
AutoSuggestControl.prototype.handleKeyDown = function (oEvent /*:Event*/) {
	
	switch(oEvent.keyCode) {
        case 38: //up arrow
            this.previousSuggestion();
            break;
        case 40: //down arrow 
            this.nextSuggestion();
            break;
        case 13: //enter
			this.selectTFWValue(this.cur);
            this.hideSuggestions();
            break;
    }

};

/**
 * Handles keyup events.
 * @scope private
 * @param oEvent The event object for the keyup event.
 */
AutoSuggestControl.prototype.handleKeyUp = function (oEvent /*:Event*/) {

	var iKeyCode = oEvent.keyCode;

    //for backspace (8) and delete (46), shows suggestions without typeahead
    if (iKeyCode == 8 || iKeyCode == 46) {
        this.provider.requestSuggestions(this, false, false);
        
    //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
        this.provider.requestSuggestions(this, true, false);
    }
};

/**
 * Hides the suggestion dropdown.
 * @scope private
 */
AutoSuggestControl.prototype.hideSuggestions = function () {
	
    this.layer.style.visibility = "hidden";
	document.getElementById("cacheframebody").style.visibility = 'hidden'
	document.getElementById("cacheframebody").style.display = "none"
	document.getElementById("cacheframebody").style.left=-1000
	
	//if what is in the box is valid
	for (var i=0; i < this.layer.firstChild.childNodes.length; i++) {
        if (this.layer.firstChild.childNodes[i].firstChild.nodeValue == this.textbox.value) {
            if(!LoadInProgress)
			{  
				LoadInProgress = true
				OnSelectionAction(this.layer.firstChild.childNodes[i].id) //Execute command
				
			}
        }
    }
	
	
};

/**
 * Highlights the given node in the suggestions dropdown.
 * @scope private
 * @param oSuggestionNode The node representing a suggestion in the dropdown.
 */
AutoSuggestControl.prototype.highlightSuggestion = function (oSuggestionNode) {
  
   for( var x = 0; x < oSuggestionNode.attributes.length; x++ ) {
		
		if( oSuggestionNode.attributes[x].nodeName.toLowerCase() == 'id' ) {
			
			if (oSuggestionNode.attributes[x].nodeValue || ""){
			
				var hotelOveredId = oSuggestionNode.attributes[x].nodeValue;			
				var isSearchText = hotelOveredId.indexOf('searchText');
		
				if (overedElement1 || "")
				{
					this.layer.firstChild.childNodes[overedElement1].className = '';
				}
				if (isSearchText == -1)
				{
					//if (document.getElementById("searchText" + overedElement1))
						//document.getElementById("searchText" + overedElement1).className = 'searchText';
					this.layer.firstChild.childNodes[hotelOveredId].className = 'current';
				}
				else
				{
					//if (overedElement2 || ""){
						//document.getElementById(overedElement2).className = 'searchText';
					//}
					//document.getElementById(hotelOveredId).className = 'searchTextOver';
					//overedElement2 = hotelOveredId;
					
					hotelOveredId = hotelOveredId.substring(10);
					this.layer.firstChild.childNodes[hotelOveredId].className = 'current';
				}
				overedElement1 = hotelOveredId;
			}
		}
	}
};

/**
 * 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);
    };
        
    //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 onfocus event handler (select suggestions)    
    this.textbox.onfocus = function () {
		if (document.getElementById(oThis.textbox.id + "SelectedValue")){
			selectedValueRef = document.getElementById(oThis.textbox.id + "SelectedValue");
			if (selectedValueRef.innerHTML == "False"){
				oThis.textbox.value = '';
			}
		}
        oThis.textbox.select();
    };
	
	
    //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.
 * @scope private
 */
AutoSuggestControl.prototype.nextSuggestion = function () {
    var cSuggestionNodes = this.layer.firstChild.childNodes;

    if (cSuggestionNodes.length > 0 && this.cur < cSuggestionNodes.length-1) {
        var oNode = cSuggestionNodes[++this.cur];
        this.highlightSuggestion(oNode);
        /*this.textbox.value = oNode.firstChild.nodeValue;*/
		this.textbox.value = eSuggestions[this.cur];
		/*this.selectTFWValue(this.cur);*/
		this.textbox.focus();
    }
};

/**
 * Highlights the previous suggestion in the dropdown and
 * places the suggestion into the textbox.
 * @scope private
 */
AutoSuggestControl.prototype.previousSuggestion = function () {
    var cSuggestionNodes = this.layer.firstChild.childNodes;

    if (cSuggestionNodes.length > 0 && this.cur > 0) {
        var oNode = cSuggestionNodes[--this.cur];
        this.highlightSuggestion(oNode);
		/*this.textbox.value = oNode.firstChild.nodeValue;*/
		this.textbox.value = eSuggestions[this.cur];
		/*this.selectTFWValue(this.cur);*/
    }
};

/**
 * 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();      
}; 

/**
 * Builds the suggestion layer contents, moves it into position,
 * and displays the layer.
 * @scope private
 * @param aSuggestions An array of suggestions for the control.
 */
AutoSuggestControl.prototype.showSuggestions = function (aSuggestions /*:2D Array*/) {
    this.layer.style.overflow = 'hidden';
    this.layer.style.height = 'auto';   
    var oDiv = null;
   
    //clean it all
    var cell = this.layer.firstChild;
	if ( cell.hasChildNodes() )
	{
	    while ( cell.childNodes.length >= 1 )
	    {
	        cell.removeChild( cell.firstChild );       
	    } 
	}
	

    //this.layer.firstChild.innerHTML = "";  //clear contents of the layer
    //this.layer.firstChild.RemoveAll();
     //alert(this.layer.firstChild.firstChild)
     
    if(document.getElementById("Tbl" + this.textbox.name))
    {
		ZoneElem = document.getElementById("Tbl" + this.textbox.name)
		WorkingWidth = ZoneElem.offsetWidth - 2
	}
    else 
    {
		if(document.getElementById("TblNoOff" + this.textbox.name))
		{
			ZoneElem = document.getElementById("TblNoOff" + this.textbox.name)
			WorkingWidth = ZoneElem.offsetWidth
		}
		else
		{
			ZoneElem = this.textbox
			WorkingWidth = ZoneElem.offsetWidth + 50			
		}
	}
    
    minusScrollOffSet = 0
    if (BrowserDetect.browser.indexOf("Explorer") != -1)
    {
		WorkingWidth += 2
		minusScrollOffSet = 2
	}
	
    this.layer.style.width = WorkingWidth
    
    if (aSuggestions.length > 10){
		this.layer.style.height = 150 + "px";
		minusScrollOffSet = 16
		if (BrowserDetect.browser.indexOf("Explorer") != -1)
			minusScrollOffSet = 18
	}else{
		//this.layer.style.height = (15 * aSuggestions.length) + 2
	}
	
    for (var i=0; i < aSuggestions.length; i++) {
        oDiv = document.createElement("div");
		oDiv.style.width = WorkingWidth - minusScrollOffSet;
		oDiv.style.height = 15 
		oDiv.id = i;
		oDiv.innerHTML +=aSuggestions[i][0];
        //oDiv.appendChild(document.createTextNode(aSuggestions[i][0]));
        this.layer.firstChild.appendChild(oDiv);
    }
    this.layer.style.overflow = 'auto';
    //leftX = this.getLeft()
    leftX = findPosX(ZoneElem)
	topY =  findPosY(ZoneElem) + (ZoneElem.offsetHeight - 1) //the -1 is for the border
    if (BrowserDetect.browser.indexOf("Firefox") == -1 && !IsInIframe && document.getElementById("Tbl" + this.textbox.name))
    {
		leftX += 4
		topY += 4
	}
	//if (BrowserDetect.browser.indexOf("Safari") != -1)
		//minusScrollOffSet = 16
	
	if(IsInIframe)
	{
		if(this.layer.offsetHeight + topY > document.getElementById("UlysseMiniMoteurZone").offsetHeight)	
		{
			
			topY = topY - this.layer.offsetHeight - ZoneElem.offsetHeight + 2
		}
	}
		
    this.layer.style.left = leftX + "px";
    this.layer.style.top = topY + "px";
    this.layer.style.visibility = "visible";
	//with cache section
	IfrRef = document.getElementById("cacheframebody")
	DivRef = this.layer
	IfrRef.style.width = DivRef.offsetWidth;
	IfrRef.style.height = parseInt(DivRef.offsetHeight);
	IfrRef.style.top = parseInt(DivRef.style.top);
	IfrRef.style.left = DivRef.style.left;
	IfrRef.style.zIndex = DivRef.style.zIndex - 1;
	IfrRef.style.display = "block";
	IfrRef.style.visibility = 'visible'
	
	overedElement1 = ""
	overedElement2 = ""

};

/**
 * 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; 
		
        this.textbox.value = sSuggestion; 

        this.selectRange(iLen, sSuggestion.length);
    }
};

/**
 * Select and TFWvalue 
 * @scope private
 * @param hotelid - The id of the selected tfw value.
 */
AutoSuggestControl.prototype.selectTFWValue = function (hotelid) {

	var hotId = completeSuggestions[hotelid][1];

	SelectAutoSuggestElem(hotId, this.textbox.id, completeSuggestions[hotelid][0], this.NewTFWType)
		
	//document.getElementById("SearchHotelLink").href = APPSWebServerURL + "Search/ulysse/default.asp?" + defaultParams + "&WHATID=100&TYPE=destination&TOLEVEL=" + hotToLevel + "&EXITID=" + hotDestCode + "&HOTELID=" + hotId + "&HOMEPAGEORIGIN=SEARCHBYHOTEL"

};

/**
 * Select and hotel and activate de "Go" Button.
 * @scope private
 * @param hotelid - The id of the selected hotel.
 */
AutoSuggestControl.prototype.selectHotelValue = function (hotelid) {

	var hotId = completeSuggestions[hotelid][1];
	var hotDestCode = completeSuggestions[hotelid][2];
	var hotToLevel = 3;
	var HotName = completeSuggestions[hotelid][0];
	var searchCode = hotDestCode.indexOf(1);
	if (searchCode == -1){
		// The code is not 1 but it could be 2
		searchCode = hotDestCode.indexOf(2);
		if (searchCode == -1){
			//The code is not 1 or 2 so we do nothing
		}else{
			//The code is 2
			hotToLevel = 2;
		}
	}else{
		// The code is 1
		hotToLevel = 1;
	}
	
	location.href = APPSWebServerURL + "web2/Search/ulysse/default.asp?" + defaultParams + "WHATID=270&TYPE=gamme&DESTINATIONID=1&CTEMPLATE=HOTEL&EXITID=" + hotDestCode + "&HOTELID=" + hotId + "&HOTELNAME=" + HotName + "&HOMEPAGEORIGIN=SEARCHBYHOTEL"

};