﻿function PlayerQuickSearch()
{
    this.eContainer = null;
    this.iTest = 1;
    this.cCurrentSearchChar = "";
    this.xmlPlayerList = null;
    this.iSelectedItem = null;
    this.eSearchContainer;
    this.eText;
    this.bIsSearchContainerVisible = false;
    this.bIsSearchActivated = false;

    // holder for this
    var root = this;
    
    // create the search container
    $("body").append("<div id=\"PlayerQuickSearchContainer\"></div>");

    // set variables
    this.eSearchContainer = $("#PlayerQuickSearchContainer");

    // add click event to textbox in order to cancel bubbling
    this.eText = $("#txtPlayerQuickSearch");

    // add click event to textbox in order to cancel bubbling
    this.eText.click
    (
        function(event)
        {
            event.stopPropagation();
        }
    )

    $("#conBrandPlayerQuickSearch").click
    (
        function(event)
        {
            event.stopPropagation();
        }
    )   
    
    // kill click bubbling
    this.eSearchContainer.click
    (
        function(event)
        {
            event.stopPropagation();
        }
    )

    // handle global click to hide result list
    $("body").click
    (
        function(event)
        {
            if (root.eSearchContainer.css("visibility") == "visible")
            {
                root.eSearchContainer.css("visibility", "hidden");
            }
            else
            {
                if (root.bIsSearchActivated)
                {
                    root.deactivate();
                }
            }
        }
    )
    
    // hide the result container
    this.eSearchContainer.css("visibility", "hidden");
    
    // position the result container
    this.positionSearchContainer();

    // set properties and events on the textbox
    this.eText.attr("autocomplete", "off").keyup
    (
        function(event)
        {
            if (event.keyCode > 40 || event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 0)
            {
                // if the first char does not match the stored first char and the value is not empty
                // go get the new result set
                if (root.eText.val().substring(0, 1).toLowerCase() != root.cCurrentSearchChar && root.eText.val() != "")
                {
                    // reset the xml obj
                    root.xmlPlayerList = null;

                    // set the search character
                    root.cCurrentSearchChar = root.eText.val().substring(0, 1).toLowerCase();

                    // get the data set for that character
                    $.ajax
                    (
                        {
                            url: "/PlayerQuickSearch/PlayerQuickSearchXml.aspx",
                            data: { "S": root.cCurrentSearchChar },
                            dataType: "xml",
                            type: "GET",
                            success: function(data)
                            {
                                root.xmlPlayerList = data;
                                root.findResults();
                            }
                        }
                    )
                }
                // else handle all other key ups
                else
                {
                    // if there is a result set, proceed
                    if (root.xmlPlayerList != null)
                    {
                        root.findResults();
                    }
                }
            }
            // up arrow
            else if (event.keyCode == 38)
            {
                event.preventDefault();
                root.handleArrow("previousItem");
            }
            // down arrow
            else if (event.keyCode == 40)
            {
                event.preventDefault();
                root.handleArrow("nextItem");
            }
            // left arrow
            else if (event.keyCode == 37)
            {
                //event.preventDefault();
                //handleArrow("nextColumn");
                // check to see if there are results
            }
            // right arrow
            else if (event.keyCode == 39)
            {
                //event.preventDefault();
                //handleArrow("previousColumn");
                // check to see if there are results
            }
        }
    ).keypress
    (
        function(event)
        {
            // handle enter... has to be done in a KEYPRESS
            if (event.keyCode == 13)
            {
                event.preventDefault();

                if (root.iSelectedItem == null)
                {
                    //var aSearchResults = $("div[id^='PlayerQuickSearchPlayerContainer_']", this.eSearchContainer);
                    var aSearchResults = $("div.PlayerQuickSearchPlayerContainer", this.eSearchContainer);
                    
                    if (aSearchResults.length == 1)
                    {
                        root.gotoPlayer($("input:hidden", $(aSearchResults[0])).val());
                    }
                    else
                    {
                        //alert("go to player search and search for " + root.eText.val());
                    }
                }
                else
                {
                    var eItem = $("div.PlayerQuickSearchPlayerContainer", root.eSearchContainer).eq(root.iSelectedItem - 1);
                    root.gotoPlayer($("input:hidden", eItem).val());
                }
            }
        }
    )   
}

