﻿var TWITTER_SEARCH_API_JSON = "http://search.twitter.com/search.json";
var TWITTER_SEARCH = "http://search.twitter.com/search";
var LANG = "en";

var TWITTER_DIV_ID = "twitterresults";
var TWITTER_DIV_ID_JQUERY = "#twitterresults";

var TWEETS_DIV_ID = "tweets";
var TWEETS_DIV_ID_JQUERY = "#tweets";

var TWEET_DIV_ID = "tweettemplate";
var TWEET_DIV_ID_JQUERY = "#tweettemplate";

var JOIN_CONVERSATION_ID = "joinconversation";
var JOIN_CONVERSATION_ID_JQUERY = "#joinconversation";

function setUpTwitterFeeds() {
    if (null != $(TWITTER_DIV_ID_JQUERY) && null != $(TWEETS_DIV_ID_JQUERY)) {
        var queryTxt = getQueryTxt();
        if ("" != queryTxt) {
            try {
                var url = TWITTER_SEARCH_API_JSON + "?q=" + queryTxt + "&callback=?";
                var link = TWITTER_SEARCH + "?q=" + queryTxt + "&lang=en";

                var additionalparams = "";

                var since = $(TWEETS_DIV_ID_JQUERY).attr("since");
                if (null != since && "" != since) {
                    additionalparams += "&since=" + since;
                }

                var rpp = $(TWEETS_DIV_ID_JQUERY).attr("rpp");
                if (null != rpp && "" != rpp) {
                    additionalparams += "&rpp=" + rpp;
                }


                if ("" != additionalparams) {
                    url += additionalparams;
                    link += additionalparams;
                }


                $(JOIN_CONVERSATION_ID_JQUERY).attr("href", link);

                $.getJSON(url, applyResults);

            } catch (err) {
                hideTwitterDiv();
            }
        }
    }
}

function trim(str) {
    return str.replace(/^\s+|\s+$/g, "");
}

function getQueryTxt() {
    var queryTxt = $(TWEETS_DIV_ID_JQUERY).html();
    if (null != queryTxt && "" != queryTxt) {
        queryTxt = trim(queryTxt);
        queryTxt = queryTxt.replace(/@/g, "%40");
        queryTxt = queryTxt.replace(/#/g, "%23");
        queryTxt = queryTxt.replace(/:/g, "%3A");
        queryTxt = queryTxt.replace(/\s/g, "+");
    }
    return queryTxt;
}

function applyResults(data, textStatus) {
    getHtmlForTweets(data.results, $(TWEETS_DIV_ID_JQUERY));
}

function scrollTweets() {
    var children = $(TWEETS_DIV_ID_JQUERY).children();
    var firstChild = children[0];

    var new_child = $(firstChild).clone();

    $(firstChild).animate({ "opacity": 0 }, 500, function() { tweetFadedOut() });
}

function tweetFadedOut() {
    var children = $(TWEETS_DIV_ID_JQUERY).children();
    var firstChild = children[0];

    var new_child = $(firstChild).clone();

    $(firstChild).detach();
    $(TWEETS_DIV_ID_JQUERY).append(new_child);

    $(new_child).animate({ "opacity": 1 }, 500);

    setTimeout(scrollTweets, 3000);
}

function getHtmlForTweets(results, div) {

    if (null != results && results.length > 0) {
        // set timeout for animation
        setTimeout(scrollTweets, 3000);

        $(div).empty();

        $.each(results, function(i, tweet) {
            addTweet(tweet, div);
        });

        // remove footer hr from last tweet
        // $(TWEETS_DIV_ID_JQUERY + " div:last-child").css("border-bottom","0px");

        // convert to links, hash tags, etc. to links
        unescapeTweets();

        showTwitterDiv();

    } else {
        hideTwitterDiv();
    }
}

function hideTwitterDiv() {
    $(TWITTER_DIV_ID_JQUERY).hide(); //.css("display", "none");	
}

function showTwitterDiv() {
    $(TWITTER_DIV_ID_JQUERY).show(); //.css("display", "block");
}

function unescapeTweets() {
    $.each($(".source"), function(i, source) {
        var sourcehtml = $(source).html();
        sourcehtml = sourcehtml.replace(/&amp;/g, "&");
        sourcehtml = sourcehtml.replace(/&lt;/g, "<");
        sourcehtml = sourcehtml.replace(/&gt;/g, ">");
        sourcehtml = sourcehtml.replace(/&quot;/g, "'");
        sourcehtml = sourcehtml.replace(/<a/g, "<a target='new'");
        $(source).html(sourcehtml);
    });

    $.each($(".profile_image_url"), function(i, source) {
        var sourcehtml = $(source).html();
        sourcehtml = "<img src='" + sourcehtml + "' height='30' width='30' />";
        $(source).html(sourcehtml);
    });

    $.each($(".from_user"), function(i, source) {
        var sourcehtml = $(source).html();
        sourcehtml = "<a target='new' href='http://twitter.com/" + sourcehtml + "'>" + sourcehtml + "</a>:";
        $(source).html(sourcehtml);
    });

    $.each($(".text"), function(i, source) {
        var sourcehtml = $(source).html();
        sourcehtml = sourcehtml.replace(/&amp;/g, "&");

        sourcehtml = sourcehtml.replace(/(http:\/\/[^\s]+)/g, "<a target='new' href='$1'>$1</a>");

        sourcehtml = sourcehtml.replace(/[\s]+#([^\s]+)/g, " <a target='new' href='http://search.twitter.com/search?q=%23$1'>#$1</a>");

        sourcehtml = sourcehtml.replace(/@([A-Za-z0-9_\-]+)/g, "<a target='new' href='http://twitter.com/$1'>@$1</a>");
        $(source).html(sourcehtml);
    });

    $.each($(".created_at"), function(i, source) {
        var sourcehtml = $(source).html();
        sourcehtml = getTweetTime(sourcehtml);
        $(source).html(sourcehtml);
    });
}

function getTweetTime(tweetDateStr) {
    var tweetDate = new Date(tweetDateStr);
    var today = new Date();
    var dateDiff = today - tweetDate;
    var seconds = dateDiff / 1000;

    var minute_secs = 60;
    var hour_secs = 3600;
    var days_secs = 86400;
    var week_secs = 604800;
    var month_secs = 2419200;

    var months = parseInt(seconds / month_secs);
    if (months >= 1) {
        return months + " months ago";
    }

    var weeks = parseInt(seconds / week_secs);
    if (weeks >= 1) {
        return weeks + " weeks ago";
    }

    var days = parseInt(seconds / days_secs);
    if (days >= 1) {
        return days + " days ago";
    }

    var hours = parseInt(seconds / hour_secs);
    if (hours >= 1) {
        return hours + " hours ago";
    }

    var minutes = parseInt(seconds / minute_secs);
    if (minutes >= 1) {
        return minutes + " minutes ago";
    }

    if (seconds >= 1) {
        return seconds + " seconds ago";
    }
    else {
        return "1 second ago"
    }
}

function addTweet(tweet, div) {
    var template = $(TWEET_DIV_ID_JQUERY).clone();

    var new_id = "tweet" + tweet.id;
    $(template).attr("id", new_id);

    $(div).append(template);

    $.each(tweet, function(name, value) {
        var query = "#" + new_id + " ." + name;

        if ("" != value) {
            $(query).text(value);
        }
    });


    $(template).css("display", "block");
    return template;
}