﻿ 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;

 $(document).ready(function() {

     var abc = $('select#speed').selectToUISlider().next();

     $("#go").click(function() {
         if ($("#query").val() != "")
             window.location = "default.aspx?q=" + encodeURIComponent($("#query").val());
     });

     $("#query").keyup(function(e) {
         alertkey(e);
     });

     $("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");
             }
         });
     });

     $("#taexpand").click(function() {
         if ($(this).attr("class") == "plus") {
             $(this).attr("class", "minus");
             $("#tagraphic").slideDown();
             $("#handle_speed span").text("pause");
         }
         else {
             $(this).attr("class", "plus");
             $("#tagraphic").slideUp();
             $("#handle_speed span").text("medium");
         }
     });

     $("#tagraphic").hide();

     $("#tryitclose").click(function() {
         $("#tagraphic").slideUp();
         $("#taexpand").attr("class", "plus");
         setCookie("twendzad", "true", 30);
         $("#handle_speed span").text("medium");
     });

     $("#tryitnow").click(function() {
         setCookie("twendzad", "true", 30);
     });

     animateBar();

     if (willRun)
         LatestTweet();

     if (Get_Cookie("twendzad") == null) {
         $("#taexpand").click();
         $("#handle_speed span").text("pause");
     }

 });

 var isOff = true;

 function animateBar() {
     if (isOff) {
         isOff = false;
         $("#topcontentsearch").css({ backgroundPosition: "0 0" }).animate({ backgroundPosition: "(-460px 0)" }, 2500, function() {
             setTimeout(animateBar, 2500);
         });
     }
     else {
         isOff = true;
         $("#topcontentsearch").animate({ backgroundPosition: "(0 0)" }, 2500, function() {
            setTimeout(animateBar, 2500);
         });
     }
 }

 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 alertkey(e) {
  if( !e ) {
    if( window.event ) {
     //Internet Explorer
      e = window.event;
    } else {
      return;
    }
  }
  if( typeof( e.keyCode ) == 'number'  ) {
    //DOM
      e = e.keyCode;
  } else if( typeof( e.which ) == 'number' ) {
    //NS 4 compatible
      e = e.which;
  } else if( typeof( e.charCode ) == 'number'  ) {
    //also NS 6+, Mozilla 0.9+
      e = e.charCode;
  } else {
    //total failure, we have no way of obtaining the key code
    return;
  }
  if(e==13) {
      window.location = "default.aspx?q=" + encodeURIComponent($("#query").val());
     return false;
  }
}

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()
{
    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;

    if (is_empty == true) 
    {
        is_empty = false;
        $.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 setCookie(c_name,value,expiredays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +value+
    ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function setAltData()
{
    var articleText = "";
    $("#reftweets").find("li span[class='post']").each(function() {
        articleText += " " + $(this).text();
    });
    
    articleText = articleText.replace(/['"]/g,'').replace(/;/,"").replace(/#/,"").replace(/-/,"").replace(/\)/,"");
    
    //setCookie("text", encodeURIComponent(articleText), 1);
    
    var sentText = "";

    $("#reftweets").find("li[score!=3] span[class='post']").each(function() {
        sentText += " " + $(this).text();
    });
    
    //sentText = sentText.replace(/['"]/g,'').replace(/;/,"").replace(/#/,"").replace(/-/,"").replace(/\)/,"");
    
    //setCookie("sentText", encodeURIComponent(sentText), 1);

    //$("#leftcontent").load("/_resources/ajax/LeftBar.aspx", setCounts);

    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 twtths = "Following " + encodeURIComponent(query) + " on twendz and it's currently " + txtRating + ". http://twendz.waggeneredstrom.com/?q=" + query.split(' ').join(encodeURIComponent("%20"));
    

    //console.log(twtths);

    $("#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) });
    }

    //var twtths = "Following " + query + " on twendz and it's currently " + $("#overallrating").html() + ". http://twendz.waggeneredstrom.com/?q=" + query.replace(/ /, "%20");

    //$("#tweetthis").attr("href", "http://twitter.com/home/?status=" + twtths);
}

function rateTweet(id, score) 
{
    var txt = "Scored: Neutral.";

    if (score == 1)
        txt = "Scored: Positive.";
    if (score == 3)
        txt = "Scored: Negative.";

    var qs = "?id=" + id + "&rating=" + score + "&text=" + $("#" + id + " .hide").text();

    $("#" + id + " .scoreit").fadeOut("slow", function() {
        $.ajax({
            type: "GET",
            url: "_resources/ajax/RateTweet.aspx" + qs
        });
    
        $(this).html(txt).fadeIn();
    });
    
}

function setTweet()
{
    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>";

            if (debug == "true") {
                tweetText += "<div class=\"scoreit\">";
                tweetText += "<strong>Raw Score: " + raw_score + "</strong>";
                tweetText += "<strong>Rate This Tweet:</strong><br />";
                tweetText += "<span class=\"scoreup\" onclick=\"rateTweet(" + external_id + ",1);\" />";
                tweetText += "<span class=\"scoren\" onclick=\"rateTweet(" + external_id + ",2);\" />";
                tweetText += "<span class=\"scoredown\" onclick=\"rateTweet(" + external_id + ",3);\" />";
                tweetText += "<em class=\"hide\">" + raw_text + "</em>";
                tweetText += "<div style=\"clear:both;\"></div>";
                tweetText += "</div>";
                tweetText += "<div class=\"wordadd\"><div class=\"wordaddcontainer\"><input type=\"text\" class=\"wordinput\" /><br />";
                tweetText += "<table><tr>";
                tweetText += "<td><input type=\"checkbox\" class=\"pos\" /> Positive</td><td><input type=\"checkbox\" class=\"neg\" /> Negative</td></tr><tr>";
                tweetText += "<td><input type=\"checkbox\" class=\"strong\" /> Strong </td><td><input type=\"checkbox\" class=\"weak\" /> Weak</td></tr><tr>";
                tweetText += "<td><input type=\"checkbox\" class=\"active\" /> Active </td><td><input type=\"checkbox\" class=\"passive\" /> Passive</tr></table>";
                tweetText += "<input type=\"button\" class=\"btnaddword\" value=\"Add\" /><br />";
                tweetText += "<a href=\"javascript:void(0);\" class=\"close\">Close</a>";
                tweetText += "</div></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();
                });

                $("#tweets li:first-child .btnaddword").click(function() {
                    var pos = ($(this).parent().find(".pos").attr("checked") == true ? 1 : 0);
                    var neg = ($(this).parent().find(".neg").attr("checked") == true ? 1 : 0);
                    var strong = ($(this).parent().find(".strong").attr("checked") == true ? 1 : 0);
                    var weak = ($(this).parent().find(".weak").attr("checked") == true ? 1 : 0);
                    var active = ($(this).parent().find(".active").attr("checked") == true ? 1 : 0);
                    var passive = ($(this).parent().find(".passive").attr("checked") == true ? 1 : 0);
                    var text = $(this).parent().find(".wordinput").val();

                    qs = "?pos=" + pos + "&neg=" + neg + "&strong=" + strong + "&weak=" + weak + "&active=" + active + "&passive=" + passive + "&text=" + text;

                    $.ajax({
                        type: "GET",
                        url: "_resources/ajax/AddWord.aspx" + qs
                    });

                    $(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;
}

function Get_Cookie(check_name) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split(';');
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for (i = 0; i < a_all_cookies.length; i++) {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split('=');


        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if (cookie_name == check_name) {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if (a_temp_cookie.length > 1) {
                cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return null;
    }
}
