//给分板模块
var mark_board = function(option, success) {
	var object = new MarkBoard(option);
	success();
	return object;
}

function MarkBoard(option) {
	this.markControl = option.markControl;
	this.timeoutSecond = 0.2;
	this.needConfirm = option.needConfirm === true ? true : false;
	this.autoSubmit = option.autoSubmit === false ? false : true;
	this.enableSkip = option.enableSkip === true ? true : false;
  //显分板上是否显示合分样式
  this.showObjectScoreAndSubjectScore = option.showTotalScore === true ? true : false;

	this.init();
	this.markControl.on('task.get.before', this, function(event, context, eventObject) {
		this.task = undefined;
		this.stepList = undefined;
		this.currentStep = undefined;
		this.stepCount = undefined;
		this.render();
	});
	this.markControl.on('task.load.finish', this, function(event, context, eventObject) {
		this.initByTask(context.task);
	});
	this.markControl.on('mark.track.set', this, function(event, context, track) {
		if(track != undefined && this.currentStep != undefined && this.currentStep.currentScore != undefined) {
			track.score = this.currentStep.currentScore;
			track.questionNumber = this.currentStep.questionNumber;
			track.number = this.currentStep.trackList.length + 1;
			this.currentStep.trackList.push(track);
			this.resetScore();
			this.updateStepScore();
			this.trySetScore(track.score);
			this.markControl.trigger('mark.track.show', track);
		}
	});
	this.markControl.on('key.press', this, function(e, context, event) {
        var code = event.keyCode;
        //console.log('key press:' + code);
        if (this.currentStep != undefined && this.task != undefined) {
            if (code >= 48 && code <= 57) {
                this.onNumberInput(code - 48);
                event.preventDefault();
                return false;
            } else if (code >= 96 && code <= 105 && event.numLock) {
                this.onNumberInput(code - 96);
                event.preventDefault();
                return false;
            } else if (code == 46 || code == 110 || code == 190) {
                //小数点
                this.onNumberInput('.');
                event.preventDefault();
                return false;
            }
        }
    });

    this.markControl.on('click.specialTag.before', this, function(event, context, eventObject) {
        this.resetScore();
    });
    this.markControl.on('show.track.event',this ,function(event,context,eventObject){
        if(this.stepList == undefined) {
            return;
        }
        for(var i = 0; i < this.stepList.length; i++) {
            var step = this.stepList[i];
            for(var j = 0; j < step.trackList.length; j++) {
                this.markControl.trigger('mark.track.show', step.trackList[j]);
            }
        }
    });
}

MarkBoard.prototype.init = function() {
	var self = this;
	this.stepBoard = getDom(this.step_board_dom, this.markControl).appendTo(this.markControl.container.centerContainer);
	this.stepBoard.height(this.markControl.container.centerContent.height());

	var stepDom = this.stepBoard.find('.step-list');
	stepDom.height((this.stepBoard.height() - 153) * 0.5);
	this.stepBoard.stepContainer = stepDom.find('ul');

	var scoreDom = this.stepBoard.find('.score_board');
	scoreDom.height((this.stepBoard.height() - 153) * 0.5);
	this.stepBoard.scoreContainer = scoreDom.find('ul');

	this.stepBoard.find('.task-submit-button').click(this, function(event) {
		self.onTaskSubmit();
	});
	this.stepBoard.find('.all-zero-button').click(this, function(event) {
		self.allZeroSubmit();
	});
	this.stepBoard.find('.undo-last-track-button').click(this, function() {
        self.markControl.trigger('click.track.before');
		if(self.currentStep != undefined && self.currentStep.trackList.length>0) {
			self.currentStep.trackList.pop();
			self.updateStepScore();
			self.refreshTrack();
			//self.markControl.trigger('mark.track.clear');
		}
	});
	this.stepBoard.find('.clear-current-track-button').click(this, function() {
        self.markControl.trigger('click.track.before');
		if(self.currentStep != undefined) {
			self.currentStep.currentScore = undefined;
			self.currentStep.trackList = [];
			self.updateStepScore();
			self.refreshTrack();
			//self.markControl.trigger('mark.track.clear');
		}
	});
	this.stepBoard.find('.clear-all-track-button').click(this, function() {
        self.markControl.trigger('click.track.before');
		if(self.stepList != undefined) {
			for(var i = 0; i < self.stepList.length; i++) {
				self.stepList[i].currentScore = undefined;
				self.stepList[i].trackList = [];
				self.updateStepScore(self.stepList[i]);
			}
			self.refreshTrack();
			//self.markControl.trigger('mark.track.clear');
		}
	});
    var dom5 = this.stepBoard.find(".sublist");
    var dom6 = this.stepBoard.find(".newSubListCss");
    if(this.showObjectScoreAndSubjectScore){
      dom6.show();
      dom5.hide();
    }else {
      dom6.hide();
      dom5.show();
    }
}