PlayerQuickSearch.prototype.positionSearchContainer = function()
{
    var aTxtOffset = this.eText.offset();
    this.eSearchContainer.css("top", aTxtOffset.top + this.eText.outerHeight());
    this.eSearchContainer.css("left", aTxtOffset.left + (this.eText.outerWidth() - this.eSearchContainer.outerWidth()));
}

PlayerQuickSearch.prototype.handleArrow = function(sAction)
{
    var aResults = $("div.PlayerQuickSearchPlayerContainer", this.eSearchContainer);

    if (aResults.length > 0)
    {
        if (this.iSelectedItem != null)
        {
            // handle next
            if (sAction == "nextItem")
            {
                if ((this.iSelectedItem + 1) <= aResults.length)
                {
                    ++this.iSelectedItem;
                }
                else
                {
                    this.iSelectedItem = 1;
                }
            }
            // handle backwords
            else if (sAction == "previousItem")
            {
                if (this.iSelectedItem > 1)
                {
                    this.iSelectedItem--;
                }
                else
                {
                    this.iSelectedItem = aResults.length;
                }
            }
        }
        else
        {
            this.iSelectedItem = 1;
        }
        // reset the styles for all
        aResults.removeClass("Selected");

        // add selected style
        var eSelectedItem = $("div.PlayerQuickSearchPlayerContainer", this.eSearchContainer).eq(this.iSelectedItem - 1);
        eSelectedItem.addClass("Selected");
    }
}

// DO THIS ON THE SERVER SIDE
PlayerQuickSearch.prototype.cleanSearchText = function (val)
{
    var r = val;
    r = r.replace(/[.,_\-]/img, " ");
    r = r.replace(/[ ]{2,}/img, " ");
    return r;
}

