//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else if(window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        alert("Your Browser Sucks!\nIt's about time to upgrade don't you think?");
    }
}

//Our XmlHttpRequest object to get the auto suggest
var searchReq = getXmlHttpRequestObject();
var cssAutoCompleteDiv = 'search_suggest';
initSuggest();

function keypressHandler()
{
    
}

function initSuggest()
{
    var queryField = document.getElementById('txtSearch');
    //queryField.onKeyDown = keypressHandler();
    queryField.onKeyUp = searchSuggest();
    queryField.focus();
}

    
//Called from keyup on the search textbox.
//Starts the AJAX request.
function searchSuggest() {
    if (searchReq.readyState == 4 || searchReq.readyState == 0) {
        var str = escape(document.getElementById('txtSearch').value);
        searchReq.open("GET", 'searchSuggest.html?query=' + str, true);
        searchReq.onreadystatechange = handleSearchSuggest; 
        searchReq.send(null);
    }        
}

//Called when the AJAX response is returned.
function handleSearchSuggest() {
    if (searchReq.readyState == 4) {
        var ss = document.getElementById('search_suggest')
        ss.innerHTML = '';
        var str = searchReq.responseText.split("\n");
        for(i=0; i < str.length - 1; i++) {
            //Build our element string.  This is cleaner using the DOM, but
            //IE doesn't support dynamically added attributes.
            var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
            suggest += 'onmouseout="javascript:suggestOut(this);" ';
            suggest += 'onclick="javascript:setSearch(this.innerHTML);" ';
            suggest += 'class="suggest_link">' + str[i] + '</div>';
            ss.innerHTML += suggest;
        }
    }
}

//Mouse over function
function suggestOver(div_value) {
    div_value.className = 'suggest_link_over';
}
//Mouse out function
function suggestOut(div_value) {
    div_value.className = 'suggest_link';
}
//Click function
function setSearch(value) {
    document.getElementById('txtSearch').value = value;
    document.getElementById('search_suggest').innerHTML = '';
}
