﻿if (!window.SAS) {
    window.SAS = {};

    window.SAS.Settings = {
        service: '/ws/GetSearchSuggestion.ashx',
        maxResults: 10,
        maxElipses: 35,
        searchDelay: 250,
        searchTimeOut: -1,
        blurTimeOut: -1,
        blurDelay: 150,
        keysIn: 3,
        keyWord: '',
        source: [],
        suggestions: [],
        search: null,
        button: null,
        autoComplete: null,
        ajaxRequest: null,
        selectedIndex: -1
    };
    
    window.SAS.GetElementByPartialId = function(tag, id) {
        var items = document.getElementsByTagName(tag);
        
        for (var i = 0; i < items.length; i++)
        {
            if(items[i].id != 'underfined' && items[i].id.indexOf(id) != -1)
                return items[i];
        }
        
        return null;
    };

    window.SAS.HideList = function() {
        window.SAS.Settings.source = [];
        window.SAS.Settings.suggestions = [];
        window.SAS.Settings.autoComplete.innerHTML = '';
        window.SAS.Settings.autoComplete.style.display = 'none';
    };

    window.SAS.ExecuteClick = function(index) {
        clearTimeout(window.SAS.Settings.blurTimeOut);
        
        if (window.SAS.Settings.suggestions.length <= index)
            return;

        var value = window.SAS.Settings.suggestions[index].term;

        window.SAS.Settings.search.val(value);
        window.SAS.Settings.button.click();
    };

    window.SAS.RenderList = function() {
        if (window.SAS.Settings.suggestions.length > 0) {
            var s = '';

            for (var i = 0; i < window.SAS.Settings.suggestions.length; i++) {
                var item = window.SAS.Settings.suggestions[i];
                var text = item.term.length > window.SAS.Settings.maxElipses ? item.term.substring(0, window.SAS.Settings.maxElipses - 3) + '...' : item.term;
                var className = window.SAS.Settings.selectedIndex == i ? 'class="highlight"' : '';

                s += '<a ' + className + ' href="/search.aspx?s=' + item.term + '" onclick="window.SAS.ExecuteClick(' + i + ');"><span class="term">' + text + '</span></a>'; //<span class="count">' + item.latestYield + '</span></a>';
            }

            window.SAS.Settings.autoComplete.innerHTML = s;
            window.SAS.Settings.autoComplete.style.display = '';
        } else {
            window.SAS.HideList();
        }
    };

    window.SAS.KeyUp = function(e) {
        clearTimeout(window.SAS.searchTimeOut);

        window.SAS.searchTimeOut = setTimeout(function() {
            var keyWord = $.trim(window.SAS.Settings.search.val());
            var forward = (window.SAS.Settings.keyWord.length < keyWord.length);

            window.SAS.Settings.keyWord = keyWord;

            if (forward)
                window.SAS.Settings.selectedIndex = -1;
            
            if (window.SAS.Settings.keyWord.length >= window.SAS.Settings.keysIn || (!forward && window.SAS.Settings.keyWord.length > 0)) {
                if ((window.SAS.Settings.suggestions.length == 0 && forward) || !forward) {
                    window.SAS.RequestSuggestions();
                } else {
                    window.SAS.FilterSuggestions();
                    window.SAS.RenderList();
                }
            } else if (window.SAS.Settings.keyWord.length > 0) {
                window.SAS.FilterSuggestions();
                window.SAS.RenderList();
            } else {
                window.SAS.HideList();
            }

        }, window.SAS.Settings.searchDelay);
    };

    window.SAS.FilterSuggestions = function() {
        var list = [];
        var count = 0;

        for (var i = 0; i < window.SAS.Settings.source.length; i++) {
            var item = window.SAS.Settings.source[i];

            var value = window.SAS.Settings.keyWord;
            var result = item.term;
            var first = result.toLowerCase().indexOf(value.toLowerCase());
            var second = value.length;
            var captured = result.substring(first, first + second);

            if (value == '' || result.toLowerCase().indexOf(value.toLowerCase()) != -1) {
                if (captured != '')
                    list.push(item);
            }

            if (list.length >= window.SAS.Settings.maxResults)
                break;
        }
        
        window.SAS.Settings.suggestions = list;
    }

    window.SAS.RequestSuggestions = function() {
        if (window.SAS.Settings.ajaxRequest != null)
            window.SAS.Settings.ajaxRequest.abort();

        var o = {
            type: 'POST',
            url: window.SAS.Settings.service,
            data: { 'keyWord': window.SAS.Settings.keyWord },
            async: true,
            cache: false,
            error: function(msg) {
                window.SAS.HideList();
            },
            success: function(msg) {
                try {
                    var list = eval('new Object(' + msg + ' );');

                    window.SAS.Settings.source = list;
                    window.SAS.Settings.suggestions = list;
                    window.SAS.FilterSuggestions();
                    window.SAS.RenderList();
                } catch (e) {
                    window.SAS.HideList();
                }
            }
        };

        window.SAS.Settings.ajaxRequest = $.ajax(o);
    }

    window.SAS.KeyDown = function(e) {
        if (window.SAS.Settings.suggestions == 0)
            return;

        switch (e.keyCode) {
            case 13: // enter
                if (window.SAS.Settings.selectedIndex == -1)
                    return;

                e.preventDefault();

                var value = window.SAS.Settings.suggestions[window.SAS.Settings.selectedIndex].term;

                window.SAS.Settings.search.val(value);
                window.SAS.Settings.button.click();

                break;
            case 40: // up
                if (window.SAS.Settings.selectedIndex + 1 < window.SAS.Settings.suggestions.length)
                    window.SAS.Settings.selectedIndex = window.SAS.Settings.selectedIndex + 1;
                else
                    window.SAS.Settings.selectedIndex = 0;

                window.SAS.RenderList();

                break;
            case 38: // down
                if (window.SAS.Settings.selectedIndex - 1 < 0)
                    window.SAS.Settings.selectedIndex = window.SAS.Settings.suggestions.length - 1;
                else
                    window.SAS.Settings.selectedIndex = window.SAS.Settings.selectedIndex - 1;

                window.SAS.RenderList();

                break;
            case 27: // esc
                window.SAS.Settings.search.val('');
                
                
                break;
        }
    }

    window.SAS.Blur = function(e) {
        clearTimeout(window.SAS.Settings.blurTimeOut);

        window.SAS.Settings.blurTimeOut = setTimeout(function() {
            window.SAS.Settings.autoComplete.innerHTML = '';
            window.SAS.Settings.autoComplete.style.display = 'none';
        }, window.SAS.Settings.blurDelay);
    }

    window.SAS.Focus = function(e) {
        window.SAS.KeyUp(e);
    }

    window.SAS.Init = function() {
        var d = document.createElement('div');

        d.id = '_SAS';
        d.className = 'searchautosuggest';
        d.style.display = 'none';

        window.SAS.Settings.search = $(window.SAS.GetElementByPartialId('input', 'searchString'));
        window.SAS.Settings.search.before(d);
        window.SAS.Settings.autoComplete = d;
        window.SAS.Settings.button = $(window.SAS.GetElementByPartialId('input', 'runSearch'));

        $(window.SAS.Settings.search).bind("keyup", window.SAS.KeyUp);
        $(window.SAS.Settings.search).bind("keydown", window.SAS.KeyDown);
        $(window.SAS.Settings.search).bind("blur", window.SAS.Blur);
        $(window.SAS.Settings.search).bind("focus", window.SAS.Focus);
    };

    $(document).ready(function() {
        window.SAS.Init(); 
    });
}
