
(function ($) {

    var xhrResultList = [];

    var liston = 1;
    var HasPhotos = false;
    var HasUsers = false;

    // create username autocomplete dropdown
    // takes an array of usernames and creates a username automcompletion HTML element
    // only returns first numResults results

    var createResultAutocomplete = function (search_term, textarea, results, numResults) {
        var container = $('<div id="search_list" style="border: 1px solid #444; position: absolute; z-index: 9999;"></div>');

        var username_list = $('<ul style="position: relative;" id="user_search_list"></ul>');
        var photo_list = $('<ul style="position: relative;" id="photo_search_list"></ul>');
        var userheader = $('<div style="position: relative; width: 275px; margin: 0; background-color: #333; color: #fff; font-weight: bold; font-size: 11px; padding: 10px 0 10px 10px;">USERS</div>');
        var photoheader = $('<div style="position: relative; width: 275px; margin: 0; background-color: #333; color: #fff; font-weight: bold; font-size: 11px; padding: 10px 0 10px 10px;">PHOTOS - What do you think of...</div>');

        var userfooter = $('<div style="position: relative; width: 285px; margin: 0; background-color: #fff; font-weight: bold; font-size: 11px; padding: 10px 0 10px 0px; text-align: center;"><a href="SearchMembers.aspx?s=' + escape(search_term) + '">More User Results</a></div>');
        var photofooter = $('<div style="position: relative; width: 285px; margin: 0; background-color: #fff; font-weight: bold; font-size: 11px; padding: 10px 0 10px 0px; text-align: center;"><a href="SearchPhotos.aspx?s=' + escape(search_term) + '">More Photo Results</a></div>');

        container.css({
            top: textarea.offset().top + textarea.outerHeight() - 1,
            left: textarea.offset().left
        });

        //Get Users
        for (var i = 0; i < results.usernames.length; i++) {
            if (i === numResults) {
                break;
            }
            username_list.append($('<li gmr-link="/' + results.usernames[i].username + '?ref=qs"><a href="/' + results.usernames[i].username + '?ref=qs" class="searchresult"><div style="float: left;"><img src="' + results.usernames[i].photourl + '"></div><div style="float: left; padding: 8px 0 0 5px;"><b>' + results.usernames[i].username + '</b></div><div class="clr"></div></a></li>'));
        }


        //Get Photos
        for (var i = 0; i < results.photos.length; i++) {
            if (i === numResults) {
                break;
            }
            photo_list.append($('<li gmr-link="/Profile.aspx?ref=qs&pid=' + results.photos[i].photoid + '"><a href="/Profile.aspx?ref=qs&pid=' + results.photos[i].photoid + '" class="searchresult"><div style="float: left;"><img src="' + results.photos[i].photourl + '"></div><div style="float: left; padding: 8px 0 0 5px;"><b>' + results.photos[i].question2 + '</b></div><div class="clr"></div></a></li>'));
        }


        if (results.photos.length > 0) {
            HasPhotos = true;
            photo_list.find('li:first-child').addClass('active');
            container.append(photoheader).append(photo_list).append(photofooter);
        }
        else {
            HasPhotos = false;
            username_list.find('li:first-child').addClass('active');
        }

        if (results.usernames.length > 0) {
            HasUsers = true;
            container.append(userheader).append(username_list).append(userfooter);
        }
        else {
            HasUsers = false;
        }

        return container;
    };

    // remove autocomplete dropdown from container

    var removeResultAutocomplete = function () {
        $('#search_list').remove();
        //container.find('textarea').removeClass('autocomplete_active').removeData('ac_start').scrollTop(9999); // scrollTop to fix Firefox bug
        return true;
    };

    // the main bit
    $.fn.gmrSearch = function (userSettings) {
        // settings
        var textarea = $(this);

        var settings = {
            usernameSelector: '.username',
            numResults: 5,
            xhrUsernames: null,
            xhrOnFocus: true
        };

        if (userSettings !== undefined) {
            jQuery.extend(settings, userSettings);
        }

        // load in XHR usernames if not already done

        var loaded = false;
        var otherkey = false;

        this.keydown(function (e) {
            var textarea = $(this);
            var username_list;
            var ddl;

            otherkey = false;

            if (e.which === 16) { // shift
                return;

            } else if (e.which === 38 || e.which === 40 || e.which === 13 || e.which === 32) { // up, down, enter, space
                if (liston == 1 && HasPhotos == true)
                    ddl = $('#photo_search_list');
                else
                    ddl = $('#user_search_list');

                if (ddl.length === 0) {
                    return;
                }

                var active;

                switch (e.which) {
                    case 38: // up
                        var switchresult = false;

                        active = ddl.find('li.active');
                        if (active.length > 0) {
                            var next = active.removeClass('active').prev().addClass('active');

                            if (next.html() == null) {
                                switchresult = true;
                            }
                        }
                        else
                            switchresult = true;

                        if (switchresult) {
                            if (liston == 2 && $('#photo_search_list').length > 0) {
                                liston = 1;
                                ddl = $('#photo_search_list');
                            }
                            else if ($('#user_search_list').length > 0) {
                                liston = 2;
                                ddl = $('#user_search_list');
                            }
                            ddl.find('li:last-child').addClass('active');
                        }
                        return false;

                    case 40: // down
                        var switchresult = false;

                        active = ddl.find('li.active');
                        if (active.length > 0) {
                            var next = active.removeClass('active').next().addClass('active');

                            if (next.html() == null) {
                                switchresult = true;
                            }
                        }
                        else
                            switchresult = true;

                        if (switchresult) {
                            if (liston == 2 && $('#photo_search_list').length > 0) {
                                liston = 1;
                                ddl = $('#photo_search_list');
                            }
                            else if ($('#user_search_list').length > 0) {
                                liston = 2;
                                ddl = $('#user_search_list');
                            }
                            ddl.find('li:first-child').addClass('active');
                        }
                        return false;

                    case 13: // enter
                        active = ddl.find('li.active');

                        if (active.length > 0) {
                            location.href = active.attr('gmr-link');
                            return false;

                            //textarea.val(textarea.val().substring(0, textarea.data('ac_start') + 1) + active.text() + ' ');
                        }
                        removeResultAutocomplete();
                        return false;
                    case 32: // space
                }

            } else if (e.which === 27) { // ESC
                removeResultAutocomplete();

            } else {
                otherkey = true;
            }

        });




        $(this).bind('paste', function () {
            typing();
        });

        this.keyup(function () {
            if (otherkey)
                typing();
        });

        function typing() {
            var username_list;
            var ddl;

            if (!textarea.hasClass('autocomplete_active')) {
                textarea.addClass('autocomplete_active');
            }


            if (textarea.val() == "") {
                removeResultAutocomplete();
            }

            var search_term = textarea.val();

            search_term = search_term.toLowerCase();

            if (xhrResultList[search_term] != null) {
                username_list = createResultAutocomplete(search_term, textarea, xhrResultList[search_term], settings.numResults);

                ddl = $('#search_list');

                if (ddl.length > 0) {
                    ddl.replaceWith(username_list);
                } else {
                    $('body').append(username_list);
                }
            }
            else {
                $.get(settings.xhrUsernames + escape(search_term), function (data) {
                    var obj = jQuery.parseJSON(data);
                    xhrResultList[search_term] = obj;

                    if (obj.usernames) {
                        username_list = createResultAutocomplete(search_term, textarea, xhrResultList[search_term], settings.numResults);

                        ddl = $('#search_list');

                        if (ddl.length > 0) {
                            ddl.replaceWith(username_list);
                        } else {
                            $('body').append(username_list);
                        }

                    }
                });
            }


        }
    };

})(jQuery);
