﻿var is_empty = true;
var tweetNum = 70;
var theXml;
var list_count = 0;
var biggest_id = 0;
var tweet_count = 1;
var ranRequest = false;
var query = "super bowl";
var altDataCount = 0;
var altDataInterval = -2;
var fNoun = "";
var fRating = 0;
var rVerbs = "Reticulating,Processing,Converging,Annotating,Pushing,Pulling,Opening,Disseminating,Unpacking,Itemizing";
var rActions = "Nodes,Dots,Opinions,Requests,Buttons,Levers,Boxes,Honeycombs,Gizmos,Widgets,Minutiae,Gadgets,Signals";
var isLoading = false;
var isPaused = false;
var willRun = false;
var lastRunDate = new Date();

$(document).ready(function () {

    $('select#speed').selectToUISlider();
//    var abc;
//    if ($('select#speed')) {
//        abc = 
//        //.next();
//    }
    
    $("h1").click(function () {
        $("#tweets li .overlay").fadeOut();
        fNoun = "";
        fRating = 0;
    });

    $("#ovsent1").click(function () {
        filterTweets("", 1);
    });

    $("#ovsent2").click(function () {
        filterTweets("", 3);
    });

    $("#ovsent3").click(function () {
        filterTweets("", 5);
    });
    $("#bottomexpand").click(function () {
        if ($(this).attr("class") == "expand") {
            $(this).attr("class", "contract");
        }
        else {
            $(this).attr("class", "expand");
        }

        $("#bottomcontent").slideToggle("slow");
    });
    $("#topexpand").click(function () {
        if ($(this).attr("class") == "expand") {
            $(this).attr("class", "contract");
            $("#content").animate({ top: 25 }, "slow");
            $("#maincontent").animate({ top: 27 }, "slow");
            $("#leftcol").animate({ top: 35 }, "slow");
            $("h2").fadeOut("fast");
            $("#topcontent input").fadeOut("fast");
            $("#logo").fadeOut("slow");
            $("#welogo").fadeOut("fast");
            $("#util").hide();
        }
        else {
            $(this).attr("class", "expand");
            $("#content").animate({ top: 110 }, "slow");
            $("#maincontent").animate({ top: 110 }, "slow");
            $("#leftcol").animate({ top: 120 }, "slow");
            $("h2").fadeIn(1000);
            $("#topcontent input").fadeIn(2000);
            $("#welogo").fadeIn(1500);
            $("#util").fadeIn(1500);
        }

        $("#topcontent").slideToggle("slow");
    });
    $("#bottomexpand").click();
    $("#bottomrefresh").click(function () {
        $(this).attr("class", "loading");
        $("#loadingtext").text("Loading...");
        isLoading = true;
        setTimeout(setLoadingMsg, Math.floor(Math.random() * 3000));

        $("#bottomcontent").load("_resources/ajax/HistoryChart.aspx?q=" + encodeURIComponent(query), function () {
            isLoading = false;
            $("#bottomrefresh").attr("class", "static");
            $("#loadingtext").text("All Done!");
            if ($("#bottomexpand").attr("class") == "expand") {
                $("#bottomcontent").slideToggle("slow");
                $("#bottomexpand").attr("class", "contract");
            }
        });
    });

    if (willRun)
        LatestTweet();
});




function setLoadingMsg() {

    if (isLoading) {
        var aryVerbs = rVerbs.split(',');
        var aryNouns = rActions.split(',');

        verb = aryVerbs[Math.floor(Math.random() * aryVerbs.length)];
        noun = aryNouns[Math.floor(Math.random() * aryNouns.length)];

        $("#loadingtext").text(verb + " " + noun + "...");
        setTimeout(setLoadingMsg, Math.floor(Math.random() * 3000));
    }
}



function querySt(ji) {
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    for (i = 0; i < gy.length; i++) {
        ft = gy[i].split("=");
        if (ft[0] == ji) {
            return ft[1];
        }
    }
}

