﻿/// <reference path="pwscommon.js"/>
function ShareAThoughtControl(instanceName) {
    /// <summary>
    /// Manages client-side dynamic behavior of the Share A Thought control.
    /// </summary>

    //get (jquery) references to DOM elements
    this._divTabAllComments = $('#divTabAllComments');
    this._divTabFriendComments = $('#divTabFriendComments');
    this._divTabTopPredictorsComments = $('#divTabTopPredictorsComments');
    this._divTabFollowComments = $('#divTabFollowComments');

    this._divTabAllCommentsTab = $('#divTabAllCommentsTab');
    this._divTabFriendCommentsTab = $('#divTabFriendCommentsTab');
    this._divTabTopPredictorsCommentsTab = $('#divTabTopPredictorsCommentsTab');
    this._divTabFollowCommentsTab = $('#divTabFollowCommentsTab');
    this._chkTwitter = $elt('chkTwitter');
    this._chkFacebook = $elt('chkFacebook');

    //bind events
    this._divTabAllCommentsTab.bind("click", { "CommentGroup": "1" }, Delegate.Create(this, this.switchTabs));
    this._divTabFriendCommentsTab.bind("click", { "CommentGroup": "2" }, Delegate.Create(this, this.switchTabs));
    this._divTabTopPredictorsCommentsTab.bind("click", { "CommentGroup": "3" }, Delegate.Create(this, this.switchTabs));
    this._divTabFollowCommentsTab.bind("click", { "CommentGroup": "4" }, Delegate.Create(this, this.switchTabs));

    $("#comment_input").bind("keypress", Delegate.Create(this, this.imposeMaxLength));
    $("#comment_input").bind("keyup", this.updateCharactersRemainingCount);
    $("#comment_share").bind("click", Delegate.Create(this, this.addComment));

    Anthem_InvokeControlMethod(
        ShareAThoughtSettings.ControlId,
        "IsCurrentUserAnonymous",
        [],
        function(isAnonymous) {
            ShareAThoughtSettings.isAnonymous = isAnonymous.value;
        });

}

