(function ($) {
    
    app = {

        homeSlide : function(obj) {
            obj.find('img').css('opacity','0').eq(0).animate({'opacity':1},1000);
            var self = this;
                this.imgs = obj.find('img');
                this.count = this.imgs.length - 1;
                this.current = 0;
                this.slide = function(){
                    var now = self.current;
                    self.current = self.current === self.count ? 0 : now + 1;
                    obj.find('img').animate({opacity:0},1000).end().find('img').eq(self.current).animate({opacity:1},1000);
                };
            setInterval(self.slide, 6666);
        },
        
        imageGallery : function () {
            $('.image-gallery').each( function (i, gal) {
                var imgw = $(gal).closest('div.subcolumn').length ? 320 : 615;
                $(gal).find('.thumbs img').each( function (i, thumb) {
                    $(thumb).click( function () {
                        $(thumb).siblings().removeClass('selected').end().addClass('selected')
                        var large = $(gal).find('.large img').hide().eq(i);
                        large.show()
                        if (large.width() > imgw) {
                            large.css({'width':imgw} );
                        }
                        
                    });
                }).load().first().click();
                if ($('.thumbs img').size() == 1) {$('.thumbs img').hide()}
            });
        }
    },
    
    twitter = {
        init : function () {
            var Basket = [];
            $.getJSON('/tweets' , function(data, status){
                if (data)
                twitter.populate(data.slice(0,3))
            }, 'jsonp');
        },
        
        populate : function (tweets) {
            _.each(tweets, function (t) {
                this.html = $('<div></div>', {
                    'class' : 'unit update',
                    html : '<p>'+t.text+' <br/>From <a href="http://twitter.com/'+t.from_user+'">'+t.from_user+'</a></p>'
                }).appendTo('#updates')
            });
        }
    }
    
    $(document).ready(function () {
        if ($('.herobox').length) {
            app.homeSlide($('.herobox')); }
        if ($('#updates').length) {
            twitter.init(); }
        if ($('.image-gallery').length) {
            app.imageGallery(); }
    });
})(jQuery);
