// http://www.pengoworks.com/workshop/jquery/autocomplete.htm
// http://www.pengoworks.com/workshop/jquery/autocomplete_docs.txt
// http://www.pengoworks.com/workshop/jquery/autocomplete_ajax.cfm?q=c
// http://code.google.com/p/jquery-autocomplete/

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

function findValue(li)
{
    var keyword = document.getElementById("tbSearch").value.trim();
    //alert("keyword = " + keyword);
    
    if (keyword == "")
    {
        document.getElementById("spnErrorMessage").innerHTML = "Please enter a keyword.";
        //alert("Please enter a keyword.");
        return false;
    }
    else
    {
        // validation - start
        var noSpecChar = /^[a-zA-Z0-9\s\&\.\-\(\)\,]+$/.test(keyword)
        //var noSpecChar = /^[a-zA-Z0-9\s]+$/.test(keyword)
        //alert(noSpecChar);
        
        if (!noSpecChar)
        {
            document.getElementById("spnErrorMessage").innerHTML = "Special characters are not allowed.";
            //alert("Special characters are not allowed.");
            return false;
        }
        
        var atLeast2Char = /[^\s]{2,100}/.test(keyword)
        //alert(atLeast2Char);
        
        if (!atLeast2Char)
        {
            document.getElementById("spnErrorMessage").innerHTML = "Please enter at least 2 characters.";
            //alert("Please enter at least 2 characters.");
            return false;
        }
        // validation - end
        
        //alert(li);
        if(li == null) // cannot find in DB
        {
            window.location = "/company-search-results.aspx?keyword=" + escape(keyword.trim());
            //return alert("No match!");
            return;
        }

        if( !!li.extra ) // if coming from an AJAX call, let's use the CityId as the value
            var sValue = li.extra[0];
        else // otherwise, let's just display the value in the text box
            var sValue = li.selectValue;

        //alert("The value you selected was: " + sValue);
        window.location = "/company-search-results.aspx?keyword=" + escape(keyword.trim());
    }
}

function selectItem(li)
{
    findValue(li);
}

function formatItem(row)
{
    //return row[0] + " (id: " + row[1] + ")";
    return row[0];
}

function lookupAjax()
{
    var oSuggest = $("#tbSearch")[0].autocompleter;

    oSuggest.findValue();

    return false;
}

$(document).ready(function() {
    $("#tbSearch").autocomplete(
        "/services/autocomplete_ajax.ashx",
        {
            delay:10,
            minChars:2,
            matchSubset:1,
            matchContains:1,
            cacheLength:100,
            onItemSelect:selectItem,
            onFindValue:findValue,
            formatItem:formatItem,
            autoFill:false
        }
    );
});
