//试卷标记处理模块
var tag_process = function(option, success) {
    var object = new TagProcess(option);
    success();
    return object;
}

function TagProcess(option) {
    this.markControl = option.markControl;
    this.url = option.url;
    this.init();
    this.markControl.on('task.get.before', this, function(event, context, eventObject) {
        this.task = undefined;
        this.reset();
    });
    this.markControl.on('task.get.success', this, function(event, context, eventObject) {
        this.task = context.task;
        this.reset();
    });
    this.markControl.on('task.get.none', this, function(event, context, eventObject) {
        this.reset();
    });
    this.markControl.on('task.get.error', this, function(event, context, eventObject) {
        this.reset();
    });
}

TagProcess.prototype.init = function() {
    this.container = getDom(this.container_dom, this.markControl).appendTo(this.markControl.container.assistant);
    this.container.list = this.container.find('#type-list');
    this.container.title = this.container.find('.popover-title');

    var self = this;
    $.post(this.url, function(result) {
        for (var i = 0; i < result.length; i++) {
            var button = getDom(self.button_dom, self.markControl).appendTo(self.container.list);
            button.attr('data-value', result[i].value);
            button.html(result[i].name);
        }

        self.container.list.find('.tag-button').click(function(event) {
            $(this).toggleClass('curr');
            self.onTypeSelect();
        });
    });
}

TagProcess.prototype.reset = function() {
    //this.container.list.find('.tag-button').removeClass('curr');
	var self = this;
    if (this.task != undefined) {
        this.container.list.find('.tag-button').each(function(index, obj) {
            var value = $(obj).attr('data-value');
            if (self.task.tags != undefined && self.task.tags.indexOf(value) != -1) {
                $(obj).addClass('curr');
            } else {
                $(obj).removeClass('curr');
            }
        });
        this.container.show();
    } else {
        this.container.hide();
    }
}

TagProcess.prototype.onTypeSelect = function() {
    var self = this;
    if (this.task != undefined) {
        var array = [];
        this.container.list.find('.tag-button').each(function(index, obj) {
            if ($(obj).hasClass('curr')) {
                array.push($(obj).attr('data-value'));
            }
        });

        if (array.length > 0) {
            this.task.tags = array.join(',');
        } else {
            this.task.tags = undefined;
        }
    }
}

TagProcess.prototype.container_dom = '<h3 class="popover-title">标记试卷</h3>\
<div class="popover-content"><p id="type-list" class="popover-list">\
</p></div>';

TagProcess.prototype.button_dom = '<a class="tag-button" href="#"></a>';