loader = new Element('img',{src:'/assets/images/ajax-loader.gif'});
var words;
var tweetReel;

Element.implement({
 	highlight: function(search, insensitive, klass){
		var regex = new RegExp('(<[^>]*>)|(\\b'+ search.escapeRegExp() +')', insensitive ? 'ig' : 'g');
		return this.set('html', this.get('html').replace(regex,
		    function(a, b, c)
		    {
    			return (a.charAt(0) == '<') ? a : '<strong class="'+ klass +'">' + c + '</strong>'; 
		    }
		));
	}
});

/**
 * Adds events to the share links
 **/
var shareLinks = function ()
{
    $$('li.delicious a').addEvent('click',
        function (ev)
        {
            ev.preventDefault();
            window.open(this.get('href'),'delicious','toolbar=no,width=550,height=550');
        }
    );

    $$('li.facebook a').addEvent('click',
        function (ev)
        {
            ev.preventDefault();
            window.open(this.get('href'),'facebook','toolbar=0,width=626,height=436');
        }
    );
    
    $$('li.digg a').addEvent('click',
        function (ev)
        {
            ev.preventDefault();
            window.open(this.get('href'),'digg','toolbar=0,width=626,height=436');
        }
    );
    
    $$('li.stumbleupon a').addEvent('click',
        function (ev)
        {
            ev.preventDefault();
            window.open(this.get('href'),'stumbleupon','toolbar=0,scrollbars=1,width=626,height=436');
        }
    );
};

var Tweet = new Class({
    Implements:         Log,
    initialize:         function (usr,msg,id,ref)
    {
        this.msg    = msg;
        this.user   = usr;
        this.id     = id;
        this.ref    = ref;
    },
    render:             function ()
    {
        this.container = new Element('div',{
            'id':       'tw'+this.id
        });
        
        this.container.setStyle('color',this.ref === 1 ? '#FFF' : '#555');
        this.container.set('class',this.ref === 1 ? 'active' : null);
        this.container.adopt(
            new Element('a',{
                'html':     this.user+':',
                'href':     'http://twitter.com/'+this.user
            })
        );

        msg = new Element('span',{
            'html':     ' '+this.msg
        });
        
        msg.highlight(words[0],true,'hl');
        msg.highlight(words[1],true,'hl');

        this.container.adopt(msg);
        return this.container;
    }
});

var TweetReel = new Class({
    Implements:         Log,
    tweets:             new Array,
    initialize:         function ()
    {
        return;
    },
    query:              function (search)
    {
        this.update();
        
        this.request = new Request.JSON(
        {
            url:            '/responder.php?action='+search
        });
        
        this.request.addEvent('onRequest',
            function ()
            {
                $('tweets').setStyles({
                    'background-image':     "url('/assets/images/ajax-loader.gif')",
                    'background-repeat':    'no-repeat',
                    'background-position':  'center 100px'
                });
            }
        );
        
        this.request.addEvent('onComplete',
            function (r)
            {
                $('tweets').setStyles({
                    'background-image':     null,
                    'background-repeat':    null,
                    'background-position':  null
                });
                this.addTweets(r);
            }.bind(this)
        );

        this.request.get();
    },
    addTweets:          function (tweets)
    {
        if(this.periodical)
        {
            $clear(this.periodical);
        }
        for(i = 0; i < tweets.results.length; i++)
        {
            this.tweets[i] = new Tweet(
                tweets.results[i].from_user,
                tweets.results[i].text,
                tweets.results[i].id,
                i
            );
            $('tweets').adopt(this.tweets[i].render());
        }
        this.periodical = this.cycle.periodical(3000);
    },
    cycle:              function ()
    {
        this.first = $('tweets').getElement(':first-child');

        fx = new Fx.Scroll($('tweets'));
        fx.addEvents({
            'complete':     function ()
            {
                $('tweets').adopt(this.first.dispose());
                fx.set(0,0);
            }.bind(this),
            'start':        function ()
            {
                this.first.getNext().tween('color',['#FFF','#555']);
                this.first.getNext().set('class',null);
                this.first.getNext().getNext().tween('color',['#555','#FFF']);
                this.first.getNext().getNext().set('class','active');
            }.bind(this)
        });

        fx.start(0,this.first.getSize().y);
    },
    update:             function ()
    {
        $clear(this.periodical);
        $('tweets').empty();
        this.tweets = new Array;
    }
    
});


var addAlphaGrads = function ()
{
    t = new Element('img',{
        'src':      '/assets/images/alpha-grad.png',
        'alt':      'gradient'
    });
    b = t.clone();
    b.set('src','/assets/images/alpha-grad-reversed.png');
    
    coords = $('tweets').getCoordinates();

    styles = {
        'position':  'absolute',
        'width':     coords.width,
        'height':    120,
        'left':      coords.left
    };
    
    t.setStyles(styles);
    b.setStyles(styles);
    
    t.setStyle('top',coords.top);
    b.setStyle('top',coords.top + coords.height - 120);
    
    document.getElement('body').adopt(t,b);
};

window.addEvents({
    'domready':     function ()
    {
        shareLinks();
        $('tweets').setStyles({
            'background-image':     "url('/assets/images/ajax-loader.gif')",
            'background-repeat':    'no-repeat',
            'background-position':  'center 100px',
            'height':               $('left').getCoordinates().height
        });
        
        document.getElements('ul.filters a').each(
            function (el)
            {
                el.addEvent('click',
                    function (e)
                    {
                        e.preventDefault();
                        words = this.get('class').split(' ');
                        tweetReel.query(this.get('rel'));
                        document.getElements('ul.filters a').each(
                            function (el)
                            {
                                el.getParent().set('class',null);
                            }
                        );
                        this.getParent().set('class','active');
                    }
                );
            }
        );
        
    },
    'load':         function ()
    {
        defaultLink     = document.getElement('ul.filters a');
        defaultLink.getParent().set('class','active');
        defaultAction   = defaultLink.get('rel');

        words = defaultLink.get('class').split(' ');

        $('tweets').setStyle('height',$('left').getCoordinates().height);
        addAlphaGrads();
        tweetReel = new TweetReel;
        tweetReel.query(defaultAction);
    }
});
