if ('undefined' == typeof bb) {
    bb = {};
}


function dump(val, scope) {

    return true;
    
    if ('undefined' != typeof console) {
        if (scope) {
            if ("string" == typeof val) {
                val = "[" + scope + "] " + val;
            }
            else {
                console.log("[" + scope + "]...");
            }
        }
        console.log(val);
    }

}



(function( $ ){
    
    var settings = {id: "#twitterbox", screenname: "", count: "5", basepath: "http://www.bitbox.de/_widgets/twitter/", label: '&nbsp;', color: '#65b6e2', speed: 16};
    var timerId = 0;
    var methods = {
        
        init: function (options) {
            dump("twitterbox.init!");
            
            return this.each(function() {
                
                if ('object' != typeof options || 'undefined' == typeof options.screenname) {
                    if ('undefined' != console) {
                        $.error("Mising option for twitterBox: screenname");
                    }
                    return;
                }

                settings = methods.getOpts(options, settings);
                //var settings = settings;

                dump("loading " + settings.count + " tweets for " + settings.screenname);
                var container = jQuery(settings.id);
                jQuery("head").append('<link rel="stylesheet" type="text/css" href="' + settings.basepath + 'twitter.css"></link>');
                jQuery(settings.id).append('<div class="twitter-row"><a href="http://twitter.com/#!/' + settings.screenname + '" class="twitterbox-label" target="_blank">' + settings.label + '</a><div class="tweetcontainer"><div class="tweet-scroller"><div id="tweets" class="tweets"><div class="tweet"></div></div></div></div></div>').addClass("twitterbox");


                var proxyUrl = settings.basepath + 'twitter.php?url=';
                var apiUrl = "";
                apiUrl += 'api.twitter.com/1/statuses/user_timeline.json';
                apiUrl += "?screen_name=" + settings.screenname;
                apiUrl += "&count=" + settings.count;
                apiUrl += "&trim_user=" + 1;
                apiUrl = encodeURI(apiUrl);

                proxyUrl += apiUrl + "&callback=?"; 

                dump("url: " + proxyUrl, "bb.twitter.init");
                jQuery.getJSON(proxyUrl, methods.render);

                methods.setColors(this);
            
                $(this).hover(methods.stop, methods.start);
                
                
            });

        },
        getOpts: function(options, defaults) {
            var settings = defaults;
            for (var key in defaults) {
                if (options[key]) {
                    settings[key] = options[key];
                }
            }
            dump(settings);
            return settings;

        },
        setColors: function(container) {
            var color = settings.color;
            var container = $(container);
            container.parents(".twitterbox").css({'border-color': color, 'background-color': color});
            container.find(".tweet-link").css({'color': color});
        }, 
        scroll: function() {
            
            timerId++;
            var first = $(".tweet").first();
            var parent = first.parent();
            var width = first.width();
            var left = parent.css("margin-left");
            left = parseInt(left);
            var rest = (width + left);
            var target = width * -1;
            var duration = rest * settings.speed;
            
            //dump("scroll: "+ timerId + ", w: " + width + ", l: " + left + ", r: " + rest + ", t: " + target + ", d: "+ duration);
            
            parent.animate({"margin-left": target}, duration, 'linear', function() {
                parent.css("margin-left", 0);
                parent.append(first.detach());
                methods.scroll();
            });
            
            
        },
        start: function() {
            methods.scroll();
        },
        stop: function() {
            $(".tweets").stop();
        },
        next: function() {
            return this.each(function() {
                var tweets = jQuery(this).find('.tweet');

                var current = tweets.filter(".active");
                if (0 == current.length)
                    current = tweets.first();

                var next = current.next();
                if (0 == next.length)
                    next = tweets.first();

                current.removeClass("active");
                current.fadeOut('slow', function() {next.fadeIn("slow"); next.addClass("active")});
            });
        },
        
        
        
        render: function(data) {
            dump(data, "bb.twitter.renderTweets");
            var tweets = data;
            _count = tweets.length;
            var container = jQuery(".tweets");
            var template = container.find(".tweet").first();
            
            for (var i = 0, len = tweets.length; i < len; i++) {
                var tweet = tweets[i];
                var item = template.clone();
                var linkedText = methods.linkify(tweet.text);
                var html = '<span class="tweet-date">' + methods.dateFormat(tweet.created_at) + "</span> " + linkedText;
                item.html(html);
                //item.hide();            
                container.append(item);
            }
            template.remove();
            //container.find(".tweet").first().show();
            
            methods.setColors(container);
            
            //window.setInterval('function() {$.twitterBox("next");}', 4000);
            methods.scroll();

        },
        dateFormat: function(dateString) {
            var date = new Date(dateString);
            var monthNames = {Jan: "01", Feb: "02", Mar: "03", Apr: "04", Mai: "05", Jun: "06", Jul: "07", Aug: "08", Sep: "09", Oct: "10", Nov: "11", Dec: "12"};
            var dateParts = dateString.match(/[a-z]{3} ([a-z]{3}) ([0-9]{2}).*([0-9]{4})/i);
            
            var day = dateParts[2];
            var month = monthNames[dateParts[1]];
            var year = dateParts[3];
            var formatted =  day + "." + month + "." + year + "";
            return formatted;
        },
        linkify: function(tweettext){ //by POLLO
            // ULREXTRACTION:
            tweettext = tweettext.replace( /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi, 
                function(url){
                    var tweet_url = url;  
                    if (!tweet_url.match('^https?:\/\/')) {
                        tweet_url = 'http://' + tweet_url;
                    }

                    url = url.replace(/(https?:\/\/)([a-z0-9\.-]{1,}[a-z]{2,}\/?)(.{0,8})(.*)/gi, "$2$3...");

                    return '<a href="' + tweet_url + '" class="tweet-link" target="_blank">' + url + '</a>';
                }
            )
            dump(tweettext);
            return tweettext;
        }
    };

    $.fn.twitterBox = function( method ) {
    
        dump("$.fn.twitterBox: " + method);

        // Method calling logic
        if ( methods[method] ) {
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.twitterBox' );
        }    

        };

    })( jQuery );
    
    
bb.twitterUpdate = {
    init: function (options) {
        dump(options);
        if (options && options.id) {
            
            jQuery(options.id).twitterBox(options);
        }
        else {
            $.error("No id given for twitterBox. Please use $(...).twitterbox();!");
        }
    }
}
