var scrollCount = 0;
var stopX = 10;
var stopCount = 0;
var stopTime = 200;
var tweetCount = 0;
var tweetList = new Array();

var twithappyId = "twit-happy" + (+new Date);
var twithappy;

function timeline(timeline) {
    for (var i = 0; i < timeline.results.length; i++) {
        tweetList[i] = textFormat(timeline.results[i].text);
    }
}

function textFormat(text) {
    text = text.replace(/(https?:\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi, "<a href='$1' target='_blank'>$1</a>");
    text = text.replace(/@([a-zA-Z0-9_]+)/gi, "<a href=\"http://twitter.com/$1\" target=\"_blank\">@$1</a>");
    text = text.replace(/#([a-zA-Z0-9_]+)/gi, "<a href='http://twitter.com/search?q=%23$1' target='_blank'>#$1</a>");
    return text;
}

function scrollMessage() {
    if (!tweetList[tweetCount]) {
        setTimer();
        return;
    }
    var posX = twithappyWidth - scrollCount * twithappyScrollSpeed;

    if (posX < stopX) {
        posX = stopX;

        stopCount++;
        if (stopCount > stopTime) {
            stopCount = 0;
            scrollCount = 0;
            tweetCount++;
        }
        if (tweetCount == tweetList.length) {
            tweetCount = 0;
        }
    }

    if (stopCount < 1) {
        document.getElementById(twithappyId).innerHTML = '<nobr><div style="position:absolute;left:' + posX + 'px;">' + tweetList[tweetCount] + '</div></nobr>';
    } else if (stopCount == 1) {
        document.getElementById(twithappyId).innerHTML = '<div style="position:absolute;left:' + posX + 'px;">' + tweetList[tweetCount] + '</div>';
    }

    scrollCount++;

    setTimer();
}

function setTimer() {
    twithappy = setTimeout("scrollMessage()", 20);
}

//document.write('<scr' + 'ipt type="text/javascript" src="http://api.twitter.com/1/statuses/user_timeline.json?id=' + twithappyAccount + '&count=' + twithappyCount + '&callback=timeline"></scr' + 'ipt>');
document.write('<scr' + 'ipt type="text/javascript" src="http://search.twitter.com/search.json?q=from:' + twithappyAccount + '&rpp=' + twithappyCount + '&callback=timeline"></scr' + 'ipt>');
document.getElementById("twit-happy").innerHTML = '<div id="' + twithappyId + '" style="overflow: hidden;position: relative;width :' + twithappyWidth + 'px;height :' + twithappyHeight + 'px;padding :5 0 0 10;font-size:13px;color :#' + twithappyColor + ';background-color :#' + twithappyBackground + ';" onmouseover="javascript:clearTimeout(twithappy)" onmouseout="setTimer()"></div>';

setTimer();
