﻿/***********************************************************************

Copyright (C) Microsoft. All rights reserved.

************************************************************************/
// break out of iframe
if (top.location != self.location) {
    top.location = self.location.href;
}
var g_searchText = '';
var g_searchOrigin = '';
var g_inSearch = false;
var g_lastItemDate = 0;
var g_updateStatus = "Update your status...";
var g_fromSpindex = "Shared from Spindex";
var g_photoMargin = 5;
var g_availableSpace = 459;
var g_photoSpace = 486;
var g_interItemSpace = 28;
var g_itemsToShow = 2;
var g_blockWidth = (g_availableSpace - g_interItemSpace) / g_itemsToShow;
var g_photoHeight = 108;
var g_savedSearchContainer = null;
var appid = "BD6F293826FDB6FEB46408A92549E6E8DFF3C5A6";
var su = "http://spindex.me";
var g_dropDownMenu = null;
var currentLeftmostLink = 0;
var g_timeZone = '';
var g_currentLeftmostPhoto = 0;
var g_currentRightmostPhoto = 0;
var g_additionalInfo = '';
var g_itemId = '';
var g_countScrolling = 0;
TwitterReporting = {};
TwitterReporting.HttpRequest = function (href) {
    var img = new Image;
    img.src = href
};
TwitterReporting.Timestamp = function () {
    var d = new Date();
    function digit2(n) {
        if (n < 10) return "0" + n; return "" + n;
    }
    var ts = d.getFullYear() + digit2(d.getMonth() + 1) + digit2(d.getDate()) + digit2(d.getHours()) + digit2(d.getMinutes()) + digit2(d.getSeconds());
    var tz = d.getTimezoneOffset();
    return ts + (tz >= 0 ? "+" : "") + tz;
};
TwitterReporting.CreateGuid = function () {
    function r(n) { return ((Math.random() + 1) * 65536 | 0).toString(16).substring(1) + (n ? r(n - 1) : "") }
    return [r(1), r(), r(), r(), r(2)].join("-")
};
TwitterReporting.GetCookie = function (name) {
    for (var nameEQ = name + "=", ca = document.cookie.split(";"), i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == " ") c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length)
    }
    return null
};
TwitterReporting.SetCookie = function (name, value, days) {
    if (days) {
        var date = new Date;
        date.setTime(date.getTime() + days * 24 * 60 * 60 * 1e3);
        var twitcookieexpires = "; expires=" + date.toGMTString()
    } else twitcookieexpires = "";
    document.cookie = name + "=" + value + twitcookieexpires + "; path=/"
};
TwitterReporting.SessionID = TwitterReporting.CreateGuid();
TwitterReporting.UserID = TwitterReporting.GetCookie("usrID");
if (TwitterReporting.UserID == null) {
    TwitterReporting.UserID = TwitterReporting.CreateGuid();
    TwitterReporting.SetCookie("usrID", TwitterReporting.UserID, 36500)
}
TwitterReporting.LogTweetDisplay = function (twID) {
    var url = "http://g.msn.com/_0MGMSN//1??cm=Spindex&appID=" + appid + "&sesID=" + TwitterReporting.SessionID + "&usrID=" + TwitterReporting.UserID + "&mo=BRO&ev=DIS&su=" + encodeURIComponent(su) + "&dtTm=" + TwitterReporting.Timestamp() + "&numTw=" + $(document.body).find(".hTweet").size() + "&twID=" + twID;
    TwitterReporting.HttpRequest(url)
};
TwitterReporting.LogTweetClick = function (linkID, du, twID) {
    var url = "http://g.msn.com/_0MGMSN//" + linkID + "??cm=Spindex&appID=" + appid + "&sesID=" + TwitterReporting.SessionID + "&usrID=" + TwitterReporting.UserID + "&mo=BRO&ev=CLK&su=" + encodeURIComponent(su) + "&du=" + encodeURIComponent(du) + "&dtTm=" + TwitterReporting.Timestamp() + "&numTw=" + $(document.body).find(".hTweet").size() + "&twID=" + twID;
    TwitterReporting.HttpRequest(url)
};
TwitterReporting.HTweetLinkMap = { "author-link": 2, "avatar-link": 3, "at-mention-link": 4, "skip-hash-mention-link": 5, "url-link": 6, "tweet-timestamp-link": 7, "tweet-source-link": 8 };
TwitterReporting.HandleTweetClick = function (e) {
    var element = $(e.currentTarget);
    for (var link in TwitterReporting.HTweetLinkMap) if (element.hasClass(link)) {
        TwitterReporting.LogTweetClick(TwitterReporting.HTweetLinkMap[link], element.attr("href"), element.parents(".hTweet").find(".tweet-id").text());
        return
    }
};
TwitterReporting.BindTweetClicks = function (tweetParent) {
    tweetParent = tweetParent || document;
    var hTweets = $(tweetParent).find(".hTweet").unbind(".hTweetEvents");
    for (var link in TwitterReporting.HTweetLinkMap) hTweets.find("." + link).bind("click.hTweetEvents", TwitterReporting.HandleTweetClick)
}
function closeDynamicPopup(e) {
    e = window.event || e;
    var target = $(e.target || e.srcElement);
    closeSearchBox(target);
    closeDropDownMenu(target);
}
function closeSearchBox(target) {
    var id = target.attr('id');
    if (id != 'searchBox' && id != 'searchText' && id != 'searchIcon') {
        $('#searchBox').hide();
    }
}
function closeDropDownMenu(target) {
    if (g_dropDownMenu) {
        if (!target.hasClass('dropDownMenu') && !target.hasClass('dqi')) {
            g_dropDownMenu.hide();
            g_dropDownMenu = null;
        }
    }
}
function encodeHtml(str) {
    if (typeof (str) == 'undefined' || str.length == 0) {
        return '';
    }
    return $('<div/>').text(str).html();
}
function decodeHtml(str) {
    if (typeof (str) == 'undefined' || str.length == 0) {
        return '';
    }
    return $('<div/>').html(str).text();
}
String.prototype.format = function () {
    var formatted = this;
    for (var i = 0; i < arguments.length; ++i) {
        formatted = formatted.replace("{" + i + "}", arguments[i]);
    }
    return formatted;
}
function setWaitCursor() {
    $('#contentNoScroll').css('cursor', 'wait');
    document.body.style.cursor = 'wait';
}
function setDefaultCursor() {
    $('#contentNoScroll').css('cursor', 'default');
    document.body.style.cursor = 'default';
}
function resizeContent() {
    var contentHeight = document.documentElement.clientHeight - 73;
    var content = $('#content');
    if (content.children().length > 0) {
        content.css('height', contentHeight + 'px');
    }
    else {
        $('#contentNoScroll').css('height', contentHeight + 'px');
        var left = $('#contentNoScroll .leftColumn');
        if (left.length > 0) {
            left.css('height', contentHeight + 'px');
        }
        var stream = $('#contentNoScroll .streamColumn');
        if (stream.length > 0) {
            stream.css('height', contentHeight + 'px');
        }
        var streamsContainer = $('#streamsContainer');
        if (streamsContainer.length > 0) {
            var prev = streamsContainer.prev();
            streamsContainer.css('height', contentHeight - (prev.length > 0 ? prev.outerHeight() : 0) - 20 + 'px');
        }
        var synopsis = $('#contentNoScroll .synopsisColumn');
        if (synopsis.length > 0) {
            synopsis.css('height', contentHeight + 'px');
        }
    }
    setColumnWidths();
}
function setColumnWidths() {
    var newWidth = $('.allColumns').width() - $('.leftColumn').width() - $('.synopsisColumn').width()
        - 20 /* synopsis column margin */ - 40 /* padding */;

    $('.streamColumn').width(newWidth);
    $('#streams').width(newWidth);
    $('#statusUpdateTextArea').width($('#statusUpdate').width() - 79 - 7);
    $('#statusUpdateText').width($('#statusUpdateTextArea').width() - 3);
}
function postToFb() {
    var postToFbCheckbox = $('#postToFb');
    return postToFbCheckbox.length > 0 && postToFbCheckbox[0].checked;
}
function postToTwitter() {
    var postToTwitterCheckbox = $('#postToTwitter');
    return postToTwitterCheckbox.length > 0 && postToTwitterCheckbox[0].checked;
}
function postStatus() {
    var message = $('#statusUpdateText').val();
    if (message == "" || message == g_updateStatus)
        return false;
    var shouldPostToFb = postToFb();
    var shouldPostToTwitter = postToTwitter();
    if ((!g_facebookPostUrl && !g_twitterPostUrl) ||
        !message || message.length == 0 || (!shouldPostToFb && !shouldPostToTwitter)) {
        resetPostBox();
        return;
    }
    var status = encodeURI(message);
    status = status.replace('#', '%23'); 
    if (shouldPostToFb) {
        $.ajax({
            url: g_facebookPostUrl.concat(status) + g_timeZone,
            success: function (data) {
                $('#streams').prepend(renderPost(data));
            }
        });
    }
    if (shouldPostToTwitter) {
        $.ajax({
            url: g_twitterPostUrl.concat(status) + g_timeZone,
            success: function (data) {
                $('#streams').prepend(renderTweet(data));
            }
        });
    }
    resetPostBox();
}
function showRemaining() {
    var statusUpdateText = $('#statusUpdateText');
    var length = statusUpdateText.val().length;
    var maxLength = 0;
    if (postToTwitter())
        maxLength = 140;
    else if (postToFb())
        maxLength = 420;
    if (maxLength > 0) {
        var remaining = maxLength - length;
        $('#postCount').text(remaining).show();
        $('.padding').show();
        $('#shortenUrl').show();
        var color = 'black';
        if (remaining < 5)
            color = 'red';
        $('#postCount').css({ 'color': color });
    }
    if (remaining > 0) {
        $('#postStatusLabel')[0].src = '/content/images/post-button-text-loaded.png';
    } else {
        $('#postStatusLabel')[0].src = '/content/images/post-button-reg.png';
    }
}
var g_validUrlRegEx = /^(|http(s)?:\/\/)?(([a-zA-Z0-9\._-]*([a-zA-Z0-9]\.[a-zA-Z0-9])[a-zA-Z]{1,6})|(([0-9]{1,3}\.){3}[0-9]{1,3}))(:\d+)?(\/[^:][^\s]*)?$/gi;
function isValidUrl(url) {
    return (url.match(g_validUrlRegEx) != null);
}
function stripTrailingPunctuation(text) {
    end = text.length;
    var chLast = text.charAt(end - 1);
    if (chLast == '?' || chLast == ';' || chLast == ',' || chLast == ')')
        end--;
    return text.substr(0, end);
}
function findUrl(text) {
    var matches = text.match(/\S+/);
    if (matches.length != 0) {
        for (var i = 0; i < matches.length; i++) {
            var test = stripTrailingPunctuation(matches[i]);
            if (isValidUrl(test))
                return test;
        }
    } else {
        text = stripTrailingPunctuation(text);
        var url = text.substring(0, end);
        if (isValidUrl(url))
            return url;
    }
    return null;
}
function shortenUrls(i, reportFailure) {
    var text = $('#statusUpdateText').val().substring(i);
    var start = text.indexOf("http:");
    if (start != -1) {
        var urlString = findUrl(text.substr(start));
        if (IsNullOrEmpty(urlString)) {
            $('#nothingToShorten').show();
            return;
        }
        end = start + urlString.length;
        var shortened = false;
        var begin = start;
        $.getJSON(g_BitlyUrl + encodeURI(urlString) + "&callback=?", function (data) {
            if (data.status_code < 300) {
                if (data.data.url.length < end - begin) {
                    var newString = $('#statusUpdateText').val().replace(urlString, data.data.url);
                    i = $('#statusUpdateText').val().indexOf(data.url) + data.data.url.length;
                    $('#statusUpdateText').val(newString);
                    $('#nothingToShorten').hide();
                    shortened = true;
                } else {
                    if (reportFailure)
                        $('#nothingToShorten').show();
                    i = start + urlString.length;
                }
            }
            if (!shortened) {
                $('#nothingToShorten').show();
            }
            if (end != text.length) {
                var start = text.substring(end).indexOf("http:");
                if (start != -1)
                    shortenUrls(end + start, !shortened);
            }
        });
    } else if (reportFailure)
        $('#nothingToShorten').show();
}
function onPostBoxClick() {
    var statusUpdateText = $('#statusUpdateText');
    if (statusUpdateText.val() == g_updateStatus)
        statusUpdateText.val('');
    statusUpdateText.keyup(showRemaining);
    statusUpdateText.css({ 'color': '#000000' });
    statusUpdateText.height('100px');

    $('#statusUpdateTextArea').height('110px');
    $('#statusUpdate').height('120px');
    $('#updateControls').height('100px');
    $('#nothingToShorten').hide();
}
function onPostBoxBlur() {
    var postText = $('#statusUpdateText').val();
    if (postText.length == 0 || postText == g_postBoxText) {
        resetPostBox();
    }
}
function onPseudoSearchClick() {
    var topLeft = findPos($('#pseudoSearch')[0]);
    $('#searchBox').css({ 'left': topLeft[0] }).show('fast');
    setTimeout("$('#searchText').val('').focus()", 50);
}
function findPos(obj) {
    var curLeft = curTop = 0;
    if (obj.offsetParent) {
        do {
            curLeft += obj.offsetLeft;
            curTop += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }
    return [curLeft, curTop];
}
function onSearchBoxClick() {
    resetLeftButtons();
    search($('#searchText').val(), 'Search Box');
    $('#searchBox').hide();
    $('#searchText').val('');
}
function onSearchBoxKeyup(e) {
    var code = 0;
    if (!e)
        e = window.event;
    if (e.keyCode)
        code = e.keyCode;
    else if (e.which)
        code = e.which;
    if (code == 13) {
        onSearchBoxClick();
        e.cancelBubble = true;
        if (e.stopPropagation)
            e.stopPropagation();
    }
}
function showRemainingCommentArea() {
    var maxLength = 140;
    if (g_additionalInfo.indexOf('facebook') != -1) {
        maxLength = 420;
    }
    var replyText = $('#' + g_itemId + ' .replytext');
    var length = replyText.val().length;
    var remaining = maxLength - length;
    $('#' + g_itemId + ' .postCount').text('Characters remaining: ' + remaining).show();
    var color = 'black';
    if (remaining < 5)
        color = 'red';
    $('#' + g_itemId + ' .postCount').css({ 'color': color });
}
function onCommentAreaKeyup(e) {
    var code = 0;
    if (!e)
        e = window.event;
    if (e.keyCode)
        code = e.keyCode;
    else if (e.which)
        code = e.which;
    if (code == 13) {
        onCommentClick(g_additionalInfo, g_itemId);
    }
    showRemainingCommentArea();
}
function onCommentAreaClick(item, label) {
    var replyText = $('#' + item + ' .replytext');
    if (replyText.val().indexOf(label) == 0)
        replyText.val('');
    replyText.css({ 'color': 'black' });
}
function onCommentCancelClick(label, item) {
    $('#' + item + ' .replytext').val(label + " . . . ").css({ 'color': '#bfc5cc' });
}
function onCommentClick(additionalInfo, item) {
    var url = "/api/query/json?q=jsocialReply&" + additionalInfo + "&d=" + $('#' + item + ' .replytext').val() + g_timeZone;
    $.getJSON(url, function (data) {
        $('#' + item + ' .comments').toggle('medium');
        $('#' + item + ' .replytext').val('');
        if (data.SourceType == "facebook") {
            $('#' + item + ' .commentList').append(renderComment(data));
        } else {
            $('#streams').prepend(renderTweet(data, false));
        }
    });
    $('#' + item + ' .replytext').val('');
}
function resetPostBox() {
    $('#statusUpdateText').val(g_postBoxText);
    var textarea = $('#statusUpdate textarea');
    textarea.css({ 'color': '#bfc5cc', 'height': '15px' });
    textarea.parent().css('height', '25px');
    $('#updateControls').css('height', '15px');
    $('#statusUpdate').css('height', '25px');
    var fbToggleButton = $('#toggleFbButton');
    var twToggleButton = $('#toggleTwButton');
    if (fbToggleButton.length > 0) {
        togglePostButton(fbToggleButton[0], "fb", '#postToFb', true);
    }
    if (twToggleButton.length > 0) {
        togglePostButton(twToggleButton[0], "twitter", '#postToTwitter', true);
    }
    $('#postCount').hide();
    $('.padding').hide();
    $('#shortenUrl').hide();
    $('#nothingToShorten').hide();
    $('#postStatusLabel')[0].src = "/content/images/post-button-reg.png";
}
function togglePostButton(toggleButton, toggleButtonPrefix, inputId, checked) {
    var input = $(inputId)[0];
    if (checked == null) {
        checked = !input.checked;
    }
    if (checked) {
        input.checked = true;
        toggleButton.src = "/content/images/" + toggleButtonPrefix + "-on-17x17.png";
    }
    else {
        input.checked = false;
        toggleButton.src = "/content/images/" + toggleButtonPrefix + "-off-17x17.png";
    }
}
function showAll() {
    g_inSearch = false;
    resetLeftButtons();
    var feedWrapper = $('#myfeed');
    feedWrapper.removeClass();
    feedWrapper.addClass('feedSelected');
    dt = new Date;
    g_timeZone = "&tz=" + dt.getTimezoneOffset();
    getStream(g_streamsUrl, true, false);
    resetSearchInfo();
    $('#pseudoSearchText').html('Search ...   ');
    $('#pseudoSearchText').css({ 'color': '#bfc5cc' });
    $('#pseudoSearch').css({ 'border-width': '1', 'border-style': 'solid', 'border-color': '#cccccc' });

}
function showRemembered(target) {
    resetLeftButtons();
    var targetWrapper = $(target);
    targetWrapper.removeClass();
    targetWrapper.addClass('rememberedSelected');
    g_inSearch = false;
    resetSearchInfo();
    var query = encodeURI(g_spindexQuery);
    getStream(g_streamsUrl + '&q=' + query + '&sq=false', true, false);
}
function resetLeftButtons() {
    var feedWrapper = $('#myfeed');
    feedWrapper.removeClass();
    feedWrapper.addClass('feedReg');
    var notificationsWrapper = $('#notification');
    notificationsWrapper.removeClass();
    notificationsWrapper.addClass($('#notificationsCount').html().length > 0 ? 'notificationsWithCount' : 'notificationsReg');
    //    var taggedWrapper = $('#remembered');
    //    taggedWrapper.removeClass();
    //    taggedWrapper.addClass('rememberedReg');
}
function showSearchInfo() {
    $('#streamResultsTitleBox').show();
    $('#streamResultsTitle').html("\"" + encodeHtml(g_searchText) + "\"");
}
function resetSearchInfo() {
    $('#streamResultsTitleBox').hide();
    g_searchText = '';
    g_searchText = '';
    var foundText = false;
    resetSavedSearchList($('#savedSearches li'));
    if (!foundText) {
        resetSavedSearchList($('#trendingTopics li'));
    }
    function resetSavedSearchList(list) {
        list.each(function (index) {
            var itemWrapper = $(this);
            var textCon = itemWrapper.find('span');
            if (textCon.hasClass('bold')) {
                textCon.removeClass('black bold');
                var subTrends = itemWrapper.find('ul');
                if (subTrends.length > 0) {
                    subTrends.remove();
                }
                foundText = true;
                return false;
            }
        });
    }
}
function resetFilterButtons() {
    var allFilter = $('#allFilter');
    allFilter.attr('src', '/content/images/all-on-22x22.png');
    allFilter.attr('alt', g_allFilterText[0]);
    var evernoteFilter = $('#evernoteFilter');
    if (g_feeds["evernote"]) {
        evernoteFilter.attr('src', '/content/images/evernote-off-22x22.png');
        evernoteFilter.attr('alt', g_evernoteFilterText[1]);
        evernoteFilter.show();
    }
    else {
        evernoteFilter.hide();
    }
    var fbFilter = $('#fbFilter');
    if (g_feeds["facebook"]) {
        fbFilter.attr('src', '/content/images/fb-off-22x22.png');
        fbFilter.attr('alt', g_facebookFilterText[1]);
        fbFilter.show();
    }
    else {
        fbFilter.hide();
    }
    var rssFilter = $('#rssFilter');
    if (g_feeds["rss"]) {
        rssFilter.attr('src', '/content/images/rss-off-22x22.png');
        rssFilter.attr('alt', g_rssFilterText[1]);
        rssFilter.show();
    }
    else {
        rssFilter.hide();
    }
    var twitterFilter = $('#twitterFilter');
    if (g_feeds["twitter"]) {
        twitterFilter.attr('src', '/content/images/twitter-off-22x22.png');
        twitterFilter.attr('alt', g_twitterFilterText[1]);
        twitterFilter.show('slow');
    }
    else {
        twitterFilter.hide();
    }
}
function search(text, origin) {
    g_inSearch = true;
    g_searchText = text; // .replace(/<b>/gi, '').replace(/<\/b>/gi, '');
    if (typeof (origin) != 'undefined') {
        g_searchOrigin = origin;
    }
    if ($('#allFilter').attr('src').indexOf('-off-') > 0) {
        resetFilterButtons();
    }
    $('#pseudoSearchText').html(truncate(g_searchText, 12));
    $('#pseudoSearchText').css({ 'color': 'black' });
    $('#pseudoSearch').css({ 'border-width': '2', 'border-style': 'solid', 'border-color': 'black' });
    updateStreams();
    $('#searchText').val('');
    if (g_searchText.indexOf('id:') == -1) {
        showSearchInfo();
        getBingResults(g_searchText.replace('#', ''));
    }
}
function renderNoWebResultsMessage() {
    $('#noWebResults').html(g_inSearch ? g_noSearchResultsForQueryText : g_noSearchResultsText);
    $('#noWebResults').show();
}
function onMoreRelatedHover(button) {
    if (button.src.indexOf("selected") == -1)
        button.src = "/content/images/more-related-button 2-searcharrow-1.png";
}
function onMoreRelatedOut(button) {
    if (button.src.indexOf("selected") == -1)
        button.src = "/content/images/more-related-button 2-searcharrow-0.png";
}
var prevSelected = null;
function onMoreRelatedClick(button, keywords) {
    if (button.src.indexOf("selected") != -1)
        return;
    if (prevSelected != null) {
        prevSelected.src = "more-related-button 2-searcharrow-0.png";
        $(prevSelected).removeClass("selected").fadeOut(100);
    }
    $(button).addClass("selected");
    button.src = "/content/images/more-related-button 2-searcharrow-1.png";
    prevSelected = button;
    getBingResults(keywords.replace(/#/g, ''));
}
function getBingResults(query, isKeywordToggled, numTries) {
    if (typeof (isKeywordToggled) == 'undefined') {
        isKeywordToggled = false;
    }
    if (!isKeywordToggled) {
        $('#synopsisLoader').show();
        $('#synopsis').hide();
        $('#webResults').hide();
        $('#noWebResults').hide();
    }
    $.ajax({
        url: g_bingGeneralQueryUrl + encodeURI(query),
        dataType: 'jsonp',
        jsonp: 'JsonCallback',
        success: function (data) {
            $('#synopsisLoader').hide();
            renderBingResults(query, isKeywordToggled, data.SearchResponse);
            $('#webResults').show();
        },
        error: function (xmlHttp, error, ex) {
            if (typeof (numTries) == 'undefined' || numTries < 5) {
                getBingResults(query, isKeywordToggled, (numTries) == 'undefined' ? 1 : numTries + 1);
            }
            else {
                $('#synopsisLoader').hide();
                renderWebResultsQuery(query);
                renderNoWebResultsMessage();
                $('#webResults').show();
            }
        }
    });
}

var g_nPhotos;
var g_nPixToMove = 0;
function movePhotos(n) {
    var current = parseInt($(this).css("left"));
    g_itemMoving = n;
    $(this).animate({ "left": current - g_nPixToMove }, "medium", "swing", doneScroll);
}
function onPhotosRight() {
    if (g_currentRightmostPhoto >= g_nPhotos - 1 || g_countScrolling > 0)
        return;
    var width = 0;
    var i = 0;
    var nImagesToMove = 0;
    var children = $("#photoContainer div");
    for (i = g_currentRightmostPhoto + 1; i < children.length; i++) {
        var widthNext = parseInt($(children[i]).css('width'));
        if (width + widthNext > g_photoSpace)
            break;
        width += widthNext;
        nImagesToMove++;
    }
    g_nPixToMove = parseInt($(children[g_currentRightmostPhoto + 1]).css('left'));
    g_countScrolling = g_nPhotos;
    $("#photoContainer").children().each(movePhotos);
    g_currentLeftmostPhoto = g_currentRightmostPhoto + 1;
    g_currentRightmostPhoto = g_currentLeftmostPhoto + nImagesToMove;

    if (g_currentRightmostPhoto >= g_nPhotos - 1) {
        document.getElementById("photoRight").src = "/content/images/RightOff.png";
    } else
        document.getElementById("photoRight").src = "/content/images/RightReg.png";
    document.getElementById("photoLeft").src = "/content/images/leftReg.png";
}
function onPhotosLeft() {
    if (g_currentLeftmostPhoto <= 0 || g_countScrolling > 0)
        return;
    var container = $("#photoContainer");
    var size = container.children().size();
    var width = 0;
    var nImagesToMove = 0;
    var children = $("#photoContainer div");
    for (var i = g_currentLeftmostPhoto - 1; i >= 0; i--) {
        var widthNext = parseInt($(children[i]).css('width'));
        if (width + widthNext >= g_photoSpace)
            break;
        width += widthNext;
        nImagesToMove++;
    }
    g_nPixToMove = parseInt($(children[g_currentLeftmostPhoto - nImagesToMove]).css('left'));
    g_countScrolling = g_nPhotos;
    container.children().each(movePhotos);
    g_currentRightmostPhoto = g_currentLeftmostPhoto - 1;
    g_currentLeftmostPhoto = g_currentRightmostPhoto - nImagesToMove;
    if (g_currentLeftmostPhoto <= 0)
        document.getElementById("photoLeft").src = "/content/images/leftOff.png";
    else
        document.getElementById("photoLeft").src = "/content/images/leftReg.png";

    document.getElementById("photoRight").src = "/content/images/rightReg.png";
}

var g_itemMoving = 0;
function doneScroll() {
    if (g_itemMoving == g_countScrolling - 1)
        g_countScrolling = 0;
}
function moveLeft(n) {
    var current = parseInt($(this).css("left"));
    g_itemMoving = n;
    $(this).animate({ "left": current - g_itemsToShow * (g_blockWidth + g_interItemSpace) }, "medium", "swing", doneScroll);

}
function moveRight(n) {
    var current = parseInt($(this).css("left"));
    g_itemMoving = n;
    $(this).animate({ "left": current + g_itemsToShow * (g_blockWidth + g_interItemSpace) }, "medium", "swing", doneScroll);
}
function onLinksLeft() {
    if (currentLeftmostLink <= 0 || g_countScrolling > 0) {
        return;
    }
    var children = $("#linkContainer").children();
    g_countScrolling = children.length;
    children.each(moveRight);
    currentLeftmostLink -= g_itemsToShow;
    if (currentLeftmostLink <= 0) {
        document.getElementById("linkLeft").src = "/content/images/leftOff.png";
    } else
        document.getElementById("linkLeft").src = "/content/images/leftReg.png";
    document.getElementById("linkRight").src = "/content/images/rightReg.png";
}
function onLinksRight() {
    var children = $("#linkContainer").children();
    var numItems = children.size();
    if (currentLeftmostLink >= numItems - g_itemsToShow || g_countScrolling > 0)
        return;
    g_countScrolling = numItems;
    children.each(moveLeft);
    currentLeftmostLink += g_itemsToShow;
    if (currentLeftmostLink >= numItems - g_itemsToShow)
        document.getElementById("linkRight").src = "/content/images/rightOff.png";
    else
        document.getElementById("linkRight").src = "/content/images/rightReg.png";

    document.getElementById("linkLeft").src = "/content/images/leftReg.png";
}
var currentLeftmostNews = 0;
function onNewsLeft() {
    if (currentLeftmostNews <= 0 || g_countScrolling > 0)
        return;
    g_countScrolling = $("#newsContainer").children().length;
    $("#newsContainer").children().each(moveRight);
    currentLeftmostNews -= g_itemsToShow;
    if (currentLeftmostNews <= 0) {
        document.getElementById("newsLeft").src = "/content/images/leftOff.png";
    } else
        document.getElementById("newsLeft").src = "/content/images/leftReg.png";
    document.getElementById("newsRight").src = "/content/images/rightReg.png";
}
function onNewsRight() {
    var container = $("#newsContainer");
    var numItems = container.children().size();
    if (currentLeftmostNews >= numItems - g_itemsToShow || g_countScrolling > 0)
        return;
    g_countScrolling = numItems;
    container.children().each(moveLeft);
    currentLeftmostNews += g_itemsToShow;
    if (currentLeftmostNews >= numItems - g_itemsToShow)
        document.getElementById("newsRight").src = "/content/images/rightOff.png";
    else
        document.getElementById("newsRight").src = "/content/images/rightReg.png";

    document.getElementById("newsLeft").src = "/content/images/leftReg.png";
}
function onLinkRightHover() {
    var numItems = $("#linkContainer").children().size();
    if (currentLeftmostLink >= numItems - g_itemsToShow)
        document.getElementById("linkRight").src = "/content/images/rightOff.png";
    else
        document.getElementById("linkRight").src = "/content/images/rightHover.png";
}
function onLinkRightOut() {
    var numItems = $("#linkContainer").children().size();
    if (currentLeftmostLink >= numItems - g_itemsToShow)
        document.getElementById("linkRight").src = "/content/images/rightOff.png";
    else
        document.getElementById("linkRight").src = "/content/images/rightReg.png";
}
function onLinkLeftHover() {
    if (currentLeftmostLink <= 0)
        document.getElementById("linkLeft").src = "/content/images/leftOff.png";
    else
        document.getElementById("linkLeft").src = "/content/images/leftHover.png";
}
function onLinkLeftOut() {
    if (currentLeftmostLink <= 0)
        document.getElementById("linkLeft").src = "/content/images/leftOff.png";
    else
        document.getElementById("linkLeft").src = "/content/images/leftReg.png";
}
function onPhotoRightHover() {
    var numItems = $("#photoContainer").children().size();
    if (g_currentLeftmostPhoto >= numItems - 3)
        document.getElementById("photoRight").src = "/content/images/rightOff.png";
    else
        document.getElementById("photoRight").src = "/content/images/rightHover.png";
}
function onPhotoRightOut() {
    var numItems = $("#photoContainer").children().size();
    if (g_currentLeftmostPhoto >= numItems - 3)
        document.getElementById("photoRight").src = "/content/images/rightOff.png";
    else
        document.getElementById("photoRight").src = "/content/images/rightReg.png";
}
function onPhotoLeftHover() {
    if (g_currentLeftmostPhoto <= 0)
        document.getElementById("photoLeft").src = "/content/images/leftOff.png";
    else
        document.getElementById("photoLeft").src = "/content/images/leftHover.png";
}
function onPhotoLeftOut() {
    if (g_currentLeftmostPhoto <= 0)
        document.getElementById("photoLeft").src = "/content/images/leftOff.png";
    else
        document.getElementById("photoLeft").src = "/content/images/leftReg.png";
}
function onNewsRightHover() {
    var numItems = $("#newsContainer").children().size();
    if (currentLeftmostNews >= numItems - g_itemsToShow)
        document.getElementById("newsRight").src = "/content/images/rightOff.png";
    else
        document.getElementById("newsRight").src = "/content/images/rightHover.png";
}
function onNewsRightOut() {
    var numItems = $("#newsContainer").children().size();
    if (currentLeftmostNews >= numItems - g_itemsToShow)
        document.getElementById("newsRight").src = "/content/images/rightOff.png";
    else
        document.getElementById("newsRight").src = "/content/images/rightReg.png";
}
function onNewsLeftHover() {
    if (currentLeftmostNews <= 0)
        document.getElementById("newsLeft").src = "/content/images/leftOff.png";
    else
        document.getElementById("newsLeft").src = "/content/images/leftHover.png";
}
function onNewsLeftOut() {
    if (currentLeftmostNews <= 0)
        document.getElementById("newsLeft").src = "/content/images/leftOff.png";
    else
        document.getElementById("newsLeft").src = "/content/images/leftReg.png";
}
function onFeedClick() {
    showAll();
    $('#synopsis').show();
    $('#webResults').hide();
}
function getSynopsis(numTries) {
    if ($('#synopsis').is(':hidden'))
        return;
    $.ajax({
        url: g_synopsisUrl,
        dataType: 'json',
        beforeSend: function () {
            if (g_inSearch) {
                return false;
            }
            $('#webResults').hide();
        },
        success: function (data) {
            $('#synopsisLoader').hide();
            populateSavedSearches(data.SavedQueries);
            populateTrending(data.TrendingTopics);
            populateRecentPhotos(data.Photos);
            populateSharedLinks(data.SharedLinks);
            populateTrendingNews(data.TrendingNews);
            showNewItemsNotifications(data.NewRecentQueryItemsCount);
            showNotificationsCount(data.NotificationsCount);
            $('#synopsis').show();
            $('.moreRelatedButton').removeClass('selected');
            setLeftColumnMargin();
        },
        error: function (xmlHttp, error, ex) {
            if (typeof (numTries) == 'undefined' || numTries < 10) {
                getSynopsis(typeof (numTries) == 'undefined' ? 1 : numTries + 1);
            }
            else {
                $('#synopsisLoader').hide();
            }
        }
    });
}
function setLeftColumnMargin() {
    var leftColumn = $('#contentNoScroll .leftColumn');
    var leftColumnHeight = 0;
    if (leftColumn.length > 0) {
        leftColumnHeight = parseInt(leftColumn.css('height'));
    }
    var marginRight = 20;
    if ($('#leftStream')[0].clientHeight >= leftColumnHeight) {
        marginRight = 0;
    }
    $('#pseudoSearch').css('margin-right', marginRight);
    $('#savedSearches').css('margin-right', marginRight);
    $('#trendingTopics').css('margin-right', marginRight);
    $('#notification').css('margin-right', marginRight);
    $('#remembered').css('margin-right', marginRight);
    $('#myfeed').css('margin-right', marginRight);
}
function getStream(url, resetButtons, shouldAppend, numTries) {
    var urlGetStream = url + g_timeZone;
    $.ajax({
        url: urlGetStream,
        dataType: 'json',
        beforeSend: function () {
            $('#streamLoader').show();
            $('#getOlderItemsBox').remove();
            $('.twitterPublic').remove();
            $('#noContent').hide();
            $('#newItemImage').attr('src', '/content/images/refresh-button-no-new.png');
            $('#lastItemDate').remove();
            $('#streams').html('');
        },
        success: function (data) {
            if (data != null && data.Stream != null) {
                renderSubTrends(data.Trends);
                renderJSONStream(data.Stream, shouldAppend, false);
                $('#streams').append("<li id='getOlderItemsBox' class='link' onclick='getOlderItems()'>Check for older items</li>");
                $('#streamLoader').hide();
                if ($('#streams li').length > 0) {
                    $('#streams a[rel="external"]').map(function () { $(this).attr('target', '_blank'); });
                    $('#streams .status .description').map(function () {
                        var titleCon = $(this);
                        titleCon.html(addLinks(titleCon.html()));
                    });
                    if (resetButtons) {
                        resetFilterButtons();
                    }
                    TwitterReporting.BindTweetClicks();
                }
                else {
                    ShowNoContentMessage();
                }
                searchTwitterPublic(urlGetStream);
                $('#streams li').hover(
                    function () {
                        $(this).find('.moreRelatedButton').fadeIn(300);
                    },
                    function () {
                        $(this).find('.moreRelatedButton').not('.selected').hide();
                    }
                );
            }
            else {
                $('#streamLoader').hide();
                ShowNoContentMessage();
                searchTwitterPublic(urlGetStream);
            }
        },
        error: function (xmlHttp, error, ex) {
            if (typeof (numTries) == 'undefined' || numTries < 10) {
                getStream(url, resetButtons, shouldAppend, typeof (numTries) == 'undefined' ? 1 : numTries + 1);
            }
            else {
                $('#streamLoader').hide();
                ShowNoContentMessage();
                searchTwitterPublic(urlGetStream);
            }
        }
    });
}
function searchTwitterPublic(urlGetStream) {
    if (typeof (g_searchText) != 'undefined' && g_searchText != "" && urlGetStream.indexOf(g_twitterPublicUrl) != 0) {
        var urlPublic = g_twitterPublicUrl + "&qr=" + encodeURI(g_searchText) + g_timeZone;
        $.getJSON(urlPublic, {}, function (publicTweets, status) {
            if (status == "success") {
                $('#streams').append("<li id='twitterPublicLabel'>Public tweets on: <span class='bold'>" + g_searchText + "</span></li>");
                renderJSONStream(publicTweets, true, true);
                if ($('#streams li').length > 0) {
                    $('#streams a[rel="external"]').map(function () { $(this).attr('target', '_blank'); });
                    $('#streams .status .description').map(function () {
                        if ($(this).html().indexOf('url-link') == -1) {
                            var titleCon = $(this);
                            titleCon.html(addLinks(titleCon.html()));
                        }
                    });
                    TwitterReporting.BindTweetClicks();
                }
            }
            else {
                // TODO Todd: handle error case
            }
        });
    }
}
function addLinks(valueIn) {
    var valueOut = '';
    while (valueIn.length > 0) {
        var start = valueIn.indexOf(' http://');
        if (start == -1)
            start = valueIn.indexOf('\nhttp://');
        var end = valueIn.indexOf(' ', start + 1);
        if (start == -1) {
            start = valueIn.indexOf('(http://');
            if (start != -1) {
                end = valueIn.indexOf(')', start + 1);
            } else {
                if (valueIn.indexOf('http://') == 0) {
                    start = 0;
                }
            }
        }
        if (end == -1) {
            end = valueIn.length;
        } else if (valueIn.charAt(end) == '.') {
            end -= 1;
        }
        if (start != -1) {
            start = valueIn.indexOf('http://', start) == start + 1 ? start + 1 : start;
            valueOut += valueIn.substr(0, start);
            var urlString = end == -1 ? valueIn.substring(start) : valueIn.substring(start, end);
            valueOut += "<a class='url-link' href='" + urlString + "' rel='external' target='_blank'>" + urlString + "</a>";
            valueIn = (end == -1) ? '' : valueIn.substr(end);
        } else {
            valueOut += valueIn;
            valueIn = '';
        }
    }
    return valueOut;
}
function ShowNoContentMessage() {
    var noContent = $('#noContent');
    if (IsNullOrEmpty(g_searchText))
        noContent[0].innerText = g_NoStreamYet;
    else
        noContent[0].innerText = g_NoMatch;
    noContent.show();
}
function renderSubTrends(trends) {
    if (g_savedSearchContainer == null || trends.length == 0) {
        return;
    }
    g_savedSearchContainer.append('<ul class="subTrend"></ul>');
    var subTrendsCon = g_savedSearchContainer.find('.subTrend');
    for (var i = 0; i < trends.length; i++) {
        subTrendsCon.append(renderSavedSearchItem(trends[i].Topic, trends[i].Count, 'Trending Topic', 'deleteTrend(this)', true, g_searchText));
    }
    g_savedSearchContainer = null;
}
function renderJSONStream(data, shouldAppend, isPublic) {
    if (data == null)
        return;
    var stream = $('#streams');
    if (!shouldAppend)
        stream.html("");
    for (var i = 0; i < data.length; i++) {
        var item = data[i];
        if (item == null)
            continue;
        g_lastItemDate = item.PublishedTicks;
        switch (item.SourceType) {
            case 'facebook':
                stream.append(renderPost(item));
                break;
            case 'twitter':
                stream.append(renderTweet(item, isPublic));
                break;
            case 'rss':
                stream.append(renderRSS(item));
                break;
            case 'evernote':
                break;
            default:
                stream.append('<li>format not yet supported.</li>');
                break;
        }
    }
}
function borderColor(item) {
    if (item.IsRetweet || item.IsRetweetMe)
        return "#91ced7";
    else if (item.IsDirectMessage)
        return "#ff9e7e";
    else if (item.IsMention)
        return "#6be2f4";
    else if (item.IsRemembered)
        return "#a8e393";
    else
        return "White";
}
function typeMessage(item) {
    if (item.IsRetweet || item.IsRetweetMe)
        return "<div class='typeMessage'>RETWEET</div>";
    else if (item.IsDirectMessage)
        return "<div class='typeMessage'>DIRECT MSG</div>";
    else if (item.IsMention)
        return "<div class='typeMessage'>MENTION</div>";
    //    else if (item.IsRemembered)
    //        return "<div class='typeMessage'>TAGGED</div>";
    else
        return '';
}
function renderPost(item) {
    var result = '<li class="facebook" id="' + item.Id + '" style="border-left: 2px solid ' + borderColor(item) + '">';
    if (item.Keywords != null) {
        var keywords = item.Keywords.replace(/,/g, ' ').replace(/'/g, '');
        result += '<img title="Search for: ' + keywords + '" onmouseover="onMoreRelatedHover(this)" onmouseout="onMoreRelatedOut(this)" onclick="onMoreRelatedClick(this, \'' + keywords + '\')" class="moreRelatedButton" src="/content/images/more-related-button 2-searcharrow-0.png">';
    }
    result += '<div class="liPad">';
    result += addAuthorPictureAndType(item);
    result += '<div class="status"><img class="middle" src="/content/images/face-12x12.png"> ';
    if (item.Author != null)
        result += '<a href="http://www.facebook.com/' + item.ScreenName + '" class="author-link" target="_blank">' + item.Author + '</a> ';
    if (item.OriginalUser != null)
        result += '<span class="bold"> -> ' + item.OriginalUser + ' </span>';
    if (item.Description != null)
        result += '<span class="description">' + renderDescription(item.Description, false) + '</span>';
    if (item.PublishedDate != null)
        result += '&nbsp;<span class="publishedDate">' + item.PublishedDate + '</span>';
    var attachments = renderAttachments(item);
    if (!IsNullOrEmpty(attachments))
        result += attachments;
    result += renderComments(item);
    var additionalInfo = "source=facebook&replyTo=" + item.ParentId;
    result += '<div class="itemActionCon"><span class="action" onclick="replyToItem(this, \'' + item.Id + '\', \'' + additionalInfo + '\')">Comment</span>';
    if (item.CommentCount > 0) {
        result += '<span class="actionCount">\\' + item.CommentCount + '</span>';
    }
    result += '<span class="grey"> | </span><span onclick="likeFacebookItem(this, \'' + item.ParentId + '\')"><span class="action">Like</span><span class="actionCount">';
    if (item.LikesCount > 0)
        result += '\\' + item.LikesCount;
    result += '</span></span>';
    result += "<span class='grey'> | </span><span class='action' onclick='shareItem(this)'>" + g_shareText + "</span></div>";
    //<span class='grey'>   | </span><span class='action' onclick='rememberItem(this)'>" + g_setTagText + "</span>";
    result += '<span class="parentId">' + item.ParentId + '</span></div></div></li>';
    return result;
}
function renderTweet(item, isPublic) {
    var result = '<li class="hTweet" id="' + item.Id + '"';
    if (isPublic)
        result += ' class="twitterPublic"';
    result += ' style="border-left: 2px solid ' + borderColor(item) + '">';
    if (!IsNullOrEmpty(item.Keywords)) {
        var keywords = item.Keywords.replace(/,/g, ' ').replace(/'/g, '').replace(/@\w+/g, '');
        result += '<img title="Search for: ' + keywords + '" onmouseover="onMoreRelatedHover(this)" onmouseout="onMoreRelatedOut(this)" onclick="onMoreRelatedClick(this, \'' + keywords + '\')" class="moreRelatedButton" src="/content/images/more-related-button 2-searcharrow-0.png">';
    }
    result += '<div class="liPad"><span class="tweet-id">' + item.TweetId + '</span>';
    result += addAuthorPictureAndType(item);
    result += '<div class="status"><img class="middle" src="/content/images/twit-12x12.png"> ';
    if (item.Author != null)
        result += '<a href="http://twitter.com/' + item.ScreenName + '" class="author-link" target="_blank">' + item.ScreenName + '</a> ';
    if (item.Description != null)
        result += '<span class="description">' + renderDescription(item.Description, true) + '</span>';
    if (item.PublishedDate != null)
        result += '&nbsp;<span class="publishedDate">' + item.PublishedDate + '</span>';
    var attachments = renderAttachments(item);
    if (!IsNullOrEmpty(attachments))
        result += attachments;
    var additionalInfo = "source=twitter&replyTo=" + item.ScreenName + "&tweetId=" + item.TweetId;
    result += '<div class="comments" style="display:none;">' + addReplyTextArea(item.Id, "Reply", additionalInfo) + '</div>';
    result += '<div class="itemActionCon"><span class="action" onclick="replyToItem(this, \'' + item.Id + '\', \'' + additionalInfo + '\')">Reply</span>';
    result += '<span class="grey"> | </span><span class="action" onclick="makeTwitterItemFavorite(this, \'' + item.TweetId + '\')">Favorite</span>';
    result += '<span class="grey"> | </span><span class="action" onclick="retweetItem(this, \'' + item.TweetId + '\')">Retweet</span>';
    result += '<span class="grey"> | </span><span class="action" onclick="shareItem(this)">' + g_shareText + '</span></div>';
    // '</span><span class="grey"> | </span><span class="action" onclick="rememberItem(this)">' + g_setTagText + '</span></div>';
    result += '<span class="parentId">' + item.ParentId + '</span></div></div></li>';
    TwitterReporting.LogTweetDisplay(item.TweetId);
    return result;
}
function renderDescription(description, isTweet) {
    var d = description;
    if (isTweet) {
        d = d.replace(/(&#35;\w+)/g, "<span class='hash-mention-link' onclick='search(\"$1\", \"hashTag\")'>$1</span>");
        d = d.replace(/&#64;(\w+)/g, "<a class='at-mention-link' href='http://twitter.com/$1' target='_blank'>@$1</a>");
    }
    d = highlightSearchTerm(d);
    return d;
}
function highlightSearchTerm(value) {
    if (g_searchText != "") {
        var searchStr = '"&#35;' + g_searchText + '", "hashTag"';
        var reSearch = new RegExp(searchStr, "ig");
        value = value.replace(reSearch, "#HASHSEARCH#");
        var re = new RegExp("(" + g_searchText + ")", "ig");
        value = value.replace(re, "<b>$1</b>");
        value = value.replace(/#HASHSEARCH#/g, '"&#35;' + g_searchText + '", "hashTag"');
    }
    return value;
}
function renderRSS(item) {
    var result = '<li class="rss" id="' + item.Id + '" style="border-left: 2px solid ' + borderColor(item) + '">';
    if (item.Keywords != null) {
        var keywords = item.Keywords.replace(/,/g, ' ').replace(/'/g, '');
        result += '<img title="Search for: ' + keywords + '" onmouseover="onMoreRelatedHover(this)" onmouseout="onMoreRelatedOut(this)" onclick="onMoreRelatedClick(this, \'' + keywords + '\')" class="moreRelatedButton" src="/content/images/more-related-button 2-searcharrow-0.png">';
    }
    result += '<div class="liPad">';
    result += addAuthorPictureAndType(item);
    if (item.Title != null)
        result += '<div class="status"><a class="author-link" target="_blank" href="' + item.Link + '">' + highlightSearchTerm(item.Title) + '</a></br>';
    if (item.Description != null)
        result += '<span class="description">' + highlightSearchTerm(item.Description) + '</span>';
    var attachments = renderAttachments(item);
    if (!IsNullOrEmpty(attachments))
        result += attachments;
    if (item.PublishedDate != null)
        result += '<div class="publishedDate">' + item.PublishedDate + '</div>';
    result += '<div class="itemActionCon"><span class="action" onclick="shareItem(this)">' + g_shareText + '</span></div>';
    // '</span><span class="grey"> | </span><span class="action" onclick="rememberItem(this)">' + g_setTagText + '</span></div>';
    result += '<span class="parentId">' + item.ParentId + '</span></div></div></li>';
    return result;
}
function renderAttachments(item) {
    if ((IsNullOrEmpty(item.AttachmentMedia) || item.AttachmentMedia.length == 0) &&
        IsNullOrEmpty(item.AttachmentCaption) && IsNullOrEmpty(item.AttachmentDescription) && IsNullOrEmpty(item.AttachmentName))
        return null;
    var result = '<div class="attachment">';
    var attachmentHref = '';
    if (item.AttachmentMedia != null) {
        for (var attachmentIndex in item.AttachmentMedia) {
            var attachment = item.AttachmentMedia[attachmentIndex];
            if (attachmentHref.length == 0)
                attachmentHref = attachment.Href;
            if (attachment.MediaPreview != null) {
                if (attachment.MediaSource != null)
                    result += '<div cursor="hand"><img class="mediaPreview" src="' + attachment.MediaPreview + '"  onclick="openPopup(event, \'' + attachment.MediaSource + '\', \'-1\', \'-1\', \'\' )"</div>';
                else {
                    if (attachment.HrefHeight > 300 && attachment.HrefWidth > 300) {
                        result += '<div cursor="hand"><img class="mediaPreview" src="' + attachment.MediaPreview + '"  onclick="openPopup(event, \'' + attachment.MediaPreview + "\', \'" + attachment.HrefHeight + "\', \'" + attachment.HrefWidth + "\', \'\')\"/></div>";
                    }
                    else {
                        result += '<div><a target="_blank" href="' + attachment.Href + '"><img class="mediaPreview" src="' + attachment.MediaPreview + '"/></a></div>';
                    }
                }
            }
        }
    }
    if (item.AttachmentName != null) {
        if (attachmentHref.length > 0) {
            result += '<a class="greyLink bold" target="_blank" href="' + attachmentHref + '">' + highlightSearchTerm(item.AttachmentName) + '</br></a>';
        }
        else {
            result += '<span class="grey bold">' + highlightSearchTerm(item.AttachmentName) + '</br></span>';
        }
    }
    if (item.AttachmentCaption != null || item.AttachmentDescription != null) {
        result += '<span class="grey attachmentText">';
        if (item.AttachmentCaption != null)
            result += highlightSearchTerm(item.AttachmentCaption);
        //        if (item.AttachmentCaption != null && item.AttachmentDescription != null)
        //            result += '</br>';
        if (item.AttachmentDescription != null)
            result += highlightSearchTerm(item.AttachmentDescription);
        result += '</span>';
    }
    result += '</div>';
    return result;
}
function addReplyTextArea(id, label, additionalInfo) {
    var result = "<div class='replydiv'><textarea class='replytext' cols='40' onkeyup='onCommentAreaKeyup()'  onclick='onCommentAreaClick(\"" + id + "\",\"" + label + "\")'>" + label + " . . . </textarea><br />";
    result += "<div class='postCount'></div>";
    result += "<a href='#' style='color: #de6b00;' onclick='onCommentCancelClick(\"" + label + "\", \"" + id + "\")'>Clear</a> | <a href='#' style='color: #de6b00;margin-right: 40px' onclick='onCommentClick(\"" + additionalInfo + "\", \"" + id + "\")'>" + label + "</a></div>";
    return result;
}
function renderComments(item) {
    var result = '<div class="comments" style="display:none;"><ul class="commentList">';
    if (item.CommentCount > 0) {
        for (var commentIndex in item.Comments) {
            result += renderComment(item.Comments[commentIndex]);
        }
    }
    result += '</ul>';
    var remaining = item.CommentCount - item.Comments.length;
    if (remaining > 0) {
        result += '<div class="getMoreCommentsBox" onclick="getMoreComments(this, \'' + item.Id + '\')">Show ' + remaining + ' more comments...</div>';

    }
    var additionalInfo = "source=facebook&replyTo=" + item.ParentId;
    result += addReplyTextArea(item.Id, "Comment", additionalInfo);
    result += '</div>';
    return result;
}
function renderComment(comment) {
    var result = '<li class="comment"><img class="middle" src="/content/images/feedicons-comments.png" height="12" width="12"> ';
    if (comment.Author != null)
        result += '<span class="author-link">' + comment.Author + '</span>';
    if (comment.Description != null)
        result += ' <span class="description">' + comment.Description + '</span>';
    if (comment.PublishedDate != null)
        result += '<br /><span class="publishedDate">' + comment.PublishedDate + '</span>';
    result += '</li>';
    return result;
}
function getDomain(url) {
    return url.split('/')[2];
}
function toggleWebSearchKeyword(keywordCon) {
    var keywordWrapper = $(keywordCon);
    if (keywordWrapper.hasClass('lightGrey')) {
        keywordWrapper.removeClass('lightGrey');
    }
    else {
        keywordWrapper.addClass('lightGrey');
    }
    var newQuery = $.trim($('#webResultsQuery a').map(function () { return $(this).hasClass('lightGrey') ? '' : this.innerHTML; }).get().join(' '));
    getBingResults(newQuery, true);
}
function renderWebResultsQuery(query) {
    var queryCon = $('#webResultsQuery');
    queryCon.html('');
    var keywords = query.split(' ');
    if (keywords.length == 1) {
        queryCon.html(encodeHtml(query));
        return;
    }
    for (var i = 0; i < keywords.length; ++i) {
        queryCon.append("<a onclick='toggleWebSearchKeyword(this)' title='" + g_keywordToggleAltText + keywords[i] + "'>" + encodeHtml(keywords[i]) + "</a> ");
    }
}
function renderBingResults(query, isKeywordToggled, response) {
    if (!isKeywordToggled) {
        renderWebResultsQuery(query);
    }
    $('#webResultsCol1').html('');
    $('#webResultsCol2').html('');
    var news = response.News;
    var hasNews = false;
    if (typeof (news) != 'undefined' && news.Total > 0) {
        hasNews = renderBingNewsResults(news.Results);
    }
    var web = response.Web;
    var hasWeb = false;
    if (typeof (web) != 'undefined' && web.Total > 0) {
        hasWeb = renderBingWebResults(web.Results);
    }
    if (!hasNews && !hasWeb) {
        renderNoWebResultsMessage();
    }
}
function renderWebItemActionVerbs(title, url) {
    return "<div class='itemActionCon'><a class='action' onclick='shareWebLink(this)'>" + g_shareText + "</a></div>";
    // <span class='grey'> | </span><a class='action' onclick='rememberWebLink(this)'>" + g_setTagText + "</a></div>";
}
function renderWebItem(title, description, url) {
    return "<li><a href='" + url + "' class='author-link' target='_blank' rel='external'>" + highlightSearchTerm(title) + "</a><div class='description'>" + highlightSearchTerm(description) + "</div><span class='grey'>" + getDomain(url) + "</span>" + renderWebItemActionVerbs(title, url) + "</li>";
}
function renderBingNewsResults(newsResults) {
    if (newsResults.length == 0) {
        return false;
    }
    for (var i = newsResults.length - 1; i >= 0; --i) {
        var news = newsResults[i];
        var container = (i % 2 == 0) ? $('#webResultsCol2') : $('#webResultsCol1');
        container.append(renderWebItem(encodeHtml(news.Title), encodeHtml(news.Snippet), news.Url));
    }
    return true;
}
function renderBingWebResults(webResults) {
    if (webResults.length == 0) {
        return false;
    }
    for (var i = webResults.length - 1; i >= 0; --i) {
        var web = webResults[i];
        var container = (i % 2 == 0) ? $('#webResultsCol1') : $('#webResultsCol2');
        container.append(renderWebItem(encodeHtml(web.Title), encodeHtml(web.Description), web.Url));
    }
    return true;
}
function showNewItemsNotifications(newItemsCount) {
    if (!g_inSearch && newItemsCount > 0) {
        $('#newItemsNotification').show();
        $('#newItemImage').attr('src', '/content/images/refresh-button-new-ready.png');
    }
}
function showNotificationsCount(count) {
    if (!g_inSearch && count > 0) {
        $('#notification').removeClass();
        $('#notification').addClass('notificationsWithCount');
        $('#notificationsCount').text(" " + count + " ");
    }
}
function onNewItemHover() {
    var newItemImage = $('#newItemImage');
    if (!g_inSearch && newItemImage.attr('src') == '/content/images/refresh-button-new-ready.png') {
        newItemImage.attr('src', '/content/images/refresh-button-new-ready-hover.png');
    }
}
function onNewItemOut() {
    var newItemImage = $('#newItemImage');
    if (!g_inSearch && newItemImage.attr('src') == '/content/images/refresh-button-new-ready-hover.png') {
        newItemImage.attr('src', '/content/images/refresh-button-new-ready.png');
    }
}
function appendAuthorPicture(note) {
    var picture = IsNullOrEmpty(note.author_picture) ? "/content/images/silhouette.png" : note.author_picture;

    return '<div class="authorPicture"><img class="avatar-link" src="' + picture + '"' +
                            'alt="' + note.author + '" /></div>';
}
function addAuthorPictureAndType(item) {
    var picture = item.Thumbnail;
    if (IsNullOrEmpty(picture))
        picture = (item.SourceType == 'rss') ? '/content/images/rssicon.png' : '/content/images/silhouette.png';

    var result = '<div class="authorPicture"><img class="avatar-link" src="' + picture + '"' +
                            'alt="' + item.Author + '" />';
    var msg = typeMessage(item);
    if (!IsNullOrEmpty(msg))
        result += msg;
    result += '</div>';
    return result;
}
function IsNullOrEmpty(string) {
    return string == null || string.length == 0;
}
function addNotificationBody(note) {
    if (!IsNullOrEmpty(note.text))
        return note.text;
    else if (!IsNullOrEmpty(note.title_html))
        return processTitleHTML(note.title_html);
    return '';
}
function streamNotification(note) {
    var listItem;

    if (!IsNullOrEmpty(note.original_user) && !IsNullOrEmpty(note.original_text)) {
        listItem = '<div class="status"><img class="middle" src="/content/images/face-12x12.png">';
        listItem += ' <a class="author-link gray" target="_blank" href="http://www.facebook.com/' + note.screen_name + '" >' + note.original_user +
                    '</a> <span class="description gray">' + note.original_text + '</span>';
        if (!IsNullOrEmpty(note.author_picture))
            listItem += '<div class="comment notificationComment"><div class="commentPhoto"><img class="avatar-link" src="' + note.author_picture + '" alt="' + note.author + '" /></div>';
        else
            listItem += '<div class="comment">';
        listItem += '<div class="status"><img class="middle" src="/content/images/feedicons-comments.png" height="12" width="12"> <span class="author-link black">' + note.author + '</span> ';
        listItem += addNotificationBody(note) + '&nbsp;<span class="publishedDate">' + note.modified + '</span></div></div>';

    } else {
        listItem = appendAuthorPicture(note) + '<div class="status"><img class="middle" src="/content/images/face-12x12.png" height="12" width="12">';
        listItem += ' <span class="author-link">' + note.author + '</span> ';
        listItem += addNotificationBody(note) + '&nbsp;<div class="publishedDate">' + note.modified + '</div></div>';
    }
    var additionalInfo = "source=facebook&replyTo=" + note.parent_id;
    listItem += addActions(note);
    listItem += '</div>';
    return listItem;
}
function facebookLike(note) {
    var listItem = appendAuthorPicture(note) + '<div class="status">';
    listItem += '<img class="middle" src="/content/images/face-12x12.png"> <a target="_blank" href="http://www.facebook.com/' + note.screen_name + ' "class="author-link">' + note.author + '</a>';
    listItem += '<span class="description">' + note.title_html + '</span>';
    if (!IsNullOrEmpty(note.modified))
        listItem += '&nbsp;<span class="publishedDate">' + note.modified + '</span>';
    listItem += addActions(note);
    listItem += '</div>';
    return listItem;
}
function facebookPhoto(note) {
    var listItem = appendAuthorPicture(note) + '<div class="status">';
    var noText = IsNullOrEmpty(note.text);
    if (noText)
        listItem += '<div class="notificationMessage">';
    listItem += '<img class="middle" src="/content/images/face-12x12.png"> <a class="author-link" target="_blank" href="http://www.facebook.com/' + note.screen_name + '">' + note.author + '</a>';
    if (noText)
        listItem += '<span class="description">';
    else
        listItem += '<span class="description gray">';
    listItem += processTitleHTML(note.title_html) + '</span>';
    if (noText)
        listItem += '&nbsp;<span class="publishedDate">' + note.modified + '</span></div>';
    else
        listItem += '<div class="comment"><img class="middle" src="/content/images/feedicons-comments.png" height="12" width="12"> ' + note.text +
        '&nbsp;<span class="publishedDate">' + note.modified + '</span></div>';
    for (var attachmentIndex in note.attachments) {
        var attachment = note.attachments[attachmentIndex];
        for (var contentIndex in attachment.attachment_content) {
            var content = attachment.attachment_content[contentIndex];
            if (content.type == "preview")
                listItem += '<div class="attachment"><a target="_blank" href="' + content.source + '"><img src="' + content.href + '"/></a></div>';
        }
    }

    var additionalInfo = "source=facebook&replyTo=" + note.uri;
    listItem += addActions(note);
    listItem += '</div>';
    return listItem;
}
function twitterDirectMessage(note) {
    var listItem = appendAuthorPicture(note) + '<div class="status"><img class="middle" src="/content/images/twit-12x12.png"> <a href="http://twitter.com/' + note.screen_name + '"class="author-link" target="_blank">' + note.author + '</a> <span class="description">sent you a message:';
    if (!IsNullOrEmpty(note.text))
        listItem += '<div class="comment">' + note.text + '&nbsp;<span class="publishedDate">' + note.modified + '</span></div></span>';
    var additionalInfo = "source=twitter&replyTo=" + note.screen_name + "&tweetId=" + item.tweet_id;
    listItem += addActions(note);
    listItem += '</div>';

    return listItem;
}
function twitterMention(note) {
    var listItem = appendAuthorPicture(note) + '<div class="status"><img class="middle" src="/content/images/twit-12x12.png"> <a href="http://twitter.com/' + note.screen_name + '" class="author-link" target="_blank">' + note.author + '</a><span class="description"> tweeted about you: ';

    if (!IsNullOrEmpty(note.text))
        listItem += '<div class="comment">' + note.text + '&nbsp;<span class="publishedDate">' + note.modified + '</span></div></span>';
    var additionalInfo = "source=twitter&replyTo=" + note.screen_name + "&tweetId=" + item.tweet_id;
    listItem += addActions(note);
    listItem += '</div>';
    return listItem;
}
function processTitleHTML(title_html) {
    if (IsNullOrEmpty(title_html))
        return '';
    var temp1 = title_html.match(/<span class="uiTooltipText">(.*)<\/span>/);
    var result;
    if (!IsNullOrEmpty(temp1)) {
        var temp2 = temp1[0].replace('<span class="uiTooltipText">', "").replace(/<br \/>/g, ", ").replace(/<.*/, "");
        var lastcomma = temp2.lastIndexOf(',');
        var part2 = temp2;
        if (lastcomma != -1) {
            part2 = temp2.slice(0, lastcomma) + ", and " + temp2.slice(lastcomma + 1);
        }
        var part1 = title_html.substr(0, title_html.indexOf('<a class=== = "uiTooltip"'));
        var part3 = title_html.substr(title_html.lastIndexOf('</span></span></a>'));
        result = part1 + ", along with " + part2 + ", " + part3;
    }
    else
        result = title_html.substr(0, title_html.length - 1).replace(/a href/g, 'a target="_blank" href');
    return result.replace(/(likes|like)/, '<b>$1</b>');
}
function generalNotification(note) {
    var listItem = appendAuthorPicture(note) + '<div class="status">';
    if (!IsNullOrEmpty(note.author))
        listItem += '<img class="middle" src="/content/images/face-12x12.png"> <a class="author-link" target="_blank" href="http://www.facebook.com/' + note.screen_name + '">' + note.author + '</a>';

    if (!IsNullOrEmpty(note.text)) {
        listItem += ' <span class="description gray">' + processTitleHTML(note.title_html) + '</span>';
        listItem += ': <div class="comment"><img class="middle" src="/content/images/feedicons-comments.png" height="12" width="12"> ' + note.text;
        if (!IsNullOrEmpty(note.modified))
            listItem += '&nbsp;<span class="publishedDate">' + note.modified + '</span>';
        listItem += '</div>';
    } else if (!IsNullOrEmpty(note.modified)) {
        listItem += ' <span class="description">' + processTitleHTML(note.title_html) + '</span>';
        listItem += '&nbsp;<span class="publishedDate">' + note.modified + '</span>';
    }

    listItem += addActions(note);
    listItem += '</div>';
    return listItem;
}
function addShare(note) {
    var action = '<span class="action" onclick="shareItem(this, \'' + note.parent_id + '\')">' + g_shareText + '</span>';
    return action;
}
function addRemember(note) {
    var action = '<span class="action" onclick="rememberItem(this, \'' + note.parent_id + '\')">' + g_setTagText + '</span>';
    return action;
}
function addLike(note) {
    if (note.notification_type == "TwitterDirectMessage" || note.notification_type == "TwitterMention")
        return '<span class="action" onclick="makeTwitterItemFavorite(this, \'' + note.parent_id + '\')">Favorite</span>';
    else
        return '<span class="action" onclick="likeFacebookItem(this, \'' + note.parent_id + '\')">Like</span>';
    return action;
}
function addViewItem(note) {
    if (note.parent_id != null) {
        return '<span class="action" onclick="search(\'id:' + note.parent_id + '\', \'notificationItemClick\')">View item</span>';
    } else if (note.href != null) {
        return '<a target="_blank" href="' + note.href + '">View item</a>';
    }
    return '';
}
function addSeparator(note) {
    return '<span class="grey"> | </span>';
}
function addActions(note) {
    var actions = '<div class="itemActionCon">';
    var first = true;
    if (note.parent_id != null && note.parent_id.indexOf('http:') == -1) {
        if (note.notification_type == "TwitterMention" || note.notification_type == "FacebookStream") {
            if (!first)
                actions += addSeparator();
            actions += addShare(note);
            first = false;
        }
        //        if (note.note_type == "TwitterMention" || note.notification_type == "TwitterDirectMessage") {
        //            if (!first)
        //                actions += addSeparator();
        //            actions += addRemember(note);
        //            first = false;
        //        }
    }
    if (!first)
        actions += addSeparator();
    actions += addViewItem(note);
    actions += '</div>';
    return actions;
}
function getNotifications(target) {
    $('#streamLoader').show();
    $('#streamResultsTitleBox').hide();
    $('#notificationsCount').text('');
    resetLeftButtons();
    var targetWrapper = typeof (target) != 'undefined' ? $(target) : $('#notification');
    targetWrapper.removeClass();
    targetWrapper.addClass('notificationsSelected');
    $.getJSON(g_notificationsUrl + g_timeZone, {}, function (notifications, status) {
        if (status == "success") {
            $('#streamLoader').hide();
            var streams = $('#streams');
            streams.html("");
            $.each(notifications, function (index, note) {
                var listItem = '<li class="notification" " style="border-left: 2px solid white"><div class="liPad">';

                switch (note.notification_type) {
                    case 'FacebookStream':
                        listItem += streamNotification(note);
                        break;
                    case 'FacebookLike':
                        listItem += facebookLike(note);
                        break;
                    case 'FacebookPhoto':
                        listItem += facebookPhoto(note);
                        break;
                    case "TwitterDirectMessage":
                        listItem += twitterDirectMessage(note);
                        break;
                    case "TwitterMention":
                        listItem += twitterMention(note);
                        break;
                    default:
                        listItem += generalNotification(note);
                        break;
                }
                listItem += '</div></li>';
                streams.append(listItem);
                g_searchText = '-NOTIFICATIONS-';
                $('#streamsContainer')[0].scrollTop = 0;
            });
        } else {
            // TODO - toddne   alert("getNotifications fails with status = " + status);
        }

    });
}
function hideChildImage(item) {
    $(item).children('img').hide();
}
function showChildImage(item) {
    $(item).children('img').show()
}
function deleteQuery(img) {
    var parent = $(img).parent();
    $.get(g_deleteSavedQueryUrl + encodeURI(parent.find('span').html()), function (data) {
        parent.detach();
        setLeftColumnMargin();
    });
}
function saveQuery(query) {
    var queryFound = false;
    $('#savedSearches li').each(function (index) {
        if ($(this).find('span').html() == query) {
            queryFound = true;
            return false;
        }
    });
    if (!queryFound) {
        $.get(g_saveQueryUrl + encodeURI(query) + "&qt=" + encodeURI(query) + g_timeZone, function (data) { });
        $('#savedSearches ul').append(renderSavedSearchItem(query, 0, 'Saved query', 'deleteQuery(this)', false));
        setLeftColumnMargin();
    }
}
function truncate(text, length) {
    if (text.length > length) {
        text = $.trim(text.substr(0, length - 4)) + '...';
    }
    return text;
}
function showDeleteTrendMenu(img) {
    var imgWrapper = $(img);
    imgWrapper.parents('ul').find('.dropDownMenu').each(function () {
        $(this).hide();
    });
    g_dropDownMenu = imgWrapper.next();
    g_dropDownMenu.show();
}
function deleteTrend(link, text, isExclude) {
    var parent = $(link).parent('li').parents('li');
    $.post((isExclude ? g_excludeTrendUrl : g_blockTrendUrl) + encodeURI(text), function (data) {
        parent.remove();
        setLeftColumnMargin();
    });
}
function onSavedSearchClick(span, text, origin) {
    resetSearchInfo();
    resetLeftButtons();
    var savedQueryWrapper = $(span);
    g_savedSearchContainer = savedQueryWrapper.parent();
    savedQueryWrapper.addClass('black bold');
    savedQueryWrapper.next('.actionCount').remove();
    search(text.replace(/,/g, ' '), origin);
}
function renderSavedSearchItem(text, count, origin, onDelete, isTrend, masterTrend) {
    var encodedTerm = encodeHtml(text);
    var item = "<li onmouseover='showChildImage(this)' onmouseout='hideChildImage(this)'><img src='\/content/images/delete.png' class='dqi hidden' alt='Delete' onclick='" + onDelete + "'/>";
    if (isTrend) {
        item += "<ul class='dropDownMenu'><li><a onclick='deleteTrend(this, \"" + text + "\",false)'>" + g_blockTrendText.format(encodedTerm) + "</a></li><li><a onclick='deleteTrend(this, \"" + text + "\",true)'>" + g_excludeTrendText.format(encodedTerm) + "</a></li></ul>";
    }
    var searchText = IsNullOrEmpty(masterTrend) ? text : masterTrend + ' ' + text;
    var tooltip = isTrend ? g_clickToSearchTrendText.format(text, count) : text + ". " + g_clickToSearchText;
    item += "<span class='link' onclick='onSavedSearchClick(this, \"" + searchText + "\",\"" + origin + "\")' title='" + tooltip + "'>" + encodeHtml(truncate(text, 17)) + "</span>";
    if (!isTrend && count > 0) {
        item = item + "<span class='actionCount'>\\" + count + "</span></li>";
    }
    return item;
}
function populateSavedSearches(savedQueries) {
    if (savedQueries.length > 0) {
        var result = ""
        for (var i = 0; i < savedQueries.length; ++i) {
            result = result + renderSavedSearchItem(savedQueries[i].Query, savedQueries[i].CountNew, 'Saved query', 'deleteQuery(this)', false);
        }
        $('#savedSearches ul').html(result);

    }
}
function populateTrending(trendingTopics) {
    if (trendingTopics.length > 0) {
        var result = "<ul>"
        for (var i = 0; i < trendingTopics.length; ++i) {
            result = result + renderSavedSearchItem(trendingTopics[i].Topic, trendingTopics[i].Count, 'Trending Topic', 'showDeleteTrendMenu(this)', true);
        }
        result = result + "</ul>"
        $('#trendingTopics').html(result);
    }
}
function populateRecentPhotos(photos) {
    g_currentLeftmostPhoto = 0;
    g_currentRightmostPhoto = 0;
    g_nPhotos = photos.length;
    if (photos.length > 0) {
        var result = "";
        var offsetX = 0;
        var i = 0;
        for (i = 0; i < photos.length; ++i) {
            var width = Math.floor(g_photoHeight * photos[i].Width / photos[i].Height);
            var photoTooltip = g_recentPhotoAltText.format(photos[i].Author);
            result += "<div title='" + photoTooltip + "' style='left:" + offsetX + "px; width:" + width + "px;' onclick='openPopup(event, \"" + photos[i].Url + "\", \"" + photos[i].Height + "\", \"" + photos[i].Width + "\", \"" + photos[i].Author + "\")'><img class='image' height='108' width = '" + width + "' src='" + photos[i].Url + "' alt='" + photoTooltip + "'/></div>";
            if (offsetX + width < g_photoSpace)
                g_currentRightmostPhoto = i;
            offsetX += width + g_photoMargin;
        }
        $('#photoContainer').html(result);
    }
}
function openPopup(e, photoUrl, photoHeight, photoWidth, photoAuthors) {
    if (!e)
        e = window.event;
    var x = e.clientX;
    var y = e.clientY + 600;
    var imgHeight = 600;

    if (photoHeight <= 0 || photoWidth <= 0)
        imgHeight = 600;
    else if (photoHeight < 600 && photoHeight > 0 && photoWidth < 600 && photoWidth > 0)
        imgHeight = photoHeight;
    else
        imgHeight = Math.round(photoHeight * 600.0 / Math.max(photoHeight, photoWidth));

    result = "<div onclick='closePopup()' style='position:fixed; top: 100px; right: 20px; border: 20px solid #444444; background-color:#444444;' >";
    result += "<img height='" + imgHeight + "' alt='click to close' src='" + photoUrl + "'><br />";
    if (!IsNullOrEmpty(photoAuthors)) {
        result += "<div id='labelPhotoAuthor'>Shared By " + photoAuthors + "</div>"
    }
    result += "<img src='/content/images/popup-closebutton.png' id='closePhotoLink' class='link' alt='close' /></div>";
    $('#popupPhoto').html(result).show("slow");
}
function closePopup() {
    $('#popupPhoto').hide("slow").html("");
}
function populateSharedLinks(sharedLinks) {
    var result = "";
    var offsetX = 0;
    for (var i = 0; i < sharedLinks.length; ++i) {
        result += "<div class='linkBlock' class='status' style='left:" + offsetX + "px;'><div class='description'><a class='linkTitle' href='" + sharedLinks[i].Url + "' target='_blank'>" + trimTitle(sharedLinks[i].Title) + "</a>";
        if (sharedLinks[i].SourceImgUrl != null && sharedLinks[i].SourceImgUrl != "") {
            result += "<div onclick='openPopup(event, \"" + sharedLinks[i].SourceImgUrl + "\", \"" + sharedLinks[i].SourceImgHeight + "\", \"" + sharedLinks[i].SourceImgWidth + "\", \"" + sharedLinks[i].Authors + "\")'><img class='linkPhoto' src='" + sharedLinks[i].Preview + "'/></div>";
        } else if (sharedLinks[i].Preview != null && sharedLinks[i].Preview != "") {
            if (sharedLinks[i].PreviewWidth > 200)
                result += "<div onclick='openPopup(event, \"" + sharedLinks[i].Preview + "\", \"" + sharedLinks[i].PreviewHeight + "\", \"" + sharedLinks[i].PreviewWidth + "\", \"" + sharedLinks[i].Authors + "\")'><img class='linkPhoto' src='" + sharedLinks[i].Preview + "'/></div>";
            else
                result += "<a href='" + sharedLinks[i].Url + "' target='_blank'><img class='linkPhoto' src='" + sharedLinks[i].Preview + "'/></a>";
        }
        var body = "";
        if (sharedLinks[i].Body != null && sharedLinks[i].Body != "")
            body = "<span class='linkBody'>" + sharedLinks[i].Body + " ...</span>";
        result += body;
        result += "</div><div class='sharedBy'>Shared by " + sharedLinks[i].Authors + " on " + sharedLinks[i].Source + "</div>";
        var title = "";
        if (sharedLinks[i].Title != null)
            title = sharedLinks[i].Title;
        result += '<div class="itemActionCon"><span class="action" onclick="shareLink(this, \'' + escape(title) + ' ' + sharedLinks[i].Url + '\')">' + g_shareText + '</span></div>';
        // '</span><span class="grey"> | </span><span class="action" onclick="rememberSharedLink(this, \'link\')">' + g_setTagText + '</span></div>';
        result += "</div>";

        offsetX += g_blockWidth + g_interItemSpace;
    }
    $('#linkContainer').html(result);
}
function trimTitle(text) {
    var trimmed = text;
    if (text != null && text.length > 54) {
        if (text.charAt(53) != ' ') {
            var index = text.lastIndexOf(' ', 54);
            if (index != -1) {
                trimmed = text.substr(0, index);
            }
        } else
            trimmed = text.substr(0, 53);
        text = "<span title='" + text + "'>" + trimmed + "...</span>";
    }
    return text;
}
function populateTrendingNews(trendingNews) {
    var result = "";
    var offsetX = 0;
    for (var i = 0; i < trendingNews.length; ++i) {
        result += "<div class='newsBlock' class='status' style='left:" + offsetX + "px;'><div class='description'>";
        var title = trendingNews[i].Title;
        result += "<a class='linkTitle' href='" + trendingNews[i].Url + "' target='_blank'>" + trimTitle(title) + "</a>";
        result += "<div class='linkBody'>" + trendingNews[i].Snippet + "</div></div><div class='attribution'>" + trendingNews[i].Source + "</div>"
        result += "<div class='attribution'>trend: " + trendingNews[i].Name + "</div>";

        result += '<div class="itemActionCon"><span class="action" onclick="shareLink(this, \'' + escape(title) + ' ' + trendingNews[i].Url + '\')">' + g_shareText + '</span></div>';
        //  result += '<span class="grey"> | </span><span class="action" onclick="rememberSharedLink(this, \'news\')">' + g_setTagText + '</span></div>';
        result += "</div>";

        offsetX += g_blockWidth + g_interItemSpace;
    }
    if (result != "")
        $('#newsContainer').html(result);
}

function replyToItem(replyText, itemId, additionalInfo) {
    g_itemId = itemId;
    g_additionalInfo = additionalInfo;
    $(replyArea = '#' + itemId + ' .comments').toggle('fast');
    $('#' + itemId + ' .replytext').css({ 'color': '#bfc5cc' });
}
function shareItem(shareText) {
    var item = $(shareText).parents('li');
    var title = item.find('.author-link');
    var textToShare = '';
    textToShare = item.find('.status .description').text();
    if (textToShare.length == '') {
        textToShare = item.find('.attachment span').text();
        var links = item.find('.attachment a');
        if (links.length > 0) {
            textToShare += ' ' + links.attr('href');
        }
    }
    var textArea = $('#statusUpdate #statusUpdateText');
    if (textToShare != '') {
        textArea.val(textToShare);
        textArea.focus();
        onPostBoxClick();
        showRemaining();
    }
    animateText(shareText);
}
function shareLink(shareText, body) {

    var textArea = $('#statusUpdate #statusUpdateText');
    if (body != '') {
        onPostBoxClick();
        textArea.val(unescape(body) + ' ' + g_fromSpindex);
        showRemaining();
        textArea.focus();
    }
    animateText(shareText);
}
function shareWebLink(shareText) {

    var textArea = $('#statusUpdate #statusUpdateText');
    var textWrapper = $(shareText);
    var item = textWrapper.context.parentNode.parentNode.innerHTML;
    var wrappedItem = $(item);
    var description = wrappedItem[2].innerHTML;
    if (description != '') {
        onPostBoxClick();
        textArea.val($(item).attr('href') + ' ' + unescape(description) + ' ' + g_fromSpindex);
        showRemaining();
        textArea.focus();
    }
    animateText(shareText);
}
function likeFacebookItem(likeText, parentId) {
    $(likeText).contents().first().html('Liked');
    var next = 1;
    if ($(likeText).contents().first().next().html() != "") {
        next = parseInt($(likeText).contents().first().next().html().substr(1)) + 1;
    }
    $(likeText).contents().first().next().html("\\" + next);
    animateText(likeText);
    $.getJSON(g_facebookLikeUrl + parentId + g_timeZone, function (data) {
       // in the future, should check for failure
    });
}
function makeTwitterItemFavorite(favText, tweetId) {
    $(favText).html('Favorited');
    animateText(favText);
    $.get(g_twitterFavoriteUrl + tweetId + g_timeZone, function (data) {
        // in the future, should check for failure
    });
}
function rememberItem(text, id) {
    var rememberUrl;
    var data = '';
    var textWrapper = $(text);
    var item = textWrapper.parents('li');
    if (typeof (id) == 'undefined') {
        id = item.attr('id');
    }
    if (typeof (id) == 'undefined') {
        rememberUrl = g_rememberWebItemUrl;
        data = { url: item.find('.author-link').attr('href'), title: item.find('.author-link').html(), description: item.find('.description').html(), tags: 'qqqREMEMBER' };
    }
    else {
        rememberUrl = g_rememberItemUrl + id;
    }
    if (textWrapper.html() == g_setTagText) {
        $.post(rememberUrl, data, function (data) { textWrapper.html(g_clearTagText); if (typeof (id) == 'undefined') item.attr('id', data); });
    }
    else {
        $.post(g_clearRememberItemUrl + id, function (data) { textWrapper.html(g_setTagText); });
    }

    animateText(text);
}
function rememberWebLink(rememberText, id) {
    var data = '';
    var textWrapper = $(rememberText);
    var item = textWrapper.context.parentElement.parentElement.innerHTML;
    var wrappedItem = $(item);
    var inner = wrappedItem[0].innerHTML;
    var innerWrapped = $(inner);
    var description = wrappedItem[2].innerHTML;
    data = { url: $(item).attr('href'), title: title, description: description, tags: 'qqqREMEMBER' };
    if (textWrapper.html() == g_setTagText) {
        $.post(g_rememberWebItemUrl, data, function (data) { textWrapper.html(g_clearTagText); });
    }

    animateText(rememberText);
}
function rememberSharedLink(rememberText, source) {
    var data = '';
    var textWrapper = $(rememberText);
    var item = textWrapper.context.parentElement.parentElement.innerHTML;
    var wrappedItem = $(item);
    var title = wrappedItem[0].innerText;
    var wrappedData = $(wrappedItem[0].innerHTML);
    var description = '';
    var index = 2;
    if (source == 'link' && wrappedData[1].className == "linkBody")
        index = 1;
    description = wrappedData[index].innerHTML;
    data = { url: wrappedData.attr('href'), title: title, description: description, tags: 'qqqREMEMBER' };
    if (textWrapper.html() == g_setTagText) {
        $.post(g_rememberWebItemUrl, data, function (data) { textWrapper.html(g_clearTagText); });
    }

    animateText(rememberText);
}
function retweetItem(retweetText, tweetId) {
    $.get(g_retweetUrl + tweetId + g_timeZone, function (data) {
        $('#streams').prepend(renderTweet(data, false));
    });
    animateText(retweetText);
}
function animateText(text) {
    $(text).fadeTo('slow', 0.5, function () { $(this).fadeTo('slow', 1); });
}
function toggleFilterButton(clickedButton, altTextArray) {
    if (clickedButton.id == 'allFilter') {
        resetFilterButtons();
        return;
    }
    var buttonWrapper = $(clickedButton);
    if (buttonWrapper.attr('alt') == altTextArray[1]) {
        buttonWrapper.attr('src', buttonWrapper.attr('src').replace('-off-', '-on-'));
        buttonWrapper.attr('alt', altTextArray[0]);
        var allButton = $('#allFilter');
        allButton.attr('src', allButton.attr('src').replace('-on-', '-off-'));
        allButton.attr('alt', g_allFilterText[1]);
    }
    else {
        buttonWrapper.attr('src', buttonWrapper.attr('src').replace('-on-', '-off-'));
        buttonWrapper.attr('alt', altTextArray[1]);
    }
}
function updateStreams(clickedButton, altTextArray) {
    if (g_searchText == '-NOTIFICATIONS-') {
        getNotifications();
        return;
    }
    if (typeof (clickedButton) != 'undefined' && typeof (altTextArray) != 'undefined') {
        toggleFilterButton(clickedButton, altTextArray);
    }
    var query = getQuery();
    if (query.length == 0) {
        showAll();
    }
    else {
        query = encodeURI(query);
        getStream(g_streamsUrl + '&q=' + query + getSearchOriginQueryStringParams(), false, false);
    }
}
function getCurrentFilterQuery() {
    var query = '';
    var filterButtons = $('#streamFilters img');
    for (var i = 0; i < filterButtons.length; ++i) {
        var button = filterButtons[i];
        switch (button.id) {
            case 'evernoteFilter':
                tryAppendFilterQuery(button, g_evernoteQuery);
                break;
            case 'fbFilter':
                tryAppendFilterQuery(button, g_fbQuery);
                break;
            case 'rssFilter':
                tryAppendFilterQuery(button, g_rssQuery);
                break;
            case 'twitterFilter':
                tryAppendFilterQuery(button, g_twitterQuery);
                break;
            default:
                continue;
        }
    }
    return query;
    function tryAppendFilterQuery(button, queryText) {
        if ($(button).attr('src').indexOf('-on-') > 0) {
            allOff = false;
            if (query.length > 0) {
                query = query + ' OR ';
            }
            query = query + queryText;
        }
    }
}
function getQuery() {
    var result = getCurrentFilterQuery();
    if (g_searchText.length > 0) {
        result = result.length > 0 ? "(" + result + ") AND (" + g_searchText + ")" : g_searchText;
    }
    return result;
}
function getSearchOriginQueryStringParams() {
    var result = '';
    if (g_searchOrigin.length > 0) {
        if (g_searchOrigin == "Saved query")
            result = "&sq=true";
        else
            result = "&sq=false";
        result += '&o=' + encodeURI(g_searchOrigin);
    }
    return result;
}
function getOlderItems() {
    var query = getQuery();
    if (query.length == 0) {
        getStream(g_moreStreamsUrl + g_lastItemDate, true, true);
    }
    else {
        query = encodeURI(query);
        getStream(g_moreStreamsUrl + g_lastItemDate + '&q=' + query + getSearchOriginQueryStringParams(), false, true);
    }
}
function getMoreComments(button, itemId) {
    $('#' + itemId + ' .comment').remove();
    $('#' + itemId + ' .getMoreCommentsBox').remove();
    var commentList = $('#' + itemId + ' .commentList');
    $.getJSON(g_moreCommentsUrl + itemId + g_timeZone, {}, function (items, status) {
        if (status == "success") {
            $.each(items.Stream[0].Comments, function (index, comment) {
                commentList.append(renderComment(comment));
            });
        }
        else {
            // TODO Todd: handle error case
        }
    });
}
(function ($) {
    $.fn.emptyNotifications = function () {
        return this.each(function () {
            if (this.tagName == 'NOTIFICATION') this.options.length = 0;
        });
    }
    $.fn.loadNotifications = function (optionsDataArray) {
        return this.each(function () {
            if (this.tagName == 'NOTIFICATION') {
                var selectElement = this;
                $each(optionsDataArray, function (index, optionData) {
                    var option = new Option(optionData.caption,
                                            optionData.value);
                    if ($.browser.msie) {
                        selectElement.add(option);
                    } else {
                        selectElement.add(option, null);
                    }
                });
            }
        });
    }
})(jQuery); 
