/***************************************************************************
 * Input Suggestions plug-in
 * 
 * Author: Rob Schellhorn
 **************************************************************************/
(function($) {

    var keyup = 38, keydown= 40, enter = 13;

    $.fn.suggestions = function(options) {

        var options = $.extend({
            autoSubmit: true,
            minimumInput: 2
        }, options);

        this.each(function() {
            var input = this;
            var suggestions = null;
            var currentSelection = null;
            var segments = new Array();

            function positionSuggestions(suggestions) {
                var p = $(input).position();
                suggestions.css('left', p.left + 'px').css('top', p.top + $(input).outerHeight() + 'px').css('z-index', '999');
            }

            function setSelection(selection) {
                if (selection.length > 0) {
                    if (currentSelection) currentSelection.removeClass('active');
                    selection.addClass('active');
                    $(input).val(segments.length > 0 ? segments.join(',') + ',' + selection.text() : selection.text());
                    currentSelection = selection;
                } else if (suggestions) {
                    suggestions.remove();
                }
            }

            /**
             * 
             */
            $(input).keyup(function(event) {
                if (event.keyCode == enter) {
                    if (suggestions) suggestions.remove();
                } else if (event.keyCode == keyup || event.keyCode == keydown) {
                    var newSelection;
                    if (!currentSelection) {
                        newSelection = $('li:first', suggestions);
                    } else if (event.keyCode == keyup) {
                        newSelection = currentSelection.prev();
                    } else {
                        newSelection = currentSelection.next();
                    }

                    setSelection(newSelection);
                } else {
                    if (suggestions) suggestions.remove();
                    currentSelection = null;

                    var query = $(input).val();
                    if (!query) query = '';

                    segments = query.split(',');
                    var lastSegment = $.trim(segments.pop());
                    if ($.trim(lastSegment).length < options.minimumInput) return;

                    $.getJSON('/api/suggest', {'query': query}, function(data) {
                        if (data.length < 1) return;

                        if (suggestions) suggestions.remove();
                        suggestions = $('<ol>').addClass('plain suggestions');
                        positionSuggestions(suggestions);
                        $.each(data, function(index, value) {
                            var text = value.replace(lastSegment, '<strong>' + lastSegment + '</strong>');
                            $('<li>').append($('<a>').html(text).click(function(event) { event.preventDefault();
                                setSelection($(this));
                                if (options.autoSubmit) $(input).parents('form').submit();
                                else suggestions.remove();
                            })).mouseenter(function() {
                                $(input).focus();
                            }).appendTo(suggestions);
                        });
                        suggestions.appendTo($(input).parent());
                    });
                }
            });

        });
    }

})(jQuery);