function LatestTweet() {

    //alert("hi");

    var qs = "?q=" + query;
    if (querySt("q") != null) {
        query = decodeURIComponent(querySt("q"));
        qs = "?q=" + querySt("q");
    }

    $("h1").html(decodeURIComponent(query));

    if (biggest_id > 0)
        qs += "&last_id=" + biggest_id;

    qs += "&since=" + lastRunDate.getMonth() + "/" + lastRunDate.getDay() + "/" + lastRunDate.getFullYear() + "+" + lastRunDate.getHours() + ":" + lastRunDate.getMinutes() + ":" + lastRunDate.getSeconds();

    //alert(qs);
    //alert(is_empty);

    lastRunDate = new Date();

    if (is_empty == true) {
        is_empty = false;

        //alert("going to make call!");

        $.ajax({
            type: "GET",
            url: "_resources/ajax/tweets.ashx" + qs.replace(/#/, "%23"),
            dataType: "xml",
            success: function (xml) {
                ranRequest = true;
                tweetNum = 0;
                theXml = xml;
                is_empty = false;
                setTweet();
            }
        });
    }
    else {
        ranRequest = false;

        if (!isPaused)
            setTweet();
    }

    setAltData();

    if (tweet_count == 0 && ranRequest == true) {
        tweet_count = 0;
        setTimeout(LatestTweet, 60000);
    }
    else {
        var speed = 6500;
        isPaused = false;

        switch ($("#handle_speed span").text()) {
            case "pause":
                speed = 6500;
                altDataInterval = -2;
                isPaused = true;
                break;
            case "slow":
                speed = 7000;
                altDataInterval = -2;
                break;
            case "medium":
            default:
                speed = 5500;
                altDataInterval = -4;
                break;
            case "somewhat fast":
                altDataInterval = -10;
                speed = 2500;
                break;
            case "fast":
                altDataInterval = -20;
                speed = 500;
                break;
        }

        setTimeout(LatestTweet, speed);
    }
}



function setAltData() {
    var articleText = "";
    $("#reftweets").find("li span[class='post']").each(function () {
        articleText += " " + $(this).text();
    });

    articleText = articleText.replace(/['"]/g, '').replace(/;/, "").replace(/#/, "").replace(/-/, "").replace(/\)/, "");

    var sentText = "";

    $("#reftweets").find("li[score!=3] span[class='post']").each(function () {
        sentText += " " + $(this).text();
    });

    if (altDataCount == 2) {
        $.post("_resources/ajax/LeftBar.aspx?q=" + query, { article: articleText, sent: sentText },
          function (data) {
              $("#leftcontent").html(data);
              //uncomment to see different bar view of overall tweets.
              //setCounts();
              setOverallRating();
              setSubjectRatings();
              $("#cloud span").click(function () {
                  //fNoun = $(this).text();
                  filterTweets($(this).text(), 0);
              });
          });

        altDataCount = altDataInterval;
    }

    altDataCount++;
}

function setSubjectRatings() {
    $("#subjects").find("li .noun").each(function () {

        var noun = $(this).text();
        var foundCount = 0;

        var s1 = 0;
        var s3 = 0;
        var s5 = 0;

        var total = 0;

        $("#reftweets").find("li").each(function () {

            var debug = $(this).attr('debug');
            var text = $(this).find('.post').text();

            if (debug == "true")
                text = $(this).find('text').text();

            if (text.toLowerCase().replace(/'/, '').match(noun) != null) {
                switch ($(this).attr("class")) {
                    case "score1":
                    case "score2":
                        s1++;
                        break;
                    case "score3":
                        s3++;
                        break;
                    case "score4":
                    case "score5":
                        s5++;
                        break;
                }
                total++;
            }

        });

        if (s1 > 0) {
            s2Perc = Math.round(100 * (s1 / total));
            if (s2Perc < 15)
                s2Perc = "";
            if (s2Perc != "")
                s2Perc += '%';
            $(this).parent().find(".subjrating .sbsent1").animate({ width: ((200 / total) * s1) - 1 }).text(s2Perc); ;
        }
        if (s3 > 0) {
            s3Perc = Math.round(100 * (s3 / total));
            if (s3Perc < 15)
                s3Perc = "";
            if (s3Perc != "")
                s3Perc += '%';
            $(this).parent().find(".subjrating .sbsent2").animate({ width: ((200 / total) * s3) - 1 }).text(s3Perc);
        }
        if (s5 > 0) {
            s5Perc = Math.round(100 * (s5 / total));
            if (s5Perc < 15)
                s5Perc = "";
            if (s5Perc != "")
                s5Perc += '%';
            $(this).parent().find(".subjrating .sbsent3").animate({ width: ((200 / total) * s5) - 1 }).text(s5Perc);
        }
    });

    $("#subjects .noun").click(function () {
        var noun = $(this).text();
        filterTweets(noun, 6);
    });

    $("#subjects").find("li .subjrating .sbsent1").click(function () {
        var noun = $(this).parent().parent().find(".noun").text();
        filterTweets(noun, 1);
    });
    $("#subjects").find("li .subjrating .sbsent2").click(function () {
        var noun = $(this).parent().parent().find(".noun").text();
        filterTweets(noun, 3);
    });
    $("#subjects").find("li .subjrating .sbsent3").click(function () {
        var noun = $(this).parent().parent().find(".noun").text();
        filterTweets(noun, 5);
    });
}

function filterTweets(noun, rating) {
    fNoun = noun;
    fRating = rating;

    $("#tweets").find("li").each(function () {

        var debug = $(this).attr('debug');
        var text = $(this).find('.post').text();

        if (debug == "true")
            text = $(this).find('text').text();

        if (noun != "" && text.toLowerCase().replace(/'/, '').match(noun) == null) {
            $(this).find(".overlay").fadeIn("slow", function () {
                $(this).css("filter", "alpha(opacity=70)");
            });
        }
        else if (rating != 0 && rating != 6) {
            var isMatch = true;
            switch ($(this).attr("class")) {
                case "score1":
                case "score2":
                    if (rating != 1) {
                        isMatch = false;
                    }
                    break;
                case "score3":
                    if (rating != 3) {
                        isMatch = false;
                    }
                    break;
                case "score4":
                case "score5":
                    if (rating != 5) {
                        isMatch = false;
                    }
                    break;
            }

            if (!isMatch) {
                $(this).find(".overlay").fadeIn("slow", function () {
                    $(this).css("filter", "alpha(opacity=70)");
                });

            }
            else {
                $(this).find(".overlay").fadeOut();
            }
        }
        else
            $(this).find(".overlay").fadeOut();

    });
}

function setOverallRating() {
    var s1 = 0;
    var s3 = 0;
    var s5 = 0;

    var total = 0;

    $("#reftweets").find("li").each(function () {
        switch ($(this).attr("class")) {
            case "score1":
            case "score2":
                s1++;
                break;
            case "score3":
                s3++;
                break;
            case "score4":
            case "score5":
                s5++;
                break;
        }
        total++;
    });

    if (s1 > 0) {
        s2Perc = Math.round(100 * (s1 / total));
        if (s2Perc < 15)
            s2Perc = "";
        if (s2Perc != "")
            s2Perc += '%';
        $("#overallrating #ovsent1").animate({ width: ((200 / total) * s1) }).text(s2Perc);
    }
    if (s3 > 0) {
        s3Perc = Math.round(100 * (s3 / total));
        if (s3Perc < 15)
            s3Perc = "";
        if (s3Perc != "")
            s3Perc += '%';
        $("#overallrating #ovsent2").animate({ width: ((200 / total) * s3) }).text(s3Perc);
    }
    if (s5 > 0) {
        s5Perc = Math.round(100 * (s5 / total));
        if (s5Perc < 15)
            s5Perc = "";
        if (s5Perc != "")
            s5Perc += '%';
        $("#overallrating #ovsent3").animate({ width: ((200 / total) * s5) }).text(s5Perc);
    }

    var txtRating = "neutral";

    if (s1 > s3 && s1 > s3)
        txtRating = "negative";
    if (s5 > s3 && s5 > s1)
        txtRating = "positive";
    var tmpQuery = query.replace("#", "%23");
    //alert (tmpQuery);
    var twtths = "Following " + encodeURIComponent(tmpQuery) + " on twendz and it's currently " + txtRating + ". http://twendz.waggeneredstrom.com/?q=" + encodeURIComponent(tmpQuery.split(' ').join(encodeURIComponent("%20")));

    $("#tweetthis").attr("href", "http://twitter.com/home/?status=" + twtths).css("display", "block").mouseover(function () {
        $(this).animate({ width: 28 }, 0);
    }).mouseout(function () {
        $(this).animate({ width: 26 }, 0);
    });
}

function setCounts() {

    var s1 = 0;
    var s2 = 0;
    var s3 = 0;
    var s4 = 0;
    var s5 = 0;

    var total = 0;

    $("#reftweets").find("li").each(function () {
        switch ($(this).attr("class")) {
            case "score1":
                s1++;
                break;
            case "score2":
                s2++;
                break;
            case "score3":
                s3++;
                break;
            case "score4":
                s4++;
                break;
            case "score5":
                s5++;
                break;
        }

        if (s1 > total)
            total = s1;
        if (s2 > total)
            total = s2;
        if (s3 > total)
            total = s3;
        if (s4 > total)
            total = s4;
        if (s5 > total)
            total = s5;
    });

    if (s1 > 0) {
        //$("#countgraph #sentiment1").html(s1);
        $("#countgraph #sentiment1").animate({ width: ((250 / total) * s1) });
    }
    if (s2 > 0) {
        //$("#countgraph #sentiment2").html(s2);
        $("#countgraph #sentiment2").animate({ width: ((250 / total) * s2) });
    }
    if (s3 > 0) {
        //$("#countgraph #sentiment3").html(s3);
        $("#countgraph #sentiment3").animate({ width: ((250 / total) * s3) });
    }
    if (s4 > 0) {
        //$("#countgraph #sentiment4").html(s4);
        $("#countgraph #sentiment4").animate({ width: ((250 / total) * s4) });
    }
    if (s5 > 0) {
        //$("#countgraph #sentiment5").html(s5);
        $("#countgraph #sentiment5").animate({ width: ((250 / total) * s5) });
    }
}

function setTweet() {

    //alert(theXml);

    var j = 0;
    var isSet = false;

    tweet_count = 0;

    $(theXml).find('tweet').each(function () {

        if (j == tweetNum) {
            var id_text = $(this).attr('id');
            var external_id = $(this).attr('external_id');
            var debug = $(this).attr('debug');
            var text = $(this).find('sentiment_text').text();
            var raw_text = $(this).find('text').text();
            var last_id = $(this).attr('external_id');
            var score = $(this).find('score').text();
            var raw_score = $(this).find('raw_score').text();
            var img = $(this).find("img").text();
            var author = $(this).find("author").text();
            var link = $(this).find("link").text();
            var published = $(this).find("published").text();

            if (parseInt(last_id) > parseInt(biggest_id))
                biggest_id = last_id;

            tweetNum++;
            j = tweetNum + 1;

            var tweetText = "<li class='score" + score + "' id=\"" + external_id + "\" ><div class=\"overlay\"></div>";

            if (debug == "true") {
                tweetText += "<span class='twsent twsentc" + score + "' />";
            }

            if (img != null)
                tweetText += "<a href='http://www.twitter.com/" + author + "' target='_blank'><img width='48' height='48' src='" + img + "' alt='" + author + "' /></a>";

            tweetText += "<span class='post'>" + text + "</span>";
            tweetText += "<strong><a href='http://www.twitter.com/" + author + "' target='_blank'>" + author + "</a>:</strong>";
            tweetText += "<span class='date'>" + published + "</span>";
            tweetText += "<div class='right'>";
            tweetText += "<a href='http://twitter.com/home?status=@" + author + " ' target='_blank'>Reply</a> ";
            tweetText += "<a href='" + link + "' target='_blank'>View Tweet</a>";
            tweetText += "</div>";
            
            tweetText += "</li>";

            var foundCount = 0;
            $("#tweets").find("li[id='" + external_id + "']").each(function () {
                foundCount++;
            });

            if (foundCount == 0) {
                $("#reftweets").prepend(tweetText);
                $("#tweets").prepend(tweetText);
                $("#tweets li:first-child").hide().fadeIn("slow", function () {
                    $(this).css({ backgroundPosition: "0 -45px" }).mouseover(function () {
                        $(this).stop().animate({ backgroundPosition: "(0 0px)" }, { duration: 150 });
                    })
                    .mouseout(function () {
                        $(this).stop().animate({ backgroundPosition: "(0 -45px)" }, { duration: 150 });
                    });
                });

                if (fRating == 0)
                    $("#tweets li:first-child .overlay").fadeOut("fast");

                else
                    filterTweets(fNoun, fRating);

                $("#tweets li:first-child .sentadd, #tweets li:first-child .sentaddn").click(function () {
                    $(this).parent().parent().find(".wordadd").css("display", "block").css("left", $(this).position().left).css("top", $(this).position().top + 25);
                    $(this).parent().parent().find(".wordadd .wordinput").val($(this).text());
                });

                $("#tweets li:first-child .close").click(function () {
                    $(this).parent().parent().hide();
                });

                
                tweet_count++;
                list_count++;
                isSet = true;
            }

            if (list_count == 71) {
                $("#reftweets li:last-child").remove();
                $("#tweets li:last-child").remove();
                list_count--;
            }
        }

        j++;
    });

    if (!isSet)
        is_empty = true;
}



