var Library_List = {
    init: function() {
        var self = this;
        var list = new List('library', {valueNames: ['status', 'title', 'type']});

        var type_filter = $('[name="type_filter"]');
        var status_filter = $('input[name="status_filter"]');

        self.filter(list, type_filter.val(), status_filter.filter(':checked').val());

        type_filter.on('change', function () {
            self.filter(list, $(this).val(), status_filter.filter(':checked').val());
        });

        status_filter.on('change', function () {
            self.filter(list, type_filter.val(), $(this).filter(':checked').val());
        });

        $('.library-rating').raty({starType : 'i', half: true, scoreName: 'rating', score: function() {
            return $(this).attr('data-score');
        }});

        $('.library-items').on('change', 'input', function() {
            var parent = $(this).closest('.library-item');
            var library_item_id = parent.data('library-item-id');

            var library_item = parent.find(':input').serializeObject();

            self.update_library_item(library_item_id, library_item)
        });

        $('.library-item-save').on('click', function() {
            var library_item_id = $(this).data('library-item-id');

            var library_item = $('#library-item-form-' + library_item_id).serializeObject();

            self.update_library_item(library_item_id, library_item)
        });
    },

    filter: function(list, type, status) {
        list.filter(function(item) {
            if (status === 'All') {
                var filter_status = true;
            } else {
                var filter_status = item.values().status == status;
            }

            return (item.values().type == type && filter_status);
        });
    },

    update_library_item: function(id, fields) {
        var library_item = {};
        library_item.id = id;

        if (typeof fields.amount_watched !== 'undefined') {
            library_item.amountWatched = fields.amount_watched;
        }

        if (typeof fields.notes !== 'undefined') {
            library_item.notes = fields.notes;
        }

        if (typeof fields.rating !== 'undefined') {
            library_item.rating = fields.rating * 2;
        }

        if (typeof fields.private !== 'undefined') {
            library_item.private = fields.private;
        }

        Library_Item.update(library_item);
    }
};

$(function(){
    if ($('#library').length != 0) {
        Library_List.init();
    }
});
