/**
 * @author timharwood
 */
//-------------------

var ListGalleryView = new Class({
    
    Extends: GalleryView,
    Implements: [Events, Options],
    
    options: {
        id: 'ListGalleryView'+new Date().getTime() + "-" + Math.random(),
        viewContainer: null,
        viewClass: '',
        dataProvider: null,
        debug: false
    },

    initialize: function(options){
        this.parent(options);
    },
    
    build: function(){        
        this.dataProvider.itemsCollection.getItems().each(function(item, index){
        
            var viewElem = item.getContent();
            var view = new ListGalleryItemView({
                viewContainer: viewElem
            });
            
            this.views.push(view);
            view.addDataProvider(item);
            
            this.viewContainer.adopt(viewElem);

            
        }.bind(this))
    },
    
    itemsIndexUpdate: function(e){
       this.showNextView(e)
    },

    showNextView: function(e){

    }
    
});

//-------------------

var ListGalleryItemView = new Class({

    Extends: SelectableItemView,
    Implements: [Events, Options],
    
    options: {
        id: new Date().getTime() + "-" + Math.random(),
        viewContainer: null,
        dataProvider: null,
        duration: 4000,
        viewClass: '',
        debug: false
    },
    
    
    build: function(){
       this.viewContainer.setStyles({
            position:'absolute'
        })
        this.updateDisplay();
    },

    dataProviderSelect: function(){
        this.updateDisplay();
    },
    
    dataProviderDeselect: function(){
        this.updateDisplay();
    },
    
    updateDisplay: function(){
        if (this.dataProvider.getSelected()){
            this.viewContainer.fade(1);
        } else {
            this.viewContainer.fade(0);
        }
    }

});







var TweetList = new Class({

    Implements: [Events, Options],
    
    options: {
        id: new Date().getTime() + "-" + Math.random(),
        twitterID: 'DustPR',
        tweetCount: 10,
        period: 50000, // IMPORTANT! Twitter only lets 150 polls per hr = 24000
        animDuration: 5000,
        fakeOnCancel: true,
        debug: false
    },
    
    timer:null,
    
    twitHolder:null,
    twidget:null,
    
    tweets:null,
    
    onTwidgetRequest:null,
    onTwidgetComplete:null,
    onTwidgetCancel:null,
    
    onNewTwidget:null,
    
    initialize: function(options){

        this.setOptions(options);
        this.createBoundMethods();
        
        this.createTweetsCollection();
        
        this.createHolder();
        this.newTwidget();
        this.createTimer();
        
    },

    createBoundMethods:function() {
       this.onTwidgetRequest = this.twidgetRequest.bind(this);
       this.onTwidgetComplete = this.twidgetComplete.bind(this);
       this.onTwidgetCancel = this.twidgetCancel.bind(this);
       this.onNewTwidget = this.newTwidget.bind(this);
    },

    createTweetsCollection:function() {
       this.tweets = new TimerplayCollection({
           autoplay: true,
           delay: this.options.animDuration
       });
       
    },

    createHolder:function() {
       this.twitHolder = new Element('div',{
           id:'twitHolder'
       });
    },
    
    createTimer:function() {
       this.timer = setInterval(this.onNewTwidget,this.options.period);
    },
    
    newTwidget:function() {
        this.twidget = new Twidget({ 
            user: this.options.twitterID, 
            count : this.options.tweetCount,
            element : this.twitHolder,
            onRequest : this.onTwidgetRequest, 
            onComplete: this.onTwidgetComplete,
            onCancel: this.onTwidgetCancel
        });
    },

    twidgetRequest:function(e) {

    },

    twidgetComplete:function(e) {
       this.repopulateTweets();
    },
    
    
    twidgetCancel:function(e) {
    	
       this.tweets.removeAllItems(true);
       clearInterval(this.timer);
       
       if (this.options.fakeOnCancel){
           //this.fakeTweets();
           this.repopulateTweets();
       }
       
    },
    
    fakeTweets:function() {
       this.twitHolder.empty();
       for (var i=this.options.tweetCount;i>0;i--) {

       	var twt = new Element('p',{
             'class':'tweet',
             'html':'This is no '+i+', a <a href="http://search.twitter.com/search?q=%23tweet">#tweet</a> that mentions <a href="http://twitter.com/mootools">@mootools</a> <a href="http://mootools.net">http://mootools.net</a>.<span class="when">3 days ago</span>'
         });
         
         this.twitHolder.adopt(twt);
       }
       
    },
    
    repopulateTweets:function() {
       var newTweets = this.twitHolder.getChildren('p');
       if (newTweets.length>0) {
           this.tweets.removeAllItems(true);
           
//           console.log(' --> %o %o',this.tweets)
           
           newTweets.each(function(el,idx){
               var tweetItem = new SelectableCollectionItem({
                   content: el.clone()
           	   });
               this.tweets.addItem(tweetItem);
           }.bind(this))
           
//           console.log(' -- --> %o %o',this.tweets)
       }
       
       var f = this.fireEvent('repopulate', {
            type: 'repopulate',
            target: this
        });
       if (this.tweets.getItems().length>0) {
           this.tweets.nextItem();
       }
       
    }
    
    
});