MarkBoard.prototype.initByTask = function(task) {
	this.task = task;
	this.stepList = task.markStepList;
	this.currentStep = undefined;
	this.stepCount = this.stepList != undefined ? this.stepList.length : 0;

	task.totalScore = parseFloat(task.totalScore);
	var markFinish = true;
	var scoreList = task.scoreList != undefined && task.scoreList != '' ? task.scoreList.split(',') : [];
	for(var j = 0; j < task.markStepList.length; j++) {
		var step = task.markStepList[j];
		step.scoreArray = [];
		if(step.trackList == undefined) {
			step.trackList = [];
		}
		if(scoreList != undefined && scoreList.length > j) {
			step.markScore = parseFloat(scoreList[j]);
			step.markFinish = true;
		} else {
			step.markFinish = false;
			markFinish = false;
		}
	}
	task.markFinish = task.totalScore != undefined && markFinish == true;

	this.render(task);
	this.refreshTrack();
	if(this.stepCount > 0) {
		this.onStepSelect(1);
	}
}

MarkBoard.prototype.render = function(task) {
	if(task != undefined) {
		var self = this;
		this.stepBoard.stepContainer.empty();
		this.stepBoard.scoreContainer.empty();
		this.stepArray = [];

		if(task.markFinish === true) {
			this.stepBoard.find('#total-score').html(task.totalScore + '');
			this.stepBoard.find('#subject-score').html(task.totalScore + '');
      this.stepBoard.find('#ObjectiveAndSubjectScore').html((task.totalScore+task.objectiveScore) + '');
		} else {
			this.stepBoard.find('#total-score').html('');
			this.stepBoard.find('#subject-score').html('');
      this.stepBoard.find('#ObjectiveAndSubjectScore').html(task.objectiveScore);
		}

		for( var i in task.markStepList) {
			var step = task.markStepList[i];
			// 初始化步骤列表
			var dom = getDom(this.step_dom, this.markControl).appendTo(this.stepBoard.stepContainer);
			dom.attr('data-number', step.number);
			dom.find('p').html(step.title);
			dom.find('h2').html(step.markScore != undefined ? step.markScore : '');
			dom.click(function() {
				self.onStepSelect($(this).attr('data-number'));
			});
			this.stepArray.push(dom);
			step.dom = dom;
		}
	} else {
		this.stepBoard.stepContainer.empty();
		this.stepBoard.scoreContainer.empty();
		this.stepArray = [];
		this.stepBoard.find('#total-score').html('');
		this.stepBoard.find('#subject-score').html('');
    this.stepBoard.find('#ObjectiveAndSubjectScore').html('');
	}
}

MarkBoard.prototype.onStepSelect = function(stepNumber) {
	if(stepNumber <= this.stepCount && stepNumber > 0) {
		var self = this;
		// 还是点击当前步骤，不触发任何动作
		if(this.currentStep != undefined && this.currentStep.number == stepNumber) {
			return;
		}

		// 修改原step状态
		if(this.currentStep != undefined) {
			this.currentStep.dom.removeClass('selected');
			this.currentStep.currentScore = undefined;
			this.currentStep.scoreArray = [];
		}

		this.currentStep = this.stepList[stepNumber - 1];
		this.currentStep.currentScore = undefined;
		this.currentStep.scoreArray = [];
		this.currentStep.dom.addClass('selected');

		this.stepBoard.scoreContainer.empty();
		for(var i = 0; i < this.currentStep.scoreList.length; i++) {
			var score = this.currentStep.scoreList[i];
			var dom2 = getDom(this.score_dom, this.markControl).appendTo(self.stepBoard.scoreContainer);
			dom2.find('p').html(score);
			dom2.attr('data-score', score);
			dom2.attr('data-number', (i + 1));
			this.currentStep.scoreArray.push(dom2);

			if(this.currentStep.markScore != undefined && score > (this.currentStep.max - this.currentStep.markScore)) {
				dom2.hide();
			}

			dom2.click(function() {
				self.onScoreClick($(this).attr('data-number'));
			});
		}
	}
}

