var actb;
var timerId;
var isBusy;
// Client side cache to avoid repeat lookups
var cache = new Object();
var mouseOverItem;
var autoCompleteActive = false;
var oldValue = "";

$(document).ready(function(){
    actb = new AutoCompleteTextBox("#txtSearch", "#suggest", "#suggestout");
    
    if ($('#txtSearch').val() == '')
        $('#txtSearch').val(com.laterooms.microsites.townpostcodeattraction);
	
	$('#main').bind('submit', function(e) {
	    actb.HideSuggestions();
        window.clearTimeout(timerId);
        return true; 
	});
});

function AutoCompleteTextBox(TextBoxId, DivId, DivIdOut) {
	// initialize member variables
	var oThis = this;
	var oText = $(TextBoxId);
	var oDiv = $(DivId);
	var oDivOut = $(DivIdOut);
	this.TextBox = oText;
	this.Div = oDiv;

    // Set left and top coords
    var pos = oText.position();
    oDivOut.css('left', pos.left + 'px').css('top', pos.top + 'px');
    
	// attach handlers to the TextBox
	oText.AutoCompleteTextBox = this;
	
//	// Use onkeypress for autorepeat up/down -Use onkeydown NOT onkeypress as ie does not prcoess tab button in onkeypress
	oText.keydown(function(oEvent) {
	    if ( !oEvent) {
		    oEvent = window.event;
	    }
	    var iKeyCode = oEvent.keyCode;
	    if (iKeyCode == 13) {
		    if (oDiv.css('display') =='block') {
			    return false;
		    }
		    else {
		        $("#search").click();
                this.cancelBubble = true;
                return false;
		    }
	    }
	    if (iKeyCode == 9) {
	        if (mouseOverItem != null) {
	            $(mouseOverItem).mousedown();
	        }
	        actb.HideSuggestions();
	        autoCompleteActive = false;
	    }
    });
	
	oText.keyup(AutoCompleteTextBox.prototype.OnKeyUp);
	
	oText.focus(function() {
	    autoCompleteActive = true;
	     ClearDefaultSearchText();
        if(oDiv.children().length > 0 && oText.val() != "") {
	        oDiv.css('display', 'block');
            if($.browser.msie) {
                $('#find select').css('visibility','hidden');
                $('#mini select').css('visibility','hidden');
                $('#searchbox select').css('visibility','hidden');
                $('#searchresults').css('z-index', '-1');
            }

        }
       
    });
    
    oText.blur(function() {
        ResetDefaultSearchText();
        actb.HideSuggestions();
        autoCompleteActive = false;
    });
}

AutoCompleteTextBox.prototype.HideSuggestions = function() {
	this.Div.css('display','none');
	if($.browser.msie) {
	    $('#find select').css('visibility','visible');
	    $('#mini select').css('visibility','visible');
	    $('#searchbox select').css('visibility','visible');
	    $('#searchresults').css('z-index', '1');
	}
}

AutoCompleteTextBox.prototype.OnKeyUp = function(oEvent) {
    
    $('#idSearch').val('');
    
    if ( ! oEvent) {
	    oEvent = window.event;
    }
	
    var iKeyCode = oEvent.keyCode;
    
    if (iKeyCode == 13 && mouseOverItem != null)
        $(mouseOverItem).mousedown();
    if (iKeyCode == 13 || iKeyCode == 27) {
        // Enter or Esc Pressed
	    actb.HideSuggestions();
	    return false;
    }
    if (iKeyCode == 8 || iKeyCode == 46) {
    }
    else if (iKeyCode == 40) { // Down
	    divs = actb.Div.children('div');
	    if(mouseOverItem != null)
	    {index = mouseOverItem.data('index') + 1;}
	    else{index=0;}
	    if (index == divs.length)
		    index = 0;
	    $(divs[index]).mousemove();
	    return;
    } else if (iKeyCode == 38) { // Up
	    divs = actb.Div.children('div');
	    if(mouseOverItem != null)
	    {index = mouseOverItem.data('index') - 1;}
	    else{index=divs.length -1;}
	    if (index < 0)
		    index = divs.length - 1;
	    $(divs[index]).mousemove();
	    return;
    } else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode <= 46)) {
	    return;
    }
    actb.HideSuggestions();
	
    var txt = actb.TextBox.val().toLowerCase();
	
    if (txt.length > 0 && txt != oldValue) {
	    if ( !cache[txt]) {
		    // clear any previous timer to avoid doing multiple lookups for fast typists
		    window.clearTimeout(timerId);
		    timerId = window.setTimeout("DoCallBack();", 500);
	    } else {
		    actb.CreateList(cache[txt]);
	    }
    } else {
	    actb.HideSuggestions();
    }
}

function DoCallBack() {
	var txt = actb.TextBox.val().toLowerCase();
	if (oldValue != txt) {
         $.ajax({
	        type: 'POST',
	        contentType: 'application/json; charset=utf-8',
	        url: '/' + basePath + 'Models/Services/Service.asmx/SearchAutocomplete',
	        data: '{searchTerm: "' + txt + '"}',
	        dataType: 'json',
	        success: searchResponse
	    });
        oldValue = txt;
	}
}

function searchResponse(response) {
    var res = response.d;
	cache[res.SearchTerm.toLowerCase()] = res;
	actb.CreateList(res);
}

function ClearDefaultSearchText()
{
    if (actb.TextBox.val() == com.laterooms.microsites.townpostcodeattraction)
    {
        actb.TextBox.val('');
    }
}

AutoCompleteTextBox.prototype.CreateList = function(res) {
    if (autoCompleteActive == true) {
        
        this.Div.empty(); // Delete all children
	
	    // get all the matching strings from the server response
	    // add each string to the popup-div
	    var i,
	    n = res.Results.length;
	
	    if (n > 0) {
		    for (i = 0; i < n; i ++ ) {
			    var odiv = $(document.createElement('div')).data('index',i).data('data',res.Results[i]);
			    
			    try {
				    odiv.html('<span>' + res.Results[i].Text + '</span>');
				    // Hotel count is deactivated until we can make it more accurate for the MicroSites
				    // odiv.html('<b>' + res.Results[i].Count + ' ' + (res.Results[i].Count != 1 ? com.laterooms.microsites.hotels : com.laterooms.microsites.hotel) + '</b><span>' + res.Results[i].Text + '</span>');
			    }
			    catch(e) {
				    alert(e);
				    return;
			    }
			    this.Div.append(odiv);
			    odiv.autocompletetextbox = this;
			    odiv.mousemove(function() {
			        //if (!jQuery.browser.msie && jQuery.browser.version != '6.0') {
			            $(mouseOverItem).removeClass();
			            $(this).addClass('hover');
			        //}
			        mouseOverItem = $(this);
			    });
			    odiv.mousedown(function() {
			        $('#txtSearch').val($(this).data('data').Text);
			        $('#idSearch').val($(this).data('data').Url);
			    });
			    if (i == n-1) {
				   mouseOverItem = null;
			    }
		    }
		    
            this.Div.css('display', 'block');
            if($.browser.msie) {
                $('#find select').css('visibility','hidden');
                $('#mini select').css('visibility','hidden');
                $('#searchbox select').css('visibility','hidden');
                $('#searchresults').css('z-index', '-1');
            }
            
	    } else {
		    actb.hidesuggestions();
	    }
	} else {
		actb.HideSuggestions();
	}
}

function ResetDefaultSearchText()
{
    if (actb.TextBox.val()=='')
    {
        actb.TextBox.val(com.laterooms.microsites.townpostcodeattraction);
    }
}