﻿var avatarTip;
var avatarElement;

function attachBubble(elementId, width, height)
{
    var content = '<iframe src="Helpers/FeedbackForm.aspx" frameborder=0 width="' + width + '" height="' + height + '"></iframe>';
    avatarTip = new Tip($(elementId), content, { 
    title: 'Something to say?',
    style: 'protogrey',
    closeButton: true,
    fixed: true,
    width: 'auto',
    stem: 'bottomRight',
    showOn: 'click',
    hideOn: { element: 'closeButton', event: 'click' },
    offset: { x: 0, y: 3 },
    hook: { tip: 'bottomRight', target: 'topMiddle' }    
    });
    
}

function refreshMe() {
    window.location = window.location;
}


function refreshAvatar(newSrc) {
    $(avatarElement).src = newSrc;
}

function doneWithAvatar()
{
    Lightview.hide();   
}
    
function considerMe(uid, label, className, objectId, labelId)
{
    ConsiderHelper.AddConsider(uid, label, className, objectId, function (result) { $(labelId).innerHTML = result; });    
}

function doneConsiderMe(result)
{
    setLabel(result);
}

function removeConsider(considerId, labelId)
{
    ConsiderHelper.RemoveConsider(considerId, 'Icon', function (result) { $(labelId).innerHTML = result; });
}

function doneRemoveConsider(result)
{
    setLabel(result);
}

function commentSentiment(uid, articleId, s, resultLabel, leftLabel, rightLabel, commentBox)
{
  if (typeof(commentBox) == "undefined") // no overloads in js, so this is how we handle logged in (vs not longged in)
  {
       CommentHelper.CommentSentiment(articleId, s, function(result) 
            { 
                var newSent = new ptSentiment(uid, articleId, result, resultLabel, leftLabel, rightLabel, null);
                newSent.DisplaySentiment();
            } 
        );   
  }
  else  // not logged in
  {
       var cmtTxt;
       cmtTxt = $(commentBox).value;
       CommentHelper.CommentSentimentSaveComment(articleId, s, cmtTxt, function (result) 
            { 
                window.location = "/Login.aspx";   
            }
        );
  }
}

function ptSentiment(uid, articleId, status, resultLabel, leftLabel, rightLabel, commentBox)
{

    this.DisplaySentiment = function()
    {
        switch (status)
        {
            case 1:  // buy
                $(resultLabel).innerHTML = "<span class=\"sentimentAgree\">You currently agree with this coverage.</span>";
                $(leftLabel).innerHTML = this.GetSentimentLinkText('Hold');
                $(rightLabel).innerHTML = this.GetSentimentLinkText('Sell');
                break;
            case 2: // sell
                $(resultLabel).innerHTML = "<span class=\"sentimentDisagree\">You currently disagree with this coverage.</span>";
                $(leftLabel).innerHTML = this.GetSentimentLinkText('Buy');
                $(rightLabel).innerHTML = this.GetSentimentLinkText('Hold');
                break;
            case 3: // changed to hold
                $(resultLabel).innerHTML = "<span class=\"commentPublished\">You are neutral on this coverage.</span>";
                $(leftLabel).innerHTML = this.GetSentimentLinkText('Buy');
                $(rightLabel).innerHTML = this.GetSentimentLinkText('Sell');
                break;
            case -1: // probrem
                $(resultLabel).innerHTML = "There was an error.  Please try again.";
                $(resultLabel).className = "sentimentDisagree";
                $(leftLabel).innerHTML = this.GetSentimentLinkText('Buy');
                $(rightLabel).innerHTML = this.GetSentimentLinkText('Sell');
                break;
            default: 
                $(resultLabel).innerHTML = "&nbsp;";
                $(leftLabel).innerHTML = this.GetSentimentLinkText('Buy');
                $(rightLabel).innerHTML = this.GetSentimentLinkText('Sell');
                break;
        }
        
        FadeIn(resultLabel);
        FadeIn(leftLabel);
        FadeIn(rightLabel);
        
    };

    this.GetSentimentLinkText = function (s)
    {
        var actions = new Array();
        actions['Buy'] = new Array('Agree','agree19.png','agree');
        actions['Sell'] = new Array('Disagree','disagree19.png','disagree');
        actions['Hold'] = new Array('Go Neutral','confused19.png','neither agree nor disagree');

        return '<a style="cursor: default" onclick="' + this.GetSentimentJS(s) + '" title="Click here to '
        + actions[s][2] + ' with this coverage">' + actions[s][0] + '<img style="padding-left:3px;" src="/images/' 
        + actions[s][1] + '" align="absmiddle" border="0"/></a>';
    };

    this.GetSentimentJS = function (s)
    {
        var commentParam;
        if (isNaN(parseInt(uid)) || uid  < 1 || typeof(uid) == "undefined") // not logged in yet, so we'll need to know the comment box id to save it. 
            {   commentParam = ',\'' + commentBox + '\'';   }
        else
            {   commentParam = '';  } 
        return 'javascript:commentSentiment(' + uid + ', ' + articleId + ', \'' + s + '\', \'' + resultLabel + '\', \'' + leftLabel 
        + '\', \'' + rightLabel + '\'' + commentParam + ');';
    };
}


function AddCommentNotLoggedIn(commentBox)
{
    CommentHelper.AddCommentNotLoggedIn($(commentBox).value, function (result)
        {
            window.location = "/Login.aspx";
        }
    );
}

function AddComment(uid, articleId, sourceLabel, sourceAreaLabel, destinationLabel)
{
   var commentText;
   var cid;
   
   commentText = $(sourceLabel).value;
   CommentHelper.AddCommentFromJS(uid, articleId, commentText, function (cid)
        {
           if (cid > 0)
           {
                // comment was added, clear the textbox and update the table 
                FadeOut(sourceLabel);
                $(sourceLabel).value = null;
                CommentHelper.GetNewCommentHTML(cid, function (newcommenthtml)
                    {
                        $(destinationLabel).innerHTML = newcommenthtml;
                    }
                );
                FadeIn(destinationLabel);
                $(sourceAreaLabel).innerHTML = "<span class=\"commentPublished\">Your comment has been published.</span>";
                FadeIn(sourceAreaLabel);
           }
           else
           {
                $(destinationLabel).innerHTML = "<span class=\"sentimentDisagree\">There was a problem saving your comment, please enter a comment and try again.</span>";
           }

        }
    );   
}

function CloseEarly(uid, articleid, sourcediv)
{

 if(window.confirm('Are you sure you wish to close this position early?\nThe close price may be different than the price displayed here, since this price information is delayed.'))
 {
     var destSpan = 'ajaxClosed'; // can pass this later if we put close buttons in places other than AC
     var closeText;
     var closeprice;
     CloseEarlyHelper.CloseEarly(uid, articleid, function(closeprice)
        {
         if (closeprice != '')
         {
            closeText = 'Closed ' + closeprice + ' <span class="downplay">(pending)</span>';
            FadeOut(sourcediv);
         }
         else
         {
            closeText = '<span class="Error">Error closing coverage</span>';
         }
          $(destSpan).innerHTML = closeText;
          FadeIn(destSpan);
          FadeIn(destSpan);
          FadeIn(destSpan);
        });

  }
}

function FormatPrice(dIn)
{
    var d = parseFloat(dIn);
    if (typeof(d) == undefined)
        { return '&nbsp;'; }

    if (d >= 1000)
        return d.toFixed(0);
    else if (d < 1)
    {
        var possibleReturn = d.toFixed(3);
        if (possibleReturn.substring(possibleReturn.length - 1) == '0')
            return d;
        else return possibleReturn;
    }
    else
        return d;
}

function FadeIn(id)
{
 var objID = $(id);
 $(objID).fade({duration: 1.0, from: 0, to: 1});
}
function FadeOut(id)
{
 var objID = $(id);
 $(objID).fade({duration: 1.0, from: 1, to: 0.01});
}

function goToLogin()
{
    window.location = '/Login.aspx';
}
    
function clearMe(obj)
{
    // where obj is a textbox
    obj.value = "";
}

function searchSubmit()
{
    var searchInput = $('txtPrimarySearch')
    var searchQuery = searchInput.value;
    
    if (searchQuery.length > 0 && searchQuery != "search securities, articles, people" && searchQuery != "please enter search text" && searchQuery != "search") // this is set in a literal so need to match that up
    {
        var newUrl = "/Search.aspx?q=" + searchQuery;
        window.location = newUrl;
    }
    else
    {
        searchInput.value = "please enter search text";
        return false;
    }
}

function confirmGoTo(url, text)
{
    if (window.confirm(text))
    {
        window.location = url;
        return;
    }   
    else
        return;
}

function sortMe(str)
{
    var urlnow = new String(document.location);
    var newhref = new String();
    
    var sortIndex;
    sortIndex = urlnow.indexOf("Sort=")
    if (sortIndex != -1)
    {
        var latterIndex = urlnow.substr(sortIndex).indexOf("&");
        if (latterIndex != -1)
            newhref = urlnow.substr(0, sortIndex) + "Sort=" + str + urlnow.substr(sortIndex + latterIndex);
        else
            newhref = urlnow.substr(0, sortIndex) + "Sort=" + str;
    } 
    else
    {
        newhref = document.location + "&Sort=" + str; // predicated on their already being some url vars (which there will be)
    }
    // that was all very laborious and ugly
    
     
    window.location = newhref;
}

function searchSelect(text, li)
{
    //alert("text = " + text);
    window.location = li.id;
}