  var refresh_rate = 60000;
  var cancel_updates = false;

    function launch() {
        cancel_udpates = false;
        $("#logon").hide();
        $("#header a").fadeIn();
        working("Fetching messages, replies, and pictures.<br/><em>this can take a moment, please wait...</em>");
        updateall();
        updatenew();
    }

    function reset() {
        showactivity("clearing cached tweets, this can take a moment");
        working("Clearing Cached Messages");
        $.post("stacker.php", {action: "reset"}, function (data) {freshlist(data);}, "json");
    }


    function logout() {

        cancel_updates = true;	
        showactivity("clearing cached tweets, this can take a moment");
        $.post("stacker.php", {action: "reset"}, function (data) {showactivity("signing off...");$.post("stacker.php", {action: "logout"}, function (data) {$("#twitterlist div").remove();showactivity("signed out!");logon();done();}, "json");}, "json");
    }


    function done() {
        $("#activity").fadeOut("slow");
        $.unblockUI();
    }


    function working(message) {
        $.blockUI({message: message, css: {border: "none", padding: "15px", backgroundColor: "#000", '-webkit-border-radius': "10px", '-moz-border-radius': "10px", opacity: ".5", color: "#fff"}});
    }


    function showactivity(message) {
        $("#activity").css("top", $(window).scrollTop() + "px");
        if (typeof message != "undefined") {
            $("#amessage").text(message);
        }
        $("#activity").fadeIn();
    }


    function tagsearch(text) {
        showactivity("searching...");
        $.post("stacker.php", {action: "search", text: text}, function (data) {done();searchresults(data);}, "json");
    }


    function hideresults() {
        $("#searchlist").hide();
        $("#twitterlist").fadeIn("fast");
    }


    function searchresults(tweetstack) {

        showactivity("fetching results...");
        var html = "";
        var total = 0;
        for (var profile_id in tweetstack) {
            if (tweetstack[profile_id].user) {
                var newhtml = "";
                newhtml += "<div class=\"picture\"><img src=\"" + tweetstack[profile_id].user.profile_image_url + "\"></div>";
                newhtml += "<div class=\"profile_name\">";
                newhtml += "" + tweetstack[profile_id].user.name + " (<span id=\"" + profile_id + "name\">@" + tweetstack[profile_id].user.screen_name + "</span>) says:</div>";
                for (var tweet_id in tweetstack[profile_id].tweets) {
                    newhtml += "<div class=\"latest_tweet\">";
                    newhtml += tweetstack[profile_id].tweets[tweet_id].text;
		    newhtml += "<span class=\"timestamp\">&nbsp;" + tweetstack[profile_id].tweets[tweet_id].when + "</span>&nbsp;";
                    newhtml += "&nbsp;<img src=\"stuff/commentsm.png\" title=\"Reply\" onClick=\"replyto('" + profile_id + "','" + tweet_id + "');\">";
                    newhtml += "</div>";
                }
                var starthtml = "";
                starthtml += "<div id=\"" + profile_id + "\" class=\"tweet\">";
                starthtml += "<div class=\"buttons\">";
                starthtml += "<img src=\"stuff/commentsm.png\" title=\"Reply\" onClick=\"replyto('" + profile_id + "','" + tweet_id + "');\">";
                starthtml += "<img src=\"stuff/user_comment.png\" title=\"Direct Message\" onClick=\"dm('" + profile_id + "');\">";
                starthtml += "</div>";
                html += starthtml + newhtml + "<div style=\"clear:both\"></div></div>";
            }
            total++;
        }
        if (total < 1) {
            alert("no results");
        } else {
            $(window).scrollTop(0);
            $("#searchlist").html("<strong>Search Results</strong>&nbsp;<a href=\"#\" onClick=\"hideresults();return false;\">close</a><hr/>" + html);
            $("#twitterlist").fadeOut("fast");
            $("#searchlist").fadeIn("fast");
            $("#searchlist div.tweet").fadeIn("slow");
            false;
        }
        done();
    }

    function keepcurrent() {

	if(cancel_updates == true) return false;
        showactivity("updating list");
        $.post("stacker.php", {action: "update"}, function (data) {updatenew(data);}, "json");

    }


    function forceupdate() {
        showactivity("updating list");
        $.post("stacker.php", {action: "update"}, function (data) {updatenew(data, true);}, "json");
    }


    function updatenew(tweetstack, nobubble) {

        if (typeof tweetstack == "undefined") {
            setTimeout("keepcurrent()", refresh_rate);
        } else {
            var html = "";
            var thisupdate = parseInt((new Date).getTime().toString().substring(0, 10));
	    var NewItems = new Object();
            for (var profile_id in tweetstack) {
                $("#" + profile_id).attr("id", profile_id + "_" + thisupdate);
                $("#" + profile_id + "_" + thisupdate).html("");
                $("#" + profile_id + "_" + thisupdate).remove();
                var newhtml = "";
                newhtml += "<div class=\"picture\"><img src=\"" + tweetstack[profile_id].user.profile_image_url + "\"></div>";
                newhtml += "<div class=\"profile_name\">";
                newhtml += "" + tweetstack[profile_id].user.name + " (<span id=\"" + profile_id + "name\">@" + tweetstack[profile_id].user.screen_name + "</span>) says:</div>";
                var first_id = null;
                var old_tweets = 0;
                var replies = 0;
                for (var tweet_id in tweetstack[profile_id].tweets) {
                    if (tweetstack[profile_id].tweets[tweet_id].repid != null) {
                        replies++;
                    }
                    if (first_id == null) {
                        first_id = tweet_id;
                        newhtml += "<div class=\"latest_tweet\">";
			newhtml += tweetstack[profile_id].tweets[tweet_id].text + "";
			newhtml += "<span class=\"timestamp\">&nbsp;" + tweetstack[profile_id].tweets[tweet_id].when + "</span>&nbsp;";
                        newhtml += replied_info(tweetstack[profile_id].tweets[tweet_id].replied);
                        newhtml += "</div>";
                    } else {
                        old_tweets++;
                        newhtml += "<div class=\"older_tweet\">";
                        newhtml += tweetstack[profile_id].tweets[tweet_id].text;
			newhtml += "<span class=\"timestamp\">&nbsp;" + tweetstack[profile_id].tweets[tweet_id].when + "</span>&nbsp;";
                        newhtml += "&nbsp;<img src=\"stuff/commentsm.png\" title=\"Reply\" onClick=\"replyto('" + profile_id + "','" + tweet_id + "');\">";
                        newhtml += replied_info(tweetstack[profile_id].tweets[tweet_id].replied);
                        newhtml += "</div>";
                    }
                }
                var starthtml = "";
                starthtml += "<div id=\"" + profile_id + "\" class=\"tweet " + thisupdate + "\">";
                starthtml += "<div class=\"buttons\">";
                starthtml += "<img src=\"stuff/commentsm.png\" title=\"Reply\" onClick=\"replyto('" + profile_id + "','" + first_id + "');\">";
                starthtml += "<img src=\"stuff/user_comment.png\" title=\"Direct Message\" onClick=\"dm('" + profile_id + "');\">";
                if (old_tweets > 0) {
                    starthtml += "<img src=\"stuff/expand.png\" title=\"Toggle Older Tweets\" onClick=\"expand('" + profile_id + "');\">";
                }
                if (replies > 0) {
                    starthtml += "<img src=\"stuff/convos.png\" title=\"Toggle Conversations\" onClick=\"convos('" + profile_id + "');\">";
                }
                starthtml += "</div>";
                html += starthtml + newhtml + "<div style=\"clear:both\"></div></div>";
		NewItems[profile_id] = profile_id;
            }
            if (html != "") {
                $("#twitterlist").prepend(html);
                $("." + thisupdate).css("background-image", "url('stuff/fade.gif')").fadeIn("slow");
            }
	    for (var profile_id in NewItems) {
		if(AllExpanded == true) {
			expand(profile_id);
			convos(profile_id);
		} else {
                	if(HistoryState[profile_id] == true) expand(profile_id);
			if(RepliesState[profile_id] == true) convos(profile_id);
		}
	    }
            if (nobubble != true) {
                setTimeout("keepcurrent()", refresh_rate);
            }
            done();
        }
    }


    function updateall() {
        $.post("stacker.php", {action: "list"}, function (data) {freshlist(data);}, "json");
    }


    function freshlist(tweetstack) {
        for (var profile_id in tweetstack) {
            if (tweetstack[profile_id].user) {
                var newhtml = "";
                newhtml += "<div class=\"picture\"><img src=\"" + tweetstack[profile_id].user.profile_image_url + "\"></div>";
                newhtml += "<div class=\"profile_name\">";
                newhtml += "" + tweetstack[profile_id].user.name + " (<span id=\"" + profile_id + "name\">@" + tweetstack[profile_id].user.screen_name + "</span>) says:</div>";
                var first_id = null;
                var old_tweets = 0;
                var replies = 0;
                for (var tweet_id in tweetstack[profile_id].tweets) {
                    if (tweetstack[profile_id].tweets[tweet_id].repid != null) {
                        replies++;
                    }
                    if (first_id == null) {
                        first_id = tweet_id;
			newhtml += "<div class=\"latest_tweet\">";
			newhtml += tweetstack[profile_id].tweets[tweet_id].text + "";
                        newhtml += "<span class=\"timestamp\">&nbsp;" + tweetstack[profile_id].tweets[tweet_id].when + "</span>&nbsp;";
                        newhtml += replied_info(tweetstack[profile_id].tweets[tweet_id].replied);
                        newhtml += "</div>";
                    } else {
                        old_tweets++;
                        newhtml += "<div class=\"older_tweet\">";
			newhtml += tweetstack[profile_id].tweets[tweet_id].text;
			newhtml += "<span class=\"timestamp\">&nbsp;" + tweetstack[profile_id].tweets[tweet_id].when + ":</span>&nbsp;";
                        newhtml += "&nbsp;<img src=\"stuff/commentsm.png\" title=\"Reply\" onClick=\"replyto('" + profile_id + "','" + tweet_id + "');\">";
                        newhtml += replied_info(tweetstack[profile_id].tweets[tweet_id].replied);
                        newhtml += "</div>";
                    }
                }
                var starthtml = "";
                starthtml += "<div id=\"" + profile_id + "\" class=\"tweet\">";
                starthtml += "<div class=\"buttons\">";
                starthtml += "<img src=\"stuff/commentsm.png\" title=\"Reply\" onClick=\"replyto('" + profile_id + "','" + first_id + "');\">";
                starthtml += "<img src=\"stuff/user_comment.png\" title=\"Direct Message\" onClick=\"dm('" + profile_id + "');\">";
                if (old_tweets > 0) {
                    starthtml += "<img src=\"stuff/expand.png\" title=\"Toggle Older Tweets\" onClick=\"expand('" + profile_id + "');\">";
                }
                if (replies > 0) {
                    starthtml += "<img src=\"stuff/convos.png\" title=\"Toggle Conversations\" onClick=\"convos('" + profile_id + "');\">";
                }
                starthtml += "</div>";
                newhtml = starthtml + newhtml + "<div style=\"clear:both\"></div></div>";
                $("#twitterlist").append(newhtml);
                $("#" + profile_id).fadeIn("fast");
            }
        }
        delete html;
        done();
    }


    function replied_info(reply,level) {

	if(typeof level == 'undefined') var level = 0;
	if(level>6) return null;
        var newhtml = "&nbsp;";
        if (reply != null) {
            var newhtml = "";
            if (reply.name != null) {
                newhtml += "<div class=\"replied_tweet thread" + level + "\">";
                newhtml += "<div class=\"replied_tweet_image\"><img src=\"" + reply.profile_image_url + "\"></div>";
                newhtml += "<div class=\"replied_tweet_user\">in reply to " + reply.name + "(<a target=\"_replied\" href=\"http://www.twitter.com/";
		newhtml +=  reply.screen_name + "\"><span id=\"" + reply.uid + "name\">@";
		newhtml += reply.screen_name + "</span></a>), who said:</div>";
                newhtml += reply.text;
                newhtml += "&nbsp;<img src=\"stuff/commentsm.png\" class=\"clickable\" title=\"Reply\" ";
		newhtml += "onClick=\"replyto('" + reply.uid + "','" + reply.id + "');\">";
		level++;
		newhtml += replied_info(reply.replied,level);
                newhtml += "</div>";
            }
        }
        return newhtml;
    }


    function logon(message) {
        $("#header a").fadeOut();
        if (typeof message == "undefined") {
            $("#logon").fadeIn();
        } else {
            $("#logon div.message").text(message);
            $("#logon").fadeIn();
        }
        done();
    }


    function authenticate() {
        $("#logon").fadeOut();
        working("Please Wait...");
        $.post("stacker.php", {action: "auth", user: $("#username").val(), pass: $("#password").val()}, function (data) {if (data.authenticated) {launch();} else {if (data.error) {logon("Error, Could Not Authenticate");} else {logon("Incorrect Username or Password");}}}, "json");
    }


    var HistoryState = new Object();
    function expand(profile_id) {

        $("#" + profile_id + " div.older_tweet").toggle();
	if($("#" + profile_id + " div.older_tweet").is(":hidden")) {
	    HistoryState[profile_id] = false;
	} else {
	    HistoryState[profile_id] = true;
	}

    }

    var RepliesState = new Object();
    function convos(profile_id) {
        $("#" + profile_id + " div.replied_tweet").toggle();
        if($("#" + profile_id + " div.replied_tweet").is(":hidden")) {
            RepliesState[profile_id] = false;
        } else {
            RepliesState[profile_id] = true;
        }

    }

    var AllExpanded = false;
    function expandall() {
	AllExpanded = true;
        $(".older_tweet").fadeIn();
        $(".replied_tweet").fadeIn();
    }


    function colapseall() {
	AllExpanded = false;
        $(".older_tweet").fadeOut();
        $(".replied_tweet").fadeOut();
    }


    function tweetlen() {
        if ($("#tweetinput").val().length > 140) {
            $("#tweetinput").val($("#tweetinput").val().substring(0, 140));
        }
        $("#tweetlength").text($("#tweetinput").val().length);
        return true;
    }


    function newtweet() {
        $("#indm").val("");
        $("#inreply").val("");
        $("#tweet div.message").text("");
        $("#tweetlength").text("0");
        $("#tweet").fadeIn();
        $("#tweetinput").val("");
        $("#tweetinput").focus();
    }


    function replyto(profile_id, reply_id) {
        $("#indm").val("");
        $("#tweetinput").val("");
        $("#tweet div.message").text("");
        $("#inreply").val(reply_id);
        $("#tweet").fadeIn();
        $("#tweetinput").val($("#" + profile_id + "name").text() + " ");
        $("#tweetlength").text($("#tweetinput").val().length);
        $("#tweetinput").focus();
    }


    function dm(profile_id) {
        var who = $("#" + profile_id + "name").text().replace("@", "");
        $("#indm").val(profile_id);
        $("#tweetinput").val("");
        $("#tweet div.message").text("Direct message to " + who + ".");
        $("#tweetlength").text($("#tweetinput").val().length);
        $("#tweet").fadeIn();
        $("#tweetinput").focus();
    }


    function canceltweet() {
        $("#indm").val("");
        $("#inreply").val("");
        $("#tweetinput").val("");
        $("#tweet div.message").text("");
        $("#tweetlength").text("0");
        $("#tweet").fadeOut();
    }


    function sendtweet() {
        showactivity("tweeting");
        if ($("#indm").val() != "") {
            $.post("stacker.php", {action: "dm", profile_id: $("#indm").val(), status: $("#tweetinput").val()}, function (data) {canceltweet();done();}, "json");
        } else {
            $.post("stacker.php", {action: "post", status: $("#tweetinput").val(), reply_id: $("#inreply").val()}, function (data) {canceltweet();done();}, "json");
        }
    }