MarkBoard.prototype.onNumberInput = function(number) {
	var self = this;
	if(this.currentStep == undefined){
		return;
	}
	if(this.numberInput == undefined){
		this.numberInput = '0';
	}
	this.numberInput = this.numberInput + number;
	if(this.timeoutId != undefined){
		clearTimeout(this.timeoutId);
	}
	this.timeoutId = setTimeout(function(){
		self.inputTimeout();
	}, this.timeoutSecond * 1000);
}

MarkBoard.prototype.inputTimeout = function() {
	if(this.currentStep!=undefined && this.numberInput!=undefined && this.numberInput.length>0){
		if(this.numberInput.endWith('.')){
			this.numberInput = this.numberInput + '5';
		}
		this.trySetScore(parseFloat(this.numberInput));
	}
	this.numberInput=undefined;
	this.timeoutId=undefined;
}

MarkBoard.prototype.onScoreClick = function(scoreNumber) {
    //禁止 特殊标识的使用
    this.markControl.trigger('click.track.before');
	if(this.task == undefined || this.currentStep == undefined) {
		return;
	}
	for(var i = 0; i < this.currentStep.scoreArray.length; i++) {
		var dom = this.currentStep.scoreArray[i];
		if(scoreNumber == dom.attr('data-number')) {
			if(dom.hasClass('selected')) {
				dom.removeClass('selected');
				this.currentStep.currentScore = undefined;
			} else {
				dom.addClass('selected');
				this.currentStep.currentScore = parseFloat(dom.attr('data-score'));
			}
		} else {
			dom.removeClass('selected');
		}
	}
}

MarkBoard.prototype.trySetScore = function(score) {
	var scoreNumber = undefined;
	if(this.currentStep != undefined && score != undefined) {
		for(var i = 0; i < this.currentStep.scoreArray.length; i++) {
			var dom = this.currentStep.scoreArray[i];
			if(!dom.is(':hidden') && parseFloat(dom.attr('data-score'))==score){
				scoreNumber = dom.attr('data-number');
				dom.removeClass('selected');
			}
		}
	}
	if(scoreNumber!=undefined){
		this.onScoreClick(scoreNumber);
	}
}

MarkBoard.prototype.resetScore = function() {
	if(this.currentStep != undefined) {
		for(var i = 0; i < this.currentStep.scoreArray.length; i++) {
			this.currentStep.scoreArray[i].removeClass('selected');
		}
		this.currentStep.currentScore = undefined;
	}
}

MarkBoard.prototype.refreshTrack = function() {
	if(this.stepList == undefined) {
		return;
	}
	this.markControl.trigger('mark.track.clear');
	for(var i = 0; i < this.stepList.length; i++) {
		var step = this.stepList[i];
		for(var j = 0; j < step.trackList.length; j++) {
			this.markControl.trigger('mark.track.show', step.trackList[j]);
		}
	}
}

MarkBoard.prototype.updateStepScore = function(step) {
	if(step == undefined) {
		step = this.currentStep;
	}
	if(step == undefined) {
		return;
	}
	var totalScore = undefined;
	for(var i = 0; i < step.trackList.length; i++) {
		if(totalScore == undefined) {
			totalScore = 0;
		}
		totalScore += parseFloat(step.trackList[i].score);
	}
	var leftScore = totalScore != undefined ? (step.max - totalScore) : step.max;
	for(var i = 0; i < step.scoreArray.length; i++) {
		var dom = step.scoreArray[i];
		dom.removeClass('selected');
		if(parseFloat(dom.attr('data-score')) > leftScore) {
			dom.hide();
		} else {
			dom.show();
			if(step.currentScore!=undefined && step.currentScore==parseFloat(dom.attr('data-score'))){
				dom.addClass('selected');
			}
		}
	}
	if(totalScore != undefined) {
		step.markFinish = true;
		step.markScore = totalScore;
		step.dom.find('h2').html(this.currentStep.markScore);
	} else {
		step.markFinish = false;
		step.markScore = undefined;
		step.dom.find('h2').html('');
	}
	this.updateTotalScore();
}

