/**
 * @fileoverview Gulu "want to" post and friend feed JS module.
 * @author Ben Homnick <ben.homnick@geniecapital.com.tw>
 */
 
var Gulu = Gulu || {};
Gulu.WantTo = Gulu.WantTo || {};

/**
 * A single "want to" post, used in friend feed.
 * @extends Backbone.Model
 */
Gulu.WantTo.Post = Backbone.Model.extend({
    defaults: {
        id: null,
        category: null,
        expiry: null,
        html: ""
    }
});

/**
 * @extends Backbone.View
 */
Gulu.WantTo.PostView = Backbone.View.extend({
    tagName: 'li',
    className: 'pic_align_left feed_li',
    
    events: {
        'click .wantto_summary': 'getAction'
    },
    
    initialize: function() {
        _.bindAll(this, 'render', 'getAction', 'renderAction');
    },
    
    render: function() {
        $(this.el).html(this.model.get('html'));
        $(this.el).attr('id', 'post-' + this.model.id);
        return this;
    },
    
    /*
     * Fetches the activity stream action for this want to post if 
     * hasn't already been fetched.  Calls renderAction() regardless.
     */
    getAction: function() {
        var url = '/wantto/ajax/render_wantto_action/?object_id=' + this.model.get('id');
        $details = $('.wantto_details', '#post-' + this.model.get('id'));
        if($details.html() == "") {
            $.getJSON(url, function(data){
                $details.html(data.html);
            });
        }
        this.renderAction();
    },
    
    /*
     * Shows the activity stream action for this want to post, hiding all
     * other want to actions.
     */
    renderAction: function() {
        var id = '#post-' + this.model.id;
        // hide other want to posts
        $(this.el).parents('#ff_content').find('.wantto_summary').show();
        $(this.el).parents('#ff_content').find('.wantto_details').hide();
        
        // show the active want to post
        $('.wantto_summary', this.el).hide();
        $('.wantto_details', this.el).show();
    }
})

/**
 * A collection of "want to" posts.
 * @extends Backbone.Collection
 */
Gulu.WantTo.FriendFeed = Backbone.Collection.extend({
    model: Gulu.WantTo.Post,
    
    initialize: function() {
        _.bindAll(this, 'byCategory');
        this._categories = [];
    },
    
    url: "/wantto/read/",
    
    parse: function(response) {
        this._categories = response.categories;
        return response.posts;
    },
    
    /**
     * Sorts posts in this collection by category.
     * @param {string} filter Optional time identifier (i.e. this_week, this_weekend)
     *     to filter by.
     * @return {dict} Category => List of posts, ordered by expiry descending.
     */
    byCategory: function(filter) {
        var result = {}
        _(this.models).each(function(item){
            var category = item.get('category');
            var expiry = item.get('expiry');
            if(!filter || filter == '' || filter == 'all' || filter == expiry){
                if(category in result) {
                    result[category].push(item);
                } else {
                    result[category] = [item];
                }
            }
        }, this);
        return result;
    }
});

/**
 * Main friend feed view
 * @extends Backbone.View
 */
Gulu.WantTo.FriendFeedView = Backbone.View.extend({
    el: '#page-content',
    
    events: {
        'change #day_select_filter': 'doFilter'
    },
    
    initialize: function(){
        _.bindAll(this, 'render', 'doFilter');
        this.collection = new Gulu.WantTo.FriendFeed();
        this.collection.bind('reset', this.doFilter); 
        this.collection.fetch();
        
        this.letsGoView = new Gulu.WantTo.LetsGoView({collection: this.collection});
    },
    
    /**
     * @param {string} Optional time identifier (i.e. now, this_week) to filter
     *     posts by.
     */
    render: function(filter) {
        // save the let's go form from certain doom!
        $('.lets_go').hide();
        $("#ff_content").after($('.lets_go'));
        
        $("#ff_content").empty();
        content = this.collection.byCategory(filter);
        if(_.size(content) == 0) {
            $("#ff_no_posts").show();
            return;
        }
        $("#ff_no_posts").hide();
        
        _(content).each(function(posts, category){
            var $category = $(_.template($("#wantto_category_tmp").html(), {
                category: category,
                categoryLabel: this.collection._categories[category].label
            }));
            _(posts).each(function(post){
                var postView = new Gulu.WantTo.PostView({model: post});
                $category.find('ul.posts_list').append(postView.render().el);
            }, this);
            $("#ff_content").append($category);
        }, this);
    },
    
    doFilter: function() {
        this.render($('#day_select_filter').val());
    }
});

/**
 * Let's go event creation form
 * @extends Backbone.View
 */
Gulu.WantTo.LetsGoView = Backbone.View.extend({
    el: '#ff_content',
 
    events: {
        'click .lets_go_tab': 'render',
        'click .lets_go .cancel_btn': 'unrender'
    },
    
    initialize: function() {
        _.bindAll(this, 'render', 'unrender');
    },
    
    render: function(event) {
        event.preventDefault();
        var $target = $(event.currentTarget);
        var category = $target.attr('id').split('_')[1];
        $('.lets_go_tab').removeClass('on');
       
        // move the lets go form to the proper place
        $target.addClass('on');
        $target.after($('.lets_go'));
        
        // insert the suggested friends list
        $('.lets_go').find('.suggested_users').html(this.collection._categories[category].suggested_friends_html);
        $('.lets_go').trigger('reset_form');
        $('.ui_select.s').width(90);
        $('.lets_go').show();
    },
    
    unrender: function(event) {
        event.preventDefault();
        $('.lets_go').hide();
        $('.lets_go_tab').removeClass('on');
    }
});