ShareAThoughtControl.prototype =
{
    //private properties
    //--------------------
    _instanceName: "",
    _pageIsPollingForComments: false,

    //public properties
    //--------------------
    controlId: "",

    //public methods
    //------------------
    switchTabs: function ShareAThought$switchTabs(e) {

        /// <summary>
        /// Switches tabs on the Share A Thought control
        /// </summary>
        /// <param name="e">event param.  e.data.CommentGroup is the CommentGroup</param>

        // Clear any existing timer.
        clearTimeout(this.shareAThoughtTimer);

        //retrieve comment group and convert to number (*1) for switch statement (which would otherwise fail)
        activeTab = (e.data.CommentGroup) * 1;

        //enable polling (ie begin the process whereby the page continually requeries the comments table for the
        //contents of the new comment group_
        ShareAThoughtSettings.pollingTimerEnabled = true;

        //set all tabs bodies invisible
        this._divTabAllComments.css('display', 'none');
        this._divTabFriendComments.css('display', 'none');
        this._divTabTopPredictorsComments.css('display', 'none');
        this._divTabFollowComments.css('display', 'none');

        //remove selected class
        this._divTabAllCommentsTab.removeClass('active');
        this._divTabFriendCommentsTab.removeClass('active');
        this._divTabTopPredictorsCommentsTab.removeClass('active');
        this._divTabFollowCommentsTab.removeClass('active');

        //set the tab and body sections on
        switch (activeTab) {
            case PWSConstants.ShareAThought.ALL:
                {
                    this._divTabAllComments.css('display', 'block');
                    this._divTabAllCommentsTab.addClass('active');
                    ShareAThoughtSettings.activeTab = PWSConstants.ShareAThought.ALL;
                    break;
                }
            case PWSConstants.ShareAThought.FRIENDS:
                {
                    this._divTabFriendComments.css('display', 'block');
                    this._divTabFriendCommentsTab.addClass('active');
                    ShareAThoughtSettings.activeTab = PWSConstants.ShareAThought.FRIENDS;
                    break;
                }
            case PWSConstants.ShareAThought.TOPPREDICTORS:
                {
                    this._divTabTopPredictorsComments.css('display', 'block');
                    this._divTabTopPredictorsCommentsTab.addClass('active');
                    ShareAThoughtSettings.activeTab = PWSConstants.ShareAThought.TOPPREDICTORS;
                    break;
                }
            case PWSConstants.ShareAThought.FOLLOW:
                {
                    this._divTabFollowComments.css('display', 'block');
                    this._divTabFollowCommentsTab.addClass('active');
                    ShareAThoughtSettings.activeTab = PWSConstants.ShareAThought.FOLLOW;
                    break;
                }
        }

        // Update the comments for the newly selected tab.
        getComments();
    },

    updateCharactersRemainingCount: function ShareAThought$updateCharactersRemainingCount() {
        /// <summary>
        /// Updates the remaining charater count
        /// </summary>     
        $("#divCharactersLeft").html((PWSConstants.ShareAThought.TOTAL_COMMENT_CHARACTERS - $elt("comment_input").value.length));
    },

    imposeMaxLength: function ShareAThought$imposeMaxLength(e) {
        /// <summary>
        /// Imposes a max length on typed input in the 'comment_input' textarea box
        /// and responds to the return key
        /// </summary>
        var commentInput = $elt("comment_input");

        if (e.keyCode == PWSConstants.KeyCodes.BACKSPACE || e.keyCode == PWSConstants.KeyCodes.DELETE) {
            return true;
        }

        if (e.keyCode == PWSConstants.KeyCodes.RETURN && commentInput.value.length > 0) {
            this.addComment();
        }
        return (commentInput.value.length <= (PWSConstants.ShareAThought.TOTAL_COMMENT_CHARACTERS - 1))
    },

    initialize: function ShareAThought$initialize() {
        /// <summary>
        /// Retrieves initial comments from all 3 comment groups
        /// </summary>
        ShareAThoughtSettings.pollingTimerEnabled = true;
        ShareAThoughtSettings.activeTab = PWSConstants.ShareAThought.ALL;
        getComments();
    },

    setHeight: function ShareAThought$setHeight(height) {
        /// <summary>
        /// Sets the height of the Share A Thought control
        /// This public method is called from PanelPredict.js
        /// </summary>
        $elt("divTabAllComments").style.height = height + "px";
        $elt("divTabFriendComments").style.height = height + "px";
        $elt("divTabTopPredictorsComments").style.height = height + "px";
    },

    addComment: function() {
        /// <summary>
        /// Adds a Share a Thought comment
        /// </summary>

        //First search for spam/profanity
        var comment = $elt("comment_input");
        var profanityArray = TwitFilter.ProfanityKeywords.split(",");
        var linkArray = TwitFilter.LinkKeywords.split(",");
        var isLink = PWSC.isKeywordMatch(comment.value.toLowerCase(), linkArray, true);
        var isProfane = PWSC.isKeywordMatch(comment.value.toLowerCase(), profanityArray, false);
        if (isLink || isProfane) {
            alert("Your thought contained keywords not allowed by our spam and profanity filter.  Shame on you!  Please try again.");
            return;
        }

        if (ShareAThoughtSettings.RequiresLogin) {
            if (ShareAThoughtSettings.isAnonymous) {
                PWSC.OpenOverlay("/SignUpOverlay.aspx?showwarning=true");
                return false;
            }
        }

        var commentTimeframe = 0;
        var commentPredictionDirection = PWSConstants.PredictionDirection.NotProvided;
        if (typeof (TimeFramePredict) != 'undefined' && TimeFramePredict != null) {
            commentTimeframe = TimeFramePredict.CurrentTimeFrame;
            commentPredictionDirection = TimeFramePredict.CurrentPredictionDirection;
        }

        if (!ShareAThoughtSettings.HasTwitterLogin && this._chkTwitter.checked) {
            return PWSC.OpenOverlay('/TwitterLogin.aspx');
        }

        if (!ShareAThoughtSettings.HasFacebookSession && this._chkFacebook.checked) {
            Anthem_InvokeControlMethod(
                                ShareAThoughtSettings.ControlId,
                                "StoreFacebookComment",
                                [comment.value, ShareAThoughtSettings.predictorId, commentPredictionDirection, commentTimeframe, ShareAThoughtSettings.Symbol],
                                function(result) { /* alert("error: " + result.error); */ }
                                );
            return PWSC.OpenOverlay('/ShareAThought.aspx');
        }


        //make the call
        Anthem_InvokeControlMethod(
                                    ShareAThoughtSettings.ControlId,
                                    "SaveComment",
                                    [comment.value, ShareAThoughtSettings.predictorId, commentPredictionDirection, commentTimeframe, this._chkTwitter.checked, this._chkFacebook.checked, ShareAThoughtSettings.Symbol],
                                    null
                    );
        comment.value = "";
        this.updateCharactersRemainingCount();

        //If there is SAT activity, then reset the disabler clock.
        ShareAThoughtSettings.ClientSideIterations = 0;

        // Refresh the current tab immediately after a comment is posted.
        if (ShareAThoughtSettings.Paused) {
            ShareAThoughtSettings.Paused = false;
        }

        getComments();

    },


    enable: function() {
        $elt(ShareAThoughtSettings.ControlId + "_divCannotShareAThought").style.display = "none";
    }
}


