//twitter api wiki: http://apiwiki.twitter.com/w/page/22554756/Twitter-Search-API-Method:-search

//this shows in firebug or ies console if active
function log(str) {
    if (window.console && window.console.log) {
        window.console.log(str);
    }

}

function getTime() {
    //do not change time here change it in the /twitter.asp at: <div class="twitterClientList" secondsOfLoop="6"
    //return parseInt($('.twitterClientList').attr('secondsOfLoop')) * 1000;
}

function returnClientResults(twitterUrl) {

    log('trying ' + twitterUrl);

    if ($('.cloned[title="' + twitterUrl + '"]').length > 0) {
        // if (false) {
        log('this div already exists - loading from dom instead of twitter ' + twitterUrl);
        clonedDiv = $('.cloned[title="' + twitterUrl + '"]');

        $("#tweets_fade").fadeIn(600, function() {
            $('#tweets').html(clonedDiv.html());
        });

        var fadeOut = setTimeout(function() {
            $("#tweets_fade").fadeOut(600);
        }, 200);

        var reload = setTimeout(function() {
            getRandomUnusedFeed();
        }, getTime());


    } else {
        //load already cloned div

        try {
            $.getJSON(twitterUrl,
        {},
        function(data) {
            try {
                twitterFromUser = data.results[0].from_user
                logoSrc = data.results[0].profile_image_url;
                var logoSrcLarge = logoSrc;

                //failing in ie (image or tweet isnt reloading!)
                logoSrcLarge = logoSrc.replace("normal.", "bigger.");

                twitterText = data.results[0].text
                   
				$('.twitter-text').html(replaceURLWithHTMLLinks(twitterText));

                //clone the div above so we dont have to refetch the twitterUrl json feed
                // and risk errors               

                $("#tweets").clone().attr('id', 'clone').css('display', 'none').attr('title', twitterUrl).addClass('cloned').appendTo($('.twitterClientList'));

                // log(twitterUrl + " <-- loaded");
                //reloads itself every min(comment to stop)
                setTimeout('getRandomUnusedFeed()', getTime());

            } catch (errInData) {
                errorCountHandleBadDataThenReload(twitterUrl, getTime(), "errInData")
            }

        });
        } catch (errInJsonFeed) {

            errorCountHandleReload(twitterUrl, getTime(), "errInJsonFeed")
        }
    } //end load fresh div

}

//removes link after bad load
function errorCountHandleBadDataThenReload(twitterUrl, time, errorPlace) {

    log("error" + errorPlace);
    //let the feed error once, try again and then remove link from dom
    $('.hadError[href="' + twitterUrl + '"]').remove();
    $('.client[href="' + twitterUrl + '"]').addClass('hadError');
    window.Errors++
    if (window.Errors < 40) {
        var reloadAfterErr = setTimeout(function() {
            getRandomUnusedFeed();
        }, time);
    }
}

function errorCountHandleReload(twitterUrl, time, errorPlace) {

    log("error" + errorPlace);

    window.Errors++
    if (window.Errors < 40) {
        var reloadAfterErr = setTimeout(function() {
            getRandomUnusedFeed();
        }, time);
    }
}


function wrapTable(text) {

    return "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"twitterWrap\"><tr><td align=\"left\" valign=\"middle\">" + text + "</td></tr></table>";
}

function returnCendynResults(twitterUrl) {

    $.getJSON(twitterUrl,
        {

    },
        function(data) {

            //$.each(data.results, function(i, result) {
            //    $("<li/>").html(replaceURLWithHTMLLinks(wrapTable(result.text))).appendTo("#twitterContainer .cendyn-footer-tweets");
                //alert(result.text)
            //});

            $('#twitterContainer').vTicker({
                speed: 1000,
                pause: 7000,
                animation: 'fade',
                mousePause: true,
                showItems: 1
            });

        });

    return true;
}

function getRandom(max) {
    return Math.floor(Math.random() * (max + 1));
}

function getRandomUnusedFeed() {

    //   log('callee: ' + arguments.callee.name);

    //reset all
    //   if (window.numLoops > 0) {
    if ($('.client[rel!="used"]').length == 0) {
        window.numLoops++;
        log('setting all un-used -- loop number' + window.numLoops);
        $('.client[rel="used"]').attr('rel', '').css('border', '1px solid black');
    }
    // }

    //-1 important
    var unusedLength = $('.client[rel!="used"]').length - 1
    feedNum = getRandom(unusedLength);

    if (unusedLength >= 0) {
        currentLink = $('.client[rel!="used"]').eq(feedNum);

        url = currentLink.attr('href')

        currentLink.attr('rel', 'used').css('border', '1px solid red');

        returnClientResults(url);

    } else {
        log('feedNum not found: ' + feedNum);

    }

}

function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp, "<a href='$1' target='_blank'>$1</a>");
}

//mh global window error handler ! careful!
window.onerror = function(msg, url, linenumber) {
    log('Global Error message: ' + msg + '\nURL: ' + url + '\nLine Number: ' + linenumber + " Error Index:" + window.Errors)

    window.Errors++
    if (window.Errors < 40) {
        var reloadAfterErr = setTimeout(function() {
            getRandomUnusedFeed();
        }, getTime());
    }
    return true;
}


$(document).ready(function() {

    window.Errors = 0;
    window.numLoops = 0;

    getRandomUnusedFeed();

    //returnCendynResults("http://search.twitter.com/search.json?q=from:cendyn&rpp=8&callback=?");

});