var TweetListGalleryView = new Class({
    
    Extends: GalleryView,
    Implements: [Events, Options],
    
    options: {
        id: 'TweetListView'+new Date().getTime() + "-" + Math.random(),
        viewContainer: null,
        viewClass: '',
        dataProvider: null,
        twitterID: '',
        debug: false
    },
    
    viewFX:null,
    tweetContainer:null,
    fullTweetContainer:null,

    initialize: function(options){
        this.parent(options);
    },
    
    addViewContainer: function(elem){
        this.parent(elem);

        if (this.viewContainer) {
            this.viewFX = new Fx.Tween(this.viewContainer,{
                unit:'px'
            });
            this.viewFX.addEvent('complete',this.vfxComplete.bind(this));
            this.viewContainer.addEvent('click',this.toggleFullView.bind(this));
            //this.viewContainer.addEvent('mouseleave',this.hideFullView.bind(this)); 
        }
        
       
    },
    
    
    addDataListeners: function(){
        this.dataProvider.tweets.addEvent('onIndexChange',this.onItemsIndexUpdate);
        this.dataProvider.addEvent('repopulate',this.build.bind(this));
    },
    
    removeDataListeners: function(){
        this.dataProvider.tweets.removeEvent('onIndexChange',this.onItemsIndexUpdate);
        this.dataProvider.removeEvents('repopulate');
    },
    
    build: function(){
        if (this.viewContainer) this.viewContainer.empty();
        this.tweetContainer = new Element('div',{
            id:'tweet'
        });

         this.fullTweetContainer = new Element('div',{
            id:'full-tweet'
        }).adopt(new Element('div', { 'class': 'full-tweet-header' } )
    		.adopt(new Element('img', { 'class': 'tweet-img', src: '/include/images/tweet.gif' } ))
    		.adopt(new Element('div', { 'class': 'tweets-text', html: 'Latest tweets ' } ))
    		.adopt(new Element('div', { 'class': 'close-tweets', html: 'X' } ))
    		.adopt(new Element('div', { 'class': 'follow-us' }).adopt(
    			new Element('a', { html: 'Follow US', href:'http://twitter.com/' + this.options.twitterID, target:'_blank' }) 
    			))
    	);
        
        this.dataProvider.tweets.getItems().each(function(item, index){
        
            var viewElem = item.getContent();
            var fullTweet = viewElem.clone();
            
            var view = new ListGalleryItemView({
                viewContainer: viewElem
            });
            
            this.views.push(view);
            view.addDataProvider(item);
            
            this.tweetContainer.adopt(viewElem);
            this.fullTweetContainer.adopt(fullTweet);

        }.bind(this));
        
        this.viewContainer.adopt(this.tweetContainer);
        this.viewContainer.adopt(this.fullTweetContainer);
    },
    
    itemsIndexUpdate: function(e){
       this.showNextView(e)
    },

    showNextView: function(e){

    },
    
    vfxComplete:function(e){
    	if(Math.abs(this.viewContainer.getStyle('margin-top').toInt())<1){
    		this.viewContainer.removeClass('full');	
    	}
    },

    showFullView: function(e){
		
		if($chk($$('#full-tweet p.tweet')[0])) {
			this.viewContainer.addClass('full');
			var fullTweetH = ($('full-tweet').getSize().y).toInt() - 18 ;
        	this.viewFX.start('margin-top','-' + fullTweetH);
		}
    },

    hideFullView: function(e){ 
        this.viewFX.start('margin-top','0');
    },

    toggleFullView: function(e){
        if (this.viewContainer.hasClass('full')) {
            this.hideFullView();
        } else {
            this.showFullView();
        }
    }
    
    
});

var TweetItemView = new Class({

    Extends: SelectableItemView,
    Implements: [Events, Options],
    
    options: {
        id: new Date().getTime() + "-" + Math.random(),
        viewContainer: null,
        dataProvider: null,
        duration: 4000,
        viewClass: 'tweet',
        debug: false
    },
    
    
    build: function(){
       this.updateDisplay();
    },

    dataProviderSelect: function(){
        this.updateDisplay();
    },
    
    dataProviderDeselect: function(){
        this.updateDisplay();
    },
    
    updateDisplay: function(){
        if (this.dataProvider.getSelected()){
            this.showDisplay();
        } else {
            this.hideDisplay();
        }
    },
    
    showDisplay: function(){
        this.viewContainer.fade(1);
    },
    
    hideDisplay: function(){
        this.viewContainer.fade(0);
    }
    
    
});


var twitList, twitListView, twitDiv;
var twitDivID='twitter-feed';

window.addEvent('domready', function(){
    twitDiv = $(twitDivID);
    twitList = new TweetList();
    twitListView = new TweetListGalleryView({
        viewContainer:twitDiv,
        twitterID:twitList.options.twitterID
    });
    twitListView.addDataProvider(twitList);
});