PlayerQuickSearch.prototype.findResults = function()
{
    var root = this;

    // reset the selected index to null
    this.iSelectedItem = null;

    var iSurnameCount = $("R SN P", this.xmlPlayerList).length;
    var iGivenNameCount = $("R GN P", this.xmlPlayerList).length;

    var sSearchVariable = this.cleanSearchText(this.eText.val());

    var aSurname = $("R SN P", this.xmlPlayerList).filter
    (
        function()
        {
            return (new RegExp("^" + sSearchVariable, "i")).test($(this).attr("SN") + " " + $(this).attr("GN"));
        }
    );

    var aGivenName = $("R GN P", this.xmlPlayerList).filter
    (
        function()
        {
            return (new RegExp("^" + sSearchVariable, "i")).test($(this).attr("GN") + " " + $(this).attr("SN"));
        }
    );

    this.eSearchContainer.empty();

    // make sure there is enough room to display all the results
    if (aSurname.length <= 35 && aGivenName.length <= 35)
    {
        //SMALL ICON DISPLAY
        if ((aSurname.length + aGivenName.length) > 6)
        {
            var html = "";
            html += "<div class=\"PlayerQuickSearchSubContainer\">";
            html += "<div class=\"Title\">Surname</div>";

            if (aSurname.length > 0)
            {
                $(aSurname).each
                (
                    function(i)
                    {
                        html += "<div class=\"PlayerQuickSearchPlayerContainer\">" + $(this).attr("GN") + "&nbsp;" + $(this).attr("SN") + "<input type=\"hidden\" value=\"" + $(this).attr("Url") + "\" /></div>";
                    }
                )
            }
            else
            {
                html += "<div class=\"NoResults\">No Results</div>";
            }
            html += "</div>";

            html += "<div class=\"PlayerQuickSearchSubContainer\">";
            html += "<div class=\"Title\">Given Name</div>";


            if (aGivenName.length > 0)
            {
                $(aGivenName).each
                (
                    function(i)
                    {
                        html += "<div class=\"PlayerQuickSearchPlayerContainer\">" + $(this).attr("GN") + "&nbsp;" + $(this).attr("SN") + "<input type=\"hidden\" value=\"" + $(this).attr("Url") + "\" /></div>";
                    }
                )
            }
            else
            {
                html += "<div class=\"NoResults\>No Results</div>";
            }
            html += "</div>";

            this.eSearchContainer.append(html);
        }

        //LARGE ICON DISPLAY
        else
        {
            var html = "";

            $(aSurname).each
            (
                function(i)
            {
                    /*
                    html += "<div class=\"PlayerQuickSearchPlayerContainer\" id=\"PlayerQuickSearchPlayerContainer_" + $(this).attr("PeId") + "\">";
                    html += "<div class=\"PlayerQuickSearchHeadshotContainer\" id=\"PlayerQuickSearchHeadshotContainer_" + $(this).attr("PeId") + "\"></div>";
                    html += "<span class=\"PlayerQuickSearchPlayerName\">" + $(this).attr("GN") + "&nbsp;" + $(this).attr("SN") + "</span><br />";
                    html += "<input type=\"hidden\" value=\"" + $(this).attr("Url") + "\" />";
                    html += "<span>" + $(this).attr("CN") + "</span>";
                    html += "</div>";
                    */
                    html += "<div class=\"PlayerQuickSearchPlayerContainer\">";
                    html += "<div class=\"PlayerQuickSearchHeadshotContainer\" id=\"PlayerQuickSearchHeadshotContainer_" + $(this).attr("PeId") + "\"></div>";
                    html += "<span class=\"PlayerQuickSearchPlayerName\">" + $(this).attr("GN") + "&nbsp;" + $(this).attr("SN") + "</span><br />";
                    html += "<input type=\"hidden\" value=\"" + $(this).attr("Url") + "\" />";
                    html += "<span>" + $(this).attr("CN") + "</span>";
                    html += "</div>";                    
                }
            )

            $(aGivenName).each
            (
                function(i)
                {
                    html += "<div class=\"PlayerQuickSearchPlayerContainer\">";
                    html += "<div class=\"PlayerQuickSearchHeadshotContainer\" id=\"PlayerQuickSearchHeadshotContainer_" + $(this).attr("PeId") + "\"></div>";
                    html += "<span class=\"PlayerQuickSearchPlayerName\">" + $(this).attr("GN") + "&nbsp;" + $(this).attr("SN") + "</span><br />";
                    html += "<input type=\"hidden\" value=\"" + $(this).attr("Url") + "\" />";
                    html += "<span>" + $(this).attr("CN") + "</span>";
                    html += "</div>";
                }
            )

            this.eSearchContainer.append(html);

            // start image loading routine
            $(".PlayerQuickSearchHeadshotContainer", this.eSearchContainer).each
            (
                function()
                {
                    var id = $(this).attr("id");
                    var personId = id.substring(id.lastIndexOf("_") + 1);
                    var img = new Image();
                    $("#" + id).empty().removeClass("error").addClass("loading");
                    $(img).load
                    (
                        function()
                        {
                            $(this).hide();
                            $("#" + id).removeClass("Loading").empty().append(this);
                            $(this).fadeIn();
                        }
                    ).error
                    (
                        function()
                        {
                            $("#" + id).hide().empty().addClass("Error").fadeIn(100);
                        }
                    ).attr("src", "/Images/Players/CroppedHeadshots/S/" + personId + ".jpg");
                }
            )
        }

        // add the click handlers
        //$("div[id^='PlayerQuickSearchPlayerContainer_']", this.eSearchContainer).click
        $("div.PlayerQuickSearchPlayerContainer", this.eSearchContainer).click
        (
            function()
            {
                root.gotoPlayer($("input:hidden", this).val());
            }
        )

        // show the thing
        this.eSearchContainer.css("visibility", "visible");
    }
    else
    {
        this.eSearchContainer.css("visibility", "hidden");
    }
    // position the popup
    this.positionSearchContainer();

    // addd the hover states
    this.addHoverStates();
}

PlayerQuickSearch.prototype.addHoverStates = function ()
{
    $(".PlayerQuickSearchPlayerContainer", this.eSearchContainer).hover
    (
        function()
        {
            $(this).addClass("Hover");
        },
        function()
        {
            $(this).removeClass("Hover");
        }
    )

    $(".PlayerQuickSearchSubContainer div[class!='Title']", this.eSearchContainer).hover
    (
        function()
        {
            $(this).addClass("Hover");
        },
        function()
        {
            $(this).removeClass("Hover");
        }
    )
}

PlayerQuickSearch.prototype.gotoPlayer = function(sUrl)
{
    // parse the id from the itemId
    //var playerId = itemId.substring(itemId.lastIndexOf("_") + 1);
    window.location.href = sUrl; // "/Players/Profile/?PersonId=" + playerId;
}

PlayerQuickSearch.prototype.activate = function()
{
    this.eContainer.css("display", "block");
    this.eText.val("");
    this.eText.focus();
    this.bIsSearchActivated = true;
}

PlayerQuickSearch.prototype.deactivate = function()
{
    this.eContainer.css("display", "none");
    $("#BrandOptions").css("display", "block");
    this.bIsSearchActivated = false;
}