﻿/// <reference path="$-vsdoc.js" />

var twitterTemplate = "<div class='smImg' id='{6}'><img src='{0}' class='avatar'> <img src='http://img.lavva.com/GSPanel/twitterRTMessage.png' class='avatarSocial'/></div><div class='smDivO'><div class='smDivI'><div class='gspArrowLeft'></div><div class='ltcw'></div><div class='rtcw'></div><div class='lbcw'></div><div class='rbcw'></div><div class='smDivII'><table width='100%' cellspacing='0' cellpadding='2' style='text-align:left;'><tbody><tr><td style='font-size: 11px;'><a href='http://twitter.com/{1}' style='color: #771177;' onclick='window.open(\"http://twitter.com/{1}\"); return false;'> {1}: </a> {2} </td></tr><tr><td style='font-size: 11px;'><span style='color: rgb(123, 121, 122);'><abbr class=\"timeago\" title='{4}'>{5}</abbr></span><span style='color: #771177;'> Twitter</span><div style='bottom:0px; right:0px; position:absolute;'><a style='background: url(\"http://img.lavva.com/GSPanel/replyArrows.png\") no-repeat scroll right center transparent; width: 11px; height: 11px;' class='inlineEl' title='Reply' href='#' onclick=\"ReplayToMsg(this,'{6}','T','{1}');\"></a><a style='display:{8}; background: url(\"http://img.lavva.com/GSPanel/replyArrows.png\") no-repeat scroll left center transparent; width: 18px; height: 11px;'  class='inlineEl' title='ReTweet' href='#' onclick=\"ReTweetMsg(this,'{6}','T','{7}','{1}');\"></a></div></td></tr></tbody></table></div></div></div>"; // 
var facebookTemplate = "<div class='smImg' id='{0}'><img src='https://graph.facebook.com/{0}/picture' class='avatar'> <img src='http://img.lavva.com/GSPanel/facebookRTMessage.png'  class='avatarSocial'/></div><div class='smDivO'><div class='smDivI'><div class='gspArrowLeft'></div><div class='ltcw'></div><div class='rtcw'></div><div class='lbcw'></div><div class='rbcw'></div><div class='smDivII'><table width='100%' cellspacing='0' cellpadding='2' style='text-align:left;'><tbody><tr><td style='font-size: 11px;'><a href='http://www.facebook.com/profile.php?id={0}' style='color: #771177;' onclick=\"window.open('http://www.facebook.com/profile.php?id={0}'); return false;\"> {1}: </a> {2}</td></tr><tr><td style='font-size: 11px;'><span style='color: rgb(123, 121, 122);'><abbr class=\"timeago\" title='{3}'>{4}</abbr></span><span style='color: #771177;'> Facebook</span><div style='bottom:0px; right:0px; position:absolute;'><a style='background: url(\"http://img.lavva.com/GSPanel/replyArrows.png\") no-repeat scroll right center transparent; width: 11px; height: 11px;' class='inlineEl' title='Reply' href='#' onclick=\"ReplayToMsg(this,'{0}','F','{1}');\"></a></div></td></tr></tbody></table></div></div></div>"; //
var timer;
var key;
var addedFirstLoadedItemsCount = 0;
var init = 1;
var limit = 50;


$(function() {

    $('a#btnMoreRes').click(function(event) {
        event.preventDefault();
        $("abbr.timeago").timeago();

        var maxTop = parseInt($("div#startpost").height());

        var top = parseInt($("div#startpost").css("top"));
        if (top !== 1)
            top *= -1;

        if ((top + 700) < maxTop) {
            $("div#startpost").animate({ "top": "-=300px" }, 100);
            $("a#btnNewestRes").show();
        }
    });

    $("a#btnNewestRes").click(function(event) {
        event.preventDefault();
        $("abbr.timeago").timeago();
        var top = $("div#startpost").css("top");

        if (top != "1px") {
            $("div#startpost").animate({ "top": "+=300px" }, 100);
        }
    });
});

function StartGettingRTSWebResult(localWebQuery) {
    $('#startpost').empty();
    $("abbr.timeago").timeago();



    key = localWebQuery;
    $.data(document.body, 'key', key);

    var url = 'http://search.twitter.com/search.json?&q=' + key + '&rpp=11&callback=?';
    $.data(document.body, 'realtime', url);

    var urlfb = 'https://graph.facebook.com/search?q=' + key + '&type=post&limit=1&lo=en_US&callback=?';
    $.data(document.body, 'realtimefb', urlfb);

    $.data(document.body, 'init', init);
    $.data(document.body, 'limit', limit);

    getSearch();
}

function linkify(text) {

    if (!text) return text;
    text = text.replace(/((https?\:\/\/|ftp\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,
                    function(url) {
                        nice = url;
                        if (url.match('^https?:\/\/')) {
                            nice = nice.replace(/^https?:\/\//i, '')
                        }
                        else
                            url = 'http://' + url;

                        return '<a target="_blank" rel="nofollow" href="' + url + '">' + nice.replace(/^www./i, '') + '</a>';
                    });

    return text;
}

function getSearch() {
    try {
        $("abbr.timeago").timeago();
        clearTimeout(timer);
        var url = $.data(document.body, 'realtime');
    }
    catch (e) {
        alert(e);
    }
    try {
        $.getJSON(url,
        function (data) {

            if (data == null || data === "undefined" || data.error != null || data.results === "undefined" || data.results.length == 0) {
                timer = setTimeout('getSearchfb()', 5000);
                return;
            }

            var results = data.results;
            results.reverse();

            $.each(results,
            function (i, item) {
                var timestamp = item.created_at;
                var str = item.text;

                var plain = item.text.replace(/@/g, 'http://twitter.com/');
                addedFirstLoadedItemsCount++;

                var linkedtext = linkify(plain);

                var linkedtext2 = linkedtext.replace('">twitter.com/', '">@');
                var linkedtext3 = linkedtext2.replace('">twitter.com/', '">@');
                //var message = item.text.replace(/"""/g, "\"");
                var message = item.text.replace(/['#]/g, '\#').replace(/['"]/g, '"').replace(/\u200b/g, '').replace("'", '`');
                var splt = timestamp.split(' ');
                var timestampResult = splt[3] + '-' + splt[2] + '-' + splt[1] + 'T' + splt[4] + 'Z' + splt[5];
                var tmago = $.timeago(timestampResult);
                //debugger;
                
                if ((item.id !== undefined || item.id !== null || item.id !== "") && $('div#' + item.id).val()===undefined) {

                    var formatResult = String.format(twitterTemplate, item.profile_image_url, item.from_user, linkedtext3.replace('">twitter.com/', '">@'), item.id, timestamp, tmago, item.id, message, $('body:has(.twittLnk)').length ? 'visible' : 'none');
                    AddResults(formatResult);
                    InvalidateRealtimePanel();
                }

            });

            var url = 'http://search.twitter.com/search.json?&q=' + key + '&rpp=1&since_id=' + data.max_id + '&callback=?';

            var maxid = data.max_id;
            maxid = maxid + 1;

            if (maxid > 0) {
                $.removeData(document.body, 'realtime');
                $.data(document.body, 'realtime', url);
            }
            timer = setTimeout('getSearchfb()', 5000);
        });
    }
    catch (e) {
        alert(e);
    }
}

function getSearchfb() {
    try {
        $("abbr.timeago").timeago();
        clearTimeout(timer);
        var url = $.data(document.body, 'realtimefb');

        if (addedFirstLoadedItemsCount < 11) {
            var urln = 'https://graph.facebook.com/search?q=' + key + '&type=post&lo=en_US&limit=' + (11 - addedFirstLoadedItemsCount) + '&callback=?';
            $.removeData(document.body, 'realtimefb');
            $.data(document.body, 'realtimefb', urln);
        }
    }
    catch (e) {
        alert(e);
    }
    try {
        $.getJSON(url,
        function (data) {
            if (data == null || data == "undefined" || data.error != null || data.data == "undefined" || data.results == "undefined" || data.data.length == 0) {
                timer = setTimeout('getSearch()', 5000);
                return;
            }

            var results = data.data;
            results.reverse();
            $.each(results,
            function (i, item) {
                var timestamp = new Date();
                if (item.type == "status" && ($('div#' + item.from.id).val() === undefined) && (item.from.id !== undefined || item.from.id !== null || item.from.id !== "")) {
                    var message = item.message.replace(/['#]/g, '\#').replace(/['"]/g, '"').replace(/\u200b/g, '').replace("'", '`').replace(/\n/g, '');
                    var formatResult = String.format(facebookTemplate, item.from.id, item.from.name, message, timestamp, $.timeago(timestamp));
                    AddResults(formatResult);
                    InvalidateRealtimePanel();
                }
            });

            var until = gup(data.paging.next);
            var urln = 'https://graph.facebook.com/search?q=' + key + '&type=post&lo=en_USt&limit=1&until=' + until + '&callback=?';

            $.removeData(document.body, 'realtimefb');
            $.data(document.body, 'realtimefb', urln);

            timer = setTimeout('getSearch()', 5000);
        });
    }
    catch (e) {
        alert(e);
    }
}

function InvalidateRealtimePanel() {

    init = init + 1;
    $.removeData(document.body, 'init');
    $.data(document.body, 'init', init);
    var limit = $.data(document.body, 'limit');

    if (init > limit) {
        var removeId = init - limit;
        var removeDiv = $("#" + removeId + "");
        if (removeDiv != null && removeDiv !== 'undefined') {
            removeDiv.html('');
            removeDiv.remove();
            removeDiv = null;
        }
    }
}

function gup(url) {
    var name = 'until';
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(url);
    if (results == null)
        return "";
    else
        return results[1];
}

function AddResults(templatedItem) {
	try {
		templatedItem = templatedItem.replace(/\n/g, "");
        if (navigator.appName == "Microsoft Internet Explorer")
            $("<div style='zoom:1'>").attr("class", "item").attr("id", "" + init + "").prependTo("#startpost").hide().html(templatedItem).slideDown(500);
        else
            $("<div>").attr("class", "item").attr("id", "" + init + "").prependTo("#startpost").hide().html(templatedItem).slideDown('slow');
        if ($("twittLnk").is(":visible"))
            $("img.gsReply").css("visibility", "visible");
        else
            $("img.gsReply").css("visibility", "hidden");
    }
    catch (e) {
        alert(e);
    }
}
