﻿
$j(document).ready(function() {

    //Public array which will be filled with data on page load
    var lstSrcTxt;

    //Get data, fill into array
    $j.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json", url: "/SearchService.asmx/SearchByIDCL",
        //data: "{}",        
        data: "{'IDCL':'" + targetIDCL + "'}",
        success: function(res) {
            //Fill the array with the recieved data
            lstSrcTxt = res.d;
            //To ensure that no text will be entered, we disable
            //the textbox until we recieved the data
            $j("#" + ricercaTxt).removeAttr("disabled");
        }
    })

    //on every keypress, the list will be filtered
    $j("#" + ricercaTxt).keyup(function() {

    if ($j("#" + ricercaTxt).val() != "") {

            var SearchString = $j("#" + ricercaTxt).val();

            //Clear the results, otherwise there will be duplicates
            $j("#" + result).empty();
            //Select all Employess which's PreName starts with the SearchString
            //Note that using the useCase() command, the casing will be considered

            var lstFilteredSrcTxt = new Array; //jLinq.from(lstSrcTxt).startsWith("txt", SearchString).orderBy("txt").select();
            var found = 0;
            for (var i = 0; (i < lstSrcTxt.length && found < 10); i++) {
                var CurrentSearchItem = lstSrcTxt[i];
                if (CurrentSearchItem.txt.indexOf(SearchString) == 0) {
                    lstFilteredSrcTxt[found] = CurrentSearchItem;
                    found++;
                }
            }


            for (var i = 0; i < lstFilteredSrcTxt.length; i++) {
                var CurrentSearchItem = lstFilteredSrcTxt[i];
                var HightlightedText = CurrentSearchItem.txt.replace(SearchString, "<span class='match'>" + SearchString + "</span>");
                var HtmlElement = $j("<div class='searchresult'>" + HightlightedText + "</div>");
                $j("#" + result).append(HtmlElement);
            }
            $j(".searchresult").each(function(i) {
                $j(this).click(function() {
                    //On click of a result div, the fullname will be written into the seachfield
                    $j("#" + ricercaTxt).val(lstFilteredSrcTxt[i].txt);
                    $j("#" + ricercaBtn).click();
                    //Hide autocomplete suggestions
                    $j("#" + result).hide();
                });
            });
            $j("#" + result).show();
        }
        else {
            $j("#" + result).hide(); 
        }
    });
});
