/* Config object */
var config = {
    parent: '.tweets',
    feedUrl: '/tweets/',
    updateInterval: 60, //in seconds
    parties: ['ap', 'r', 'sv', 'h', 'v', 'frp', 'krf', 'sp', 'd', 'ks']
};

/* Tweet provider */
var TweetProvider = function(conf) {
    this.conf = conf;
};
TweetProvider.prototype = {
	getTweets: function(id, filter, success, error) {
        var strId = ( id && id !== undefined ) ? id.type + '=' + id.value + '&' : '';
        var url = this.conf.feedUrl + '?' + strId + 'filter=' + filter.join(',');
        $.ajax({
            type: 'GET',
            url: url,
            dataType: 'html',
            success: success,
            error: error
        });
	}
};

/* Display module */
var ListDisplay = function(list) {
	this.container = $(list);
};
ListDisplay.prototype = {
	add: function(listItems, method) {
        this.container[method || 'prepend'](listItems);
        var that = this;
        if ($.trim(listItems).length > 0) {
           $(listItems).each(function() {
               that.highlight($(this));
           });
        }
    },
    clear: function() {
        this.container.empty();
    },
    showError: function(message) {
        var elem = $('<li class="error">' + message + '</li>');
        this.add(elem, 'prepend');
    },
    getNewId: function() {
        return $('li:first', this.container).attr('id');
    },
    getOldId: function() {
        return $('li:last', this.container).attr('id');
    },
    highlight: function(tweet) {
        if( tweet.is('li') ) {
            var tweet_id = tweet.attr('id');
            $('#' + tweet_id).animate({ backgroundColor: "#ffff99" }, 500).animate({ backgroundColor: "#ffffff" }, 500);
        }
    }
};

/* Twitter feed */
var TweetFeed = function(display, provider, conf) {
    this.display = display;
    this.provider = provider;
    this.conf = conf;
    
    var filter = $.merge([], conf.parties);
    //this.createResetControl();
    
    this.setRestriction = function(id) {
        if( $.inArray(id, filter) < 0 ) {
            filter.push(id);
        }
    };
    this.clearRestriction = function(id) {
        var index = $.inArray(id, filter);
        if( index > -1 ) {
            filter.remove(index);
        }
    };
    this.resetFilter = function() {
        filter = $.merge([], this.conf.parties);
    };
    this.getFilter = function() {
        return filter;
    };
};
TweetFeed.prototype = {
    startUpdates: function() {
        var that = this;
        this.interval = setInterval(function() { 
                that.update({ type: 'newId', value: that.display.getNewId() });
            }, this.conf.updateInterval * 1000);
    },
    stopUpdates: function() {
        clearInterval(this.interval);
    },
    update: function(id) {
		var that = this;
        this.provider.getTweets(id, this.getFilter(), function(res) {
            if( !id ) {
                that.display.clear();
            }
            var method = (id && id.type == 'oldId') ? 'append' : 'prepend';
            that.display.add(res, method);
            $(".date").prettierDate();
        }, function(x, s, e) { that.handleError(x, s, e); });
    },
    handleError: function(xhr, status, error) {
        //this.display.showError('TweetFeed: ' + status + ' ' + error);
    }/*,
    createResetControl: function() {
        var that = this;
        var list = $('#parties');
        this.clearBtn = $('<div id="clear">Vis alle</div>');
        this.clearBtn.click(function() {
                that.resetFilter();
                that.update();
                list.children().removeClass('disabled');
                $(this).hide();
            }).hide();
        $('#meta_filtering').append(this.clearBtn);
    }*/
};

var feedManager = {
    createTweetFeed: function(conf) {
        var displayModule = new ListDisplay(config.parent);
        var tweetProvider = new TweetProvider(conf);
        return new TweetFeed(displayModule, tweetProvider, conf);
    }
};

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};

