/**
 * View for list of checked out documents
 */
var CheckedOutView = Backbone.View.extend({

    el : '#checked_out',
    collection : new CheckedOutCollection(),

    initialize : function() {
        this.setCollection(new CheckedOutCollection());
    },

    events : {
        "click a[name='cancel_checkout']" : "cancelCheckout",
        "click a[name='checkin']" : "checkin"
    },

    cancelCheckout : function(element) {
        element.preventDefault();
        if (confirm(lmsg("documents.details.cancel_checkout_confirm"))) {
            var doc = this.collection.get($(element.currentTarget).data('doc-id'));
            var parent_id = doc.get('parent_id');
            doc.destroy({success: function () {
                    docsShowMessage(lmsg('documents.checkin.cancel'), 'success');
                }});
            if (parent_id == docs_list_state.get('folder_id'))
                list_view.load(docs_list_state.get('folder_id'), 0, list_view.pagesize);
        }
    },

    checkin : function(element) {
        element.preventDefault();
        xajax_show_checkin_dialog($(element.currentTarget).data('doc-id'));
    },

    render : function() {
        if (!this.collection.is_loaded || this.collection.length == 0)
            this.setVisible(false);
        else
        {
            this.$el.show();
            var template = _.template($('#checked_out_template').html());
            this.$('#checked_out_items').empty();
            this.collection.each(function(doc, index) {
                var data = {};
                data.parent_id = doc.get('parent_id');
                data.doc_id = doc.get('doc_id');
                data.file_name = doc.get('title');
                data.icon = claIcon(doc.get('title'));
                this.$('#checked_out_items').append(template(data));
            }, this);
        }
    },

    setVisible : function(visible) {
        if (visible) {
            if (!this.collection.is_loaded)
                this.collection.load();
            this.render();
        } else
            this.$el.hide();
    },

    setCollection : function(collection) {
        if (this.collection) {
            this.collection.unbind('change', this.render, this);
            this.collection.unbind('reset', this.render, this);
            this.collection.unbind('remove', this.render, this);
            this.collection.unbind('add', this.render, this);
        }

        this.collection = collection;
        this.collection.bind('change', this.render, this);
        this.collection.bind('reset', this.render, this);
        this.collection.bind('remove', this.render, this);
        this.collection.bind('add', this.render, this);
    }
});
