/**
 * ATV Twitter Teaser Widget
 * Author: René Kersten (rene.kersten@exoet.com)
 */

var twitter_next_setup_callback_id = 0;

var AtvTwitter = new Class({
    initialize: function(profiles)
    {
        this.logger('initialize');
        this.profiles = profiles;
        this.myScroll = null;
        this.last_id = 0;
        this.box_wrapper = 'twitter_box_scroller';
        this.container_id = 'twitter_box_twitterlist';
        this.container = $(this.container_id) || new Element('ul', { id: this.container_id});
        this.update_interval = 30000;
        this.update_periodical = true;
        this.max_follow_links = 4;
        this.show_follow_links = true;

        this.callback_id = twitter_next_setup_callback_id++;
        this.update_timer = null;
        this.callback_update_script_tag = null;

        var link;

        window["twitter_callback" + this.callback_id] = this.onUpdateHandler.bind(this);


        if(this.show_follow_links)
        {
            var follow_list = $('twitter_box').getElement('.follow');
            follow_list.appendText('Follow ');

            if (this.profiles.indexOf('ATV') < 0)
            {
                this.profiles.push('ATV');
            }
    
            for (var i=0; i<=this.max_follow_links; i++)
            {
                if (this.profiles.hasOwnProperty(i))
                {
                    follow_list.grab(this.buildFollowLink(this.profiles[i]));
                    if (i < this.max_follow_links && i < profiles.length -1)
                    {
                        follow_list.appendText(' | ');
                    }
                }
            }
        }

        this.logger(profiles);
        this.logger('http://search.twitter.com/search.json?callback=twitter_callback' + this.callback_id + '&q=' + this.getSearchString());

        new Asset.javascript('http://search.twitter.com/search.json?callback=twitter_callback' + this.callback_id + '&q=' + this.getSearchString());
    },

    build : function(results)
    {
        this.logger('build');
        this.buildHtml(results);

        if (this.update_periodical)
        {

        }
    },


    buildHtml : function(results)
    {
        this.logger('buildHtml');
        this.logger(results);
        if (results.length)
        {
            for (var i = 0; i < results.length; i++)
            {
                this.logger('buildHtml: ' + results[i].id + ' last_id: ' + this.last_id + ' (' + (results[i].id > this.last_id) + ')');
                if(results[i].id > this.last_id)
                {
                    this.container.grab(this.renderTweet(results[i]), 'bottom');
                }
            }

            this.last_id = results[0].id;
            this.logger('set last_id: ' + this.last_id);

            $(this.box_wrapper).grab(this.container);

            var ua = navigator.userAgent;
            var isiUser = /iPad/i.test(ua) || /iPhone OS/i.test(ua);
            if(isiUser)
            {
                this.myScroll = new iScroll('twitter_box_scroller', {
                    hScrollbar: false
                });
            }
        }
    },


    update : function()
    {
        this.logger('update');
        if (this.callback_update_script_tag)
        {
            this.callback_update_script_tag.destroy();
        }
        this.callback_update_script_tag = new Asset.javascript('http://search.twitter.com/search.json?callback=twitter_callback' + this.callback_id + '&q=' + this.getSearchString() + '&since_id=' + this.last_id);
    },


    updateHtml : function(results)
    {
        this.logger('updateHtml');
        if (results.length)
        {
            for (var i = 0; i < results.length; i++)
            {
                this.logger('updateHtml: ' + results[i].id + ' last_id: ' + this.last_id + ' (' + (results[i].id > this.last_id) + ')');
                if(results[i].id > this.last_id)
                {
                    this.container.grab(this.renderTweet(results[i]), 'top');
                }
            }

            this.last_id = results[0].id;
            this.logger('set last_id: ' + this.last_id);
        }
    },


    renderTweet : function(data, position)
    {
        this.logger('renderTweet: ' + data.id);
        var tweet = new Element('li');
        var tweet_image = new Element('a', {
            'href': 'http://twitter.com/' + data.from_user,
            'target': '_blank'
        }).grab(new Element('img', {
            'src': data.profile_image_url}));
        var tweet_content = new Element('div', {'class': 'content'});
        var tweet_link = new Element('a', {'class': 'title', text: data.from_user, href: 'http://twitter.com/' + data.from_user, 'target': '_blank'});

        tweet.grab(tweet_image);
        tweet_content.grab(tweet_link);
        this.linkText(data.text);
        tweet_content.set('html', this.linkText(data.text));
        tweet.grab(tweet_content);

        return tweet;
    },

    onUpdateHandler: function(data)
    {
        this.logger('onUpdateHandler');
        if (!this.update_timer)
        {
            this.buildHtml(data.results);
            this.update_timer = this.update.periodical(this.update_interval, this);
        } else
        {
            this.updateHtml(data.results);
        }

        if(null !== this.myScroll)
            this.myScroll.refresh();
    },

    linkText: function(text)
    {
        this.logger('linkText');
        text = text.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(url)
        {
            return '<a href="' + url + '" target="_blank">' + url + '</a>';
        });

        text = text.replace(/[@]+[A-Za-z0-9-_]+/, function(u)
        {
            var username = u.replace("@", "");
            return '<a href="http://twitter.com/' + username + '" target="_blank">@' + username + '</a>';
        });

        text = text.replace(/[#]+[A-Za-z0-9-_]+/, function(t)
        {
            var tag = t.replace("#", "%23");
            return '<a href="http://search.twitter.com/search?q=' + tag + '" target="_blank">' + t + '</a>';
        });

        return text;
    },

    logger: function(log_message)
    {
        var logger_enabled = (project.environment != 'production');

        if (typeof console == 'object' && logger_enabled)
        {
            console.log('TwitterWidget', [log_message]);
        }
    },

    buildFollowLink: function(twitter_name)
    {
        var link = new Element('a', {
            'href': 'http://www.twitter.com/' + twitter_name,
            'target': '_blank'
        });

        link.innerHTML = '@' + twitter_name; //we need to set the link text via the native innerHTML property because MooTools fails in IE (<=8) when the string contains an '@';

        return link;
    },

    getSearchString: function()
    {
        return 'from:' + this.profiles.join(' OR from:');
    }

});