//Constants
//---------------------------------------------
PWSConstants.ShareAThought = {
    ALL: 1,
    FRIENDS: 2,
    TOPPREDICTORS: 3,
    FOLLOW: 4,
    TOTAL_COMMENT_CHARACTERS: 110
};


//Static methods related to Share A Thought. Anthem seems to not allow a callback method be an instance method.
//If we can fix this Anthem issue, we will move these methods and the 'Setting' properties , and the methods below inside the object.
//--------------------------------------------------
var ShareAThoughtSettings = {};
ShareAThoughtSettings.activeTab = PWSConstants.ShareAThought.ALL;
ShareAThoughtSettings.pageIsPollingForComments = true;
ShareAThoughtSettings.pollingTimerEnabled = false;
ShareAThoughtSettings.predictorId = 0;
ShareAThoughtSettings.Height = 0;
ShareAThoughtSettings.HeightOffset = 15;
ShareAThoughtSettings.ShowTimeAgo = true;
ShareAThoughtSettings.ClientSideIterations = 0;
ShareAThoughtSettings.ClientSideIterationsMax = 90;
ShareAThoughtSettings.Paused = false;
//5 seconds is the default value.
ShareAThoughtSettings.PollingInterval = 5000;
ShareAThoughtSettings.shareAThoughtTimer;
ShareAThoughtSettings.isAnonymous;
ShareAThoughtSettings.HasTwitterLogin = false;
ShareAThoughtSettings.Symbol = "";

function getComments() {
    /// <summary>
    /// Makes an Anthem call to server-side code to get the comments that relate to the 
    /// tab that is currently active.
    /// </summary>

    switch (ShareAThoughtSettings.activeTab) {
        case PWSConstants.ShareAThought.ALL:
            {
                Anthem_InvokeControlMethod(
                                ShareAThoughtSettings.ControlId,
                                "GetAllComments",
                                [],
                                getCommentsCallback
                );
                break;
            }
        case PWSConstants.ShareAThought.FRIENDS:
            {
                Anthem_InvokeControlMethod(
                                ShareAThoughtSettings.ControlId,
                                "GetFriendsComments",
                                [ShareAThoughtSettings.predictorId],
                                getCommentsCallback
                                );
                break;
            }
        case PWSConstants.ShareAThought.FOLLOW:
            {
                Anthem_InvokeControlMethod(
                                ShareAThoughtSettings.ControlId,
                                "GetFollowComments",
                                [ShareAThoughtSettings.predictorId],
                                getCommentsCallback
                                );
                break;
            }
        case PWSConstants.ShareAThought.TOPPREDICTORS:
            {
                Anthem_InvokeControlMethod(
                                ShareAThoughtSettings.ControlId,
                                "GetTopPredictorsComments",
                                [],
                                this.getCommentsCallback
                                );
                break;
            }
    }

}

function getSATTimeframeDescription(timeFrame) {
    /// <summary>
    /// Returns the English description of prediction direction
    /// used by Share a Thought (SAT)    
    /// </summary>    
    switch (timeFrame) {
        case PWSConstants.TimeFrames.OneDay:
            return "1 day";
        case PWSConstants.TimeFrames.OneWeek:
            return "1 week";
        case PWSConstants.TimeFrames.OneMonth:
            return "1 month";
        case PWSConstants.TimeFrames.ThreeMonth:
            return "3 months";
    }
}


function getSATDirectionDescription(direction) {
    /// <summary>
    /// Returns the English description of prediction direction
    /// used by Share a Thought (SAT)    
    /// </summary>    
    switch (direction) {
        case PWSConstants.PredictionDirection.Up:
            return "UP";
        case PWSConstants.PredictionDirection.Down:
            return "DOWN";
    }
}


function getCommentsCallback(resultJson) {
    /// <summary>
    /// Retrieves the JSON data from the server-side comments call and displays it on the 
    /// appropriate Share A Thought tab
    /// </summary>

    // Clear any existing timeout.


    //Retrieve comments collection from callback result (in JSON format)
    var result = eval(resultJson.value);
    if (!result) {
        return;
    }
    result = result[0];
    var comments = result.Comments;

    //Create the comments markup from the comments collection
    if (comments != null) {
        var commentsCount = comments.length;
        var tmpFriendsChat = "";
        for (var i = commentsCount - 1; i >= 0; i--) {

            var comment = comments[i];
            var imageMarkup = "";

            //constuct hover text,
            //ie 'Predicted UP in 1 week for APPL'
            var predictionHover = "";
            var predictionImage;
            if (comment.PredictionDirection == PWSConstants.PredictionDirection.NotProvided) {

                if (comment.IsTwitter) {
                    predictionHover = "Twitter comment";
                    predictionImage = PWSConstants.FromTwitter
                }
                else {
                    predictionHover = "No Prediction";
                    predictionImage = PWSConstants.NoPredictionImage;
                }
            }
            else {
                predictionHover = "Predicted " +
                        getSATDirectionDescription(comment.PredictionDirection) +
                        " in " +
                        getSATTimeframeDescription(comment.LeadTimeInDays) +
                        " for " + comment.Symbol;
                if (comment.PredictionDirection == PWSConstants.PredictionDirection.Up) {
                    predictionImage = PWSConstants.UpArrowSmall;
                }
                if (comment.PredictionDirection == PWSConstants.PredictionDirection.Down) {
                    predictionImage = PWSConstants.DownArrowSmall;
                }
            }

            //construct image markup
            //ie the markup for the up or down arrow to the left of the Screenname            
            imageMarkup = "<a href=\"#\"><img alt=\"" + predictionHover + "\" title=\"" + predictionHover + "\" src='/images/" + predictionImage + "' style='margin-right:4px;' /></a>";

            var userLink = "";

            //add comment and image to markup

            if (comment.IsTwitter || !ShareAThoughtSettings.ShowMemberPopUp) {

                var spanStyle = "";

                if (comment.IsTwitter) {
                    spanStyle = " style='color:brown'";
                }
                else {
                    spanStyle = " style='color:black'";
                }

                tmpFriendsChat += "<tr><td valign='top' style='padding:10px 0 0 0;'>" + imageMarkup + "</td><td valign='top' style='padding:10px 0 0 0;'><span" + spanStyle + ">" + comment.UserScreenName + "</span> - " + comment.UserComment;
            }
            else {
                tmpFriendsChat += "<tr><td valign='top' style='padding:10px 0 0 0;'>" + imageMarkup + "</td><td valign='top' style='padding:10px 0 0 0;'><a href=\"/peopleprofile.aspx?pid=" + comment.PredictorID + "\" onmouseover=\"PopUpMemberSummary.Show(this, '" + comment.UserScreenName + "', " + comment.PredictorID + ");\" onmouseout=\"PopUpMemberSummary.Hide();\">" + comment.UserScreenName + "</a> - " + comment.UserComment;
            }
            if (ShareAThoughtSettings.ShowTimeAgo) {
                tmpFriendsChat += " <span style='color:#996'>(" + comment.TimeAgo + ")</span>";
            }
            tmpFriendsChat += "</td></tr>";
        }

        //Identify the target div in which to display the results
        var divResults = null;

        if (result.CommentGroup == PWSConstants.ShareAThought.ALL) {
            divResults = $elt("divTabAllCommentsContent");
        }
        if (result.CommentGroup == PWSConstants.ShareAThought.FRIENDS) {
            divResults = $elt("divTabFriendsCommentsContent");
        }
        if (result.CommentGroup == PWSConstants.ShareAThought.TOPPREDICTORS) {
            divResults = $elt("divTabTopPredictorsCommentsContent");
        }
        if (result.CommentGroup == PWSConstants.ShareAThought.FOLLOW) {
            divResults = $elt("divTabFollowCommentsContent");
        }

        //Display the results
        if (divResults) {
            divResults.innerHTML = "<table>" + tmpFriendsChat + "</table>";

            //push the results up so that the latest comments shows up at the bottom
            //and the overflow pushes up beyond the top
            var delta = (divResults.offsetHeight - ShareAThoughtSettings.Height)
            if (delta > 0) {
                divResults.style.top = "-" + delta + "px";
            }
        }
    }

    //If this page has been open for about 6 minutes (or 90 iterations of SAT loads) without a 
    //page refresh then shut down SAT.
    if (ShareAThoughtSettings.ClientSideIterations++ > ShareAThoughtSettings.ClientSideIterationsMax) {
        ShareAThoughtSettings.Paused = true;
        return;
    }

    //Requery 4 seconds later
    if (ShareAThoughtSettings.pollingTimerEnabled) {
        // Clear any timer that may still be running.
        clearTimeout(this.shareAThoughtTimer);
        this.shareAThoughtTimer = setTimeout(getComments, ShareAThoughtSettings.PollingInterval);
    }
}