var RegistrationHandler = function() {
    var that = this;
    this.form = $('#new_unapproved_author');
    this.lb = new Lightbox($('#lightbox'), $('#overlay'));
    
    this.form.submit(function(e) {
        that.handleRegistration($(this).serialize());
        return false;
    });
    $('#register').click(function() {
        that.lb.show();
        return false;
    });
};
RegistrationHandler.prototype = {
    successMsg: 'Takk for din registrering!',
    errorMsg: 'Registreringen feilet, ' +
              'forsøk igjen eller send en ' +
              'epost til post@twittertinget.no',
    handleRegistration: function(formData) {
        var that = this;
        $.ajax({
            type: 'POST',
            url: this.form[0].action,
            dataType: 'html',
            data: formData,
            success: function(res) {
                that.registrationCompleted(that.successMsg, 'info');    
            },
            error: function(x, s, e) {
                that.registrationCompleted(that.errorMsg, 'error');
            }
        });
    },
    registrationCompleted: function(msg, resType) {
        this.lb.hide();
        this.showInfo(msg, resType);
    },
    showInfo: function(message, className) {
        var info = $('<div class="'+ className +'">'+ message +'</div>');
        info.hide();
        $('#related_info').prepend(info);
        info.slideDown();
        var timer = setTimeout(function() {
            info.slideUp();
        }, 5000);
    }
};

var Lightbox = function(lightboxEl, overlayEl) {
    this.lb = lightboxEl;
    this.ol = overlayEl;
    var that = this;
    $('.cancel', this.lb).click(function(e) {
        that.hide();
        return false;
    });
};
Lightbox.prototype = {
    show: function() {
        this.ol.css('height', $(document).height());
        this.ol.css({display:'block'});
        //this.ol.fadeIn();
        this.lb.css({
            top: $(window).scrollTop() 
                 + $(window).height()/2 
                 - this.lb.height()/2,
            display: 'block'
        });
    },
    hide: function() {
        this.ol.css({display:'none'});
        this.lb.hide();
    }
};

$(document).ready(function(){
   	$(".date").prettierDate();

    var regHandler = new RegistrationHandler();    
    var feed = feedManager.createTweetFeed(config);
    feed.startUpdates();
	
    $('#parties li a').click(handleFiltering);
    $('#meta_filtering li a').click(handleFiltering);
    $('#show_more').click(showHistory);
    $('#clear').click(showOtherParties);
    
    function handleFiltering(e) {
        var item = $(this).parent();
        if( item.hasClass('disabled') ) {
            enable(item, this.id);
        } else {
            var allParties = $('#parties li, #meta_filtering li:not(.seperator)');

            if( $(allParties).filter('.disabled').length === 0 ) {
                $(allParties).each(function() {
                    disable($(this), $(this).find('a').attr('id'));
                });
                enable(item, this.id);
            } else {
                disable(item, this.id);
                if( $(allParties).filter(":not('.disabled')").length === 0 ) {
	                  feed.resetFilter();
	                  $(allParties).removeClass('disabled');
                }
            }
        }
        /* drop clear button
        if( item.siblings('.disabled').length === 0 ) {
            feed.clearBtn.hide();
        } else {
            feed.clearBtn.show();
        }*/
        feed.update();
        return false;
    }
    
    function enable(item, id) {
        item.removeClass('disabled');
        feed.setRestriction(id);
    }
    function disable(item, id) {
        item.addClass('disabled');
        feed.clearRestriction(id);
    }
    
    function showHistory(e) {
        feed.update({
                type: 'oldId', 
                value: feed.display.getOldId()
            });
        return false;
    }
		
    function showOtherParties(e) {
        $('#meta_filtering ul').toggle();
    }
});

/**
 * Fikser flikking i bakgrunnsbilder i IE
 */
/*@cc_on
	@if (@_win32)
		try {
			document.execCommand("BackgroundImageCache", false, true);
		} catch(err) {};
	@end @*/