﻿//var suggestionTimer;
//var mainObject;

//function showSuggestions(obj)
//{
//    mainObject = obj;
//    clearTimeout(suggestionTimer);      
//    if (mainObject.value.length >=3)
//        { 
//            $(".ssSuggestions").show();
//            $(".ssWait").show();
//            suggestionTimer = setTimeout("triggerSmartSearch();", 500);
//            
//        }
//    else 
//        {
//            $(".ssSuggestions").html('');
//            $(".ssSuggestions").hide();
//        }        
//}


//	
//function triggerSmartSearch()
//{
//    var searchString = $("#zoeken").val();

//    $.ajax(
//        {
//            type    : "POST",
//            url     : "smartSearch.aspx",
//            data    : {"searchString":searchString},
//            timeout : 5000,
//            success : function(result) { $(".ssSuggestions").html(result);$(".ssWait").hide();},
//            error   : function(xhr, status, exception) {
//                alert(status + ' ' + exception );
//            }
//        });
//}
//	
//$(function(){
//    $("#zoeken").keyup(function(event){
//        $("#zoeken").data("userTyped", $("#zoeken").val());
//        showSuggestions(document.getElementById("zoeken"));
//    });
//});


var suggestionTimer;
var mainObject;
var resultdivname = "#ssSuggestions"
var zoekveldname = "#zoeken"

$(function() {
    // Hook click on 
    $(zoekveldname).keypress(ShowSuggestions).focus(ShowSuggestions);
    $(resultdivname).hide();

    // Sluiten
    $("body").click(checkClose);
});

function checkClose(e) {
    if ($(e.target).closest(resultdivname).length == 0 && !$(e.target).is(zoekveldname)) {
        $(resultdivname).fadeOut();
        $(zoekveldname).removeClass("loading");
    }
}
//Checks the right charactercount and then calls the searchaction
function ShowSuggestions() {
    mainObject = $(zoekveldname);
    clearTimeout(suggestionTimer);
    if (mainObject.val().length >= 3) {
        $(zoekveldname).addClass("loading");
        suggestionTimer = setTimeout("TriggerSearch();", 500);
    }
    else {
        $(zoekveldname).removeClass("loading");
        $(resultdivname).fadeOut();
    }
}

//Calls the ajax handler
function TriggerSearch() {
    //$(".ssWait").show();  

    $.ajax({
        type: "POST",
        url: "/smartsearch.aspx/GetResults",
        data: "{'searchterm': '" + $(zoekveldname).val() + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            $(resultdivname).html(response.d).fadeIn();
            $(zoekveldname).removeClass("loading");
        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert("Error status: " + xhr.status + " - " + xhr.statusText);
            alert(thrownError);
        }
    });
}