MarkBoard.prototype.updateTotalScore = function() {
	if(this.task != undefined) {
		var totalScore = '';
		var finish = true;
		for(var i = 0; i < this.stepList.length; i++) {
			if(this.stepList[i].markScore != undefined) {
				if(totalScore == '') {
					totalScore = 0;
				}
				totalScore += this.stepList[i].markScore;
			} else {
				finish = false;
			}
		}
		var ObjectiveAndSubjectScore = totalScore+this.task.objectiveScore;
		this.task.totalScore = totalScore;
		this.task.markFinish = finish;
		this.stepBoard.find('#ObjectiveAndSubjectScore').html(ObjectiveAndSubjectScore);
		this.stepBoard.find('#total-score').html(totalScore);
		this.stepBoard.find('#subject-score').html(totalScore);
	}
}

MarkBoard.prototype.allZeroSubmit = function() {
	if(this.task != undefined && this.stepList != undefined && this.stepList.length > 0 && confirm('确认要提交零分卷吗？')) {
		for(var i = 0; i < this.stepList.length; i++) {
			this.stepList[i].markFinish = true;
			this.stepList[i].markScore = 0;
			this.stepList[i].trackList = [];
			this.stepList[i].trackList.push({
			    questionNumber: this.stepList[i].questionNumber,
			    number: 1,
			    score: 0,
			    positionX: 0,
			    positionY: 0
			});
		}
		this.onTaskSubmit();
	}
}

MarkBoard.prototype.onTaskSubmit = function() {
	if(this.task == undefined) {
		return;
	}
	var totalScore = 0;
	var scoreList = [];
	var trackList = [];
	var finish = true;
	for( var i in this.stepList) {
		var score = this.stepList[i].markScore;
		var tracks = this.stepList[i].trackList;
		if(score != undefined) {
			totalScore = totalScore + score;
			scoreList.push(score);
		} else {
			finish = false;
		}
		if(tracks != undefined) {
			trackList = trackList.concat(tracks);
		}
	}
	if(!finish) {
		alert('当前任务还有未给分的题，请继续给分');
	} else if(!this.needConfirm || confirm('主观分为' + totalScore + ', 确认要提交吗？')) {
		this.task.totalScore = totalScore;
		this.task.scoreList = scoreList.join(',');
		this.task.trackList = trackList;
		this.markControl.submitTask();
	}
}

MarkBoard.prototype.step_board_dom = '<div class="span3 mark-steps"><div class="step-board">\
  <div class="newSubListCss"><span class="fraction" style="">主观分<i class="red" id="subject-score"></i></span>\
  <span class="fraction">总分<i class="red" id="ObjectiveAndSubjectScore"></i></span></div>\
  <div class="sublist"><p class="fraction">总分 <i class="red" id="total-score"></i></p></div>\
	<div class="button"><input type="submit" value="零分卷" class="btn1 all-zero-button"/>\
	<input type="submit" value="提&nbsp;交" class="btn2 task-submit-button"/></div>\
	<div class="step-list"><div class="number"><ul></ul></div></div>\
	<div class="score_board"><div class="score"><ul></ul></div></div>\
	<div class="clear_button">\
	<input type="submit" value="回退" class="btn1 undo-last-track-button" />\
	<input type="submit" value="清除本题" class="btn1 clear-current-track-button" />\
	<!--<input type="submit" value="清除全卷" class="btn1 clear-all-track-button"/></div>-->\
	</div></div>';

MarkBoard.prototype.step_dom = '<li><a href="#"><p></p><h2></h2></a></li>';

MarkBoard.prototype.score_dom = '<li><a href="#"><p></p></a></li>';