/** 
 * 中文词语评测卡片
 * @module speechui/cards/CnWordEvalCard
 * @date 2013/06/09
 */

define(function (require, exports, module) {
    var _enwordcard = require('./enwordeval');
    var _speech     = require('../common/speech');
    var _define     = require('../define');
    var _tplParse   = require('../thirdparty/template');
    var mask        = require('../common/mask');
    var pyUtil      = require('../common/pinyinutil');
    var $           = require('jquery');

    // 中文单词评测错误码
     var ErrorCode = {
        //声母错
        ErrorVowel : 1,
        //韵母错
        ErrorConsonant : 2,
        //声调错
        ErrorTone : 4
    };

    /**
     * 卡片初始化
     * @param {{
     *     id:       string,
     *     paperUrl: string,
     *     audios:   Array.<string>
     * }} options  卡片加载参数
     * @extends {speechui.cards.enwordeval.EnWordEvalCard}
     */
    function CnWordEvalCard(options){
       _enwordcard.Constructor.call(this);  //EnCard构造函数为空
       this.wordPaper = [];
       this.pyArray = [];
       this.init(options);
    }

    CnWordEvalCard.prototype = new _enwordcard.Constructor();
    CnWordEvalCard.prototype.constructor = CnWordEvalCard;

    /**
     * 获取卡片名称
     * @return String
     * @protected
     */
    CnWordEvalCard.prototype.getCardName = function () {
        return _define.CardName.CnWordEval;
    };

    /**
     * 获取卡片单词信息
     * @protected
     */
    CnWordEvalCard.prototype.getWordInfo = function () {
        //初始化wordArray、scoreArray和records
        var array = this.paper.split("\n");
        var i = 0, j = 0;

        for(i = 0; i < array.length; i++){
            if(array[i].length === 0){
                array.splice(i,1);
                i--;
            }
        }
        for(i = 1, j = 1; i < this.audios.length * 2; i += 2, j++){
            this.wordArray[j] = array[i];
            var arr = [];
            for(var k = 0; k < array[i].length; k++){
                arr.push(array[i].charAt(k));
            }
            this.panelWord[j] = arr;
            this.wordPaper[j] = array[0] + '\n' + array[i] + '\n' + array[i+1];
        }

        for(i = 2; i < array.length; i += 2){
            this.pyArray.push(array[i].replace(/\|/g,""));
        }

        for(i = 0; i < this.wordArray.length - 1; i++ ){
            var py = pyUtil.PinYinUtil.getSYmu(this.pyArray[i]);
            var info = {
                py    : py,
                error : 0
            }
//            var info = {
//                py    : '',
//                error : ''
//            };
            this.scoreArray.push(info);
            info = {
                id    : '',
                begin : 0 ,
                end   : 0 ,
                flag  : true ,
                time  : 0
            };
            this.records.push(info);
        }
    };

    /**
     * 卡片渲染
     * @return String
     * @protected
     */
    CnWordEvalCard.prototype.render = function () {
        var text = {
            index : [],
            words : []
        };
        for (var i = 1; i < this.panelWord.length; i++) {
            text.index.push({
                index  : i-1,
                words  : this.panelWord[i]
            });
        }
        return _tplParse.render(this.tpl, text);
    };

    /**
     * 点击事件
     * @protected
     */
    CnWordEvalCard.prototype.registerClickEvent = function () {
        this.clickEvent = {
            onStartRec : function(){
                if(_speech.speecher.Recorder.isReady){
                    var dom = this.dom;
                    this.recordID = "word-card-" + new Date().getTime();
                    var success = _speech.speecher.Recorder.record({
                        evalType: SeEvalType.ReadWordCn,
                        evalText: this.paper,
                        evalParams: "vadEnable=true, vadSpeechTail=2500",
                        sndId: this.recordID
                    });
                    LogUtil.debug("Begin record:" + success);
                    if(success){
                        this.curStatus = this.Status.recording;
                        this.disableAllFunBtn();
                        dom.find('.word_startRec').hide();
                        dom.find('.word_stopRec').show();
                        this.enableSingleFunBtn('.word_stopRec');
                    }
                }
            },
            onStopRec : function() {
                var success = _speech.speecher.Recorder.stop();
                if(success){
                    this.disableSingleFunBtn('.word_stopRec');
                    this.maskOption.type = this.maskType.common;
                    this.maskOption.msg = "正在评测中，请稍候";
                    this.maskOption.flag = true;
                    mask.showMask(this.maskOption);
                }
                LogUtil.debug("Stop record:" + success);
            },
            onPlayWord : function() {
                if(_speech.speecher.Player.isReady){
                    var dom    = this.dom;
                    var audios = this.audios;

                    this.curStatus = this.Status.playWording;
                    for(var i = 0; i < audios.length; i++){
                        this.setWordPanelColor(i, 'gray');
                    }

                    dom.find('.word_playWord').hide();
                    dom.find('.word_stopWord').show();
                    this.disableAllFunBtn();
                    this.enableSingleFunBtn('.word_stopWord');
                    this.setWordPanelColor(this.wordIndex, this.setColor(0));

                    _speech.speecher.Player.loadAudio(encodeURI(audios[0]));
                    _speech.speecher.Player.play();
                }

            },
            onStopWord : function() {
                this.curStatus = this.Status.normal;
                _speech.speecher.Player.stop();
            },
            onPlayRead : function() {
                var dom    = this.dom;
                var audios = this.audios;

                this.curStatus = this.Status.playReading;
                for(var i = 0; i < audios.length; i++){
                    this.setWordPanelColor(i, 'gray');
                }
                dom.find('.word_playRead').hide();
                dom.find('.word_stopRead').show();
                this.disableAllFunBtn();
                this.enableSingleFunBtn('.word_stopRead');
                _speech.speecher.Recorder.loadAudio(this.records[0].id, false);
            },
            onStopRead : function() {
                this.curStatus = this.Status.normal;
                _speech.speecher.Recorder.stopPlay();
            },
            onPlayCom : function() {
                this.wordIndex = 0;
                this.openPop();
                this.disableAllFunBtn();
                this.enableAllFunBtn();
                this.setPopWordScore();
                this.clickEvent.onPlayCom.call(this);
                this.popStatus = this.Status.playComing;
            },
            onPopWordPanel : function(id){
                this.wordIndex = id;
                this.openPop();
                this.disableAllFunBtn();
                this.setPopStyle();
                this.setPopWordScore();
                this.popStatus = this.Status.pop;
            },
            onShowPY:function(){
                var chk = this.dom.find('.change_yb > input');
                if(chk.attr("checked") == "checked"){
                    this.setWordScore();
                }else{
                    for(var i=0; i<this.pyArray.length; i++){
                        var dom = this.dom;
                        dom.find('.word_eval_' + i).text("");
                        dom.find('.cn_eva_' + i).css("padding", "0px 4px 50px 0px");
                        dom.find('.word_eval_' + i + ' > span').css({width:'45px'});
                        dom.find('.word_text_' + i + ' > span').css({width:'45px'});
                    }
                }
            }
        }
    };

    /**
     * SpeechJS回调事件
     * @param {EnWordEvalCard} self
     * @protected
     */
    CnWordEvalCard.prototype.registerCallBack = function (self) {
        _speech.registerEvent({
            recordEvents: {
                onReady : function () {
                    window.readyInfo.recorder = true;
                    if( window.readyInfo.recorder == true &&  window.readyInfo.player == true){
                        self.maskOption.flag = false;
                        mask.showMask(self.maskOption);
                    }
                },
                onEvalResult : function (e) {
                    self.dom.find('.word_mic').css("width", 0);

                    if(e.resultType == EvalCallbackType.ENDPOINT){
                        self.clickEvent.onStopRec.call(self);
                    }else if(e.resultType === EvalCallbackType.SCORE){
                        for (var i = 0; i < e.result.Sentences.length; i++) {
                            var wordResult = e.result.Sentences[i].Words[0];
                            var info = {};
                            var err  = [] ;
                            info.py = pyUtil.PinYinUtil.getSYmu(wordResult.Symbol);
                            for(var j = 0; j < wordResult.Sylls.length; j++){
                                err[j] = wordResult.Sylls[j].ErrorCode;
                            }
                            info.error = err;
                            self.scoreArray[i] = info;

                            var recordInfo = {};
                            recordInfo.begin = wordResult.BegPos;
                            recordInfo.end   = wordResult.EndPos;
                            recordInfo.id    = self.recordID;
                            recordInfo.flag  = false;
                            recordInfo.time  = new Date().getTime();
                            self.records[i]  = recordInfo;
                        }

                        self.initStatus = false;
                        self.curStatus = self.Status.normal;
                        self.disableAllFunBtn();
                        self.enableAllFunBtn();
                        self.dom.find('.word_stopRec').hide();
                        self.dom.find('.word_startRec').show();

                        self.maskOption.flag = false;
                        mask.showMask(self.maskOption);
                        self.setWordScore();
                        self.dom.find('.change_yb > input').attr("checked","true");
                    }
                },
                onRecording : function (e) {
                    var volume = e.energy;
                    if(volume < 50){
                        volume += 20;
                    }else if(volume>=50 && volume<60){
                        volume = 70;
                    }else if(volume>=60 && volume<80){
                        volume = 80;
                    }
                    self.dom.find('.word_mic_sgray').css("width", volume);
                },
                onAudioLoaded : function(){
                    var color = self.setColor(self.wordIndex);
                    self.setWordPanelColor(self.wordIndex, color);
                    _speech.speecher.Recorder.playRange(self.records[self.wordIndex].begin, self.records[self.wordIndex].end);
                    if(self.wordIndex == self.audios.length - 1){
                        self.wordIndex++;
                    }
                },
                onPlayStop : function(){
                    if(self.curStatus == self.Status.playReading && self.wordIndex < self.audios.length){
                        setTimeout(function() {
                            self.setWordPanelColor(self.wordIndex, 'gray');
                            self.wordIndex++;
                            _speech.speecher.Recorder.loadAudio(self.records[self.wordIndex].id, false);
                        }, 500);
                    }else{
                        self.wordIndex == self.audios.length ? self.wordIndex-- : "" ;
                        self.setWordPanelColor(self.wordIndex, 'gray');

                        self.wordIndex = 0;
                        self.disableAllFunBtn();
                        self.enableAllFunBtn();
                        self.dom.find('.word_stopRead').hide();
                        self.dom.find('.word_playRead').show();
                        self.curStatus = self.Status.normal;
                    }
                },
                onError : function(e){

                    if(self.curStatus == self.Status.recording || self.curStatus == self.Status.playReading){

                        if( e.errorType == 3 || (e.errorType == 2 && e.errorCode == 10118) ){
                            self.maskOption.msg = "没有检测到声音";
                        }else if( (e.errorType == 2 && e.errorCode == 11004) || (e.errorType == 1 && e.errorCode == 4002) ){
                            self.maskOption.msg = "登陆云平台失败";
                        }else if( e.errorType == 2 && (e.errorCode == 10115 || e.errorCode == 10116) ){
                            var time = new Date().getTime();
                            if( time - self.records[self.wordIndex].time < 5000 ){
                                self.maskOption.msg = "正在上传语音文件";
                            }else{
                                self.maskOption.msg = "音频加载出错";
                            }
                        }else if(e.errorType==2 && e.errorCode==20006){
                            self.maskOption.msg = "正在录制视频或录音设备被占用，不能录音";
                        }else{
                            console.log(JSON.stringify(e));
                            self.maskOption.msg = "网络连接出错";
                        }

                        self.maskOption.type = self.maskType.common;
                        self.maskOption.flag = true;
                        mask.showMask(self.maskOption);
                        setTimeout(function() {
                            self.showAllFunBtn();
                            self.disableAllFunBtn();
                            if(self.initStatus) {
                                self.enableSingleFunBtn('.word_startRec');
                                self.enableSingleFunBtn('.word_playWord');
                                self.enableSingleFunBtn('.word_panel_index');
                            }else{
                                self.enableAllFunBtn();
                            }
                            self.maskOption.flag = false;
                            mask.showMask(self.maskOption);
                            self.wordIndex = 0;
                            self.curStatus = self.Status.normal;
                        }, 2500);
                    }
                }
            },
            playEvents:{
                onReady : function(){
                    window.readyInfo.player = true;
                    if( window.readyInfo.recorder == true &&  window.readyInfo.player == true){
                        self.maskOption.flag = false;
                        mask.showMask(self.maskOption);
                    }
                },
                onStop : function(){
                    if(self.curStatus == self.Status.playWording &&
                        self.wordIndex < self.audios.length &&
                        self.wordIndex != self.audios.length - 1
                       ){
                            setTimeout(function(){
                                self.setWordPanelColor(self.wordIndex, 'gray');
                                self.wordIndex++;

                                var color = self.setColor(self.wordIndex);
                                self.setWordPanelColor(self.wordIndex, color );

                                _speech.speecher.Player.loadAudio(encodeURI(self.audios[self.wordIndex]));
                                _speech.speecher.Player.play();
                                if(self.wordIndex == self.audios.length-1){
                                    self.wordIndex++;
                                }
                            }, 800);
                        } else{
                            if(self.wordIndex == self.audios.length){
                                self.wordIndex--;
                            }
                            self.setWordPanelColor(self.wordIndex, 'gray');
                            self.disableAllFunBtn();
                            self.wordIndex = 0;
                            if(self.initStatus) {
                                self.enableSingleFunBtn('.word_startRec');
                                self.enableSingleFunBtn('.word_playWord');
                                self.enableSingleFunBtn('.word_panel_index');
                            }else{
                                self.enableAllFunBtn();
                            }
                            self.dom.find('.word_stopWord').hide();
                            self.dom.find('.word_playWord').show();
                            self.curStatus = self.Status.normal;
                        }
                }
            }
        });
    };

    /**
     * 弹出层点击事件
     * @protected
     */
    CnWordEvalCard.prototype.registerPopClickEvent = function () {
        this.clickEvent = {
            onStartRec : function(){
                var dom = this.dom;
                this.recordID = "word-card-" + new Date().getTime();
                var success = _speech.speecher.Recorder.record({
                    evalType: SeEvalType.ReadWordCn,
                    evalText: this.wordPaper[this.wordIndex + 1],
                    evalParams: "vadEnable=true, vadSpeechTail=2500",
                    sndId: this.recordID
                });
                LogUtil.debug("Begin record:" + success);
                if(success){
                    this.popStatus = this.Status.recording;
                    this.disableAllFunBtn();
                    dom.find('.pop_word_startRec').hide();
                    dom.find('.pop_word_stopRec').show();
                    this.enableSingleFunBtn('.pop_word_stopRec');
                }
            },
            onStopRec : function() {
                var success = _speech.speecher.Recorder.stop();
                if(success){
                    this.maskOption.type = this.maskType.top;
                    this.maskOption.msg = "正在评测中，请稍候";
                    this.maskOption.flag = true;
                    mask.showMask(this.maskOption);
                    this.disableSingleFunBtn('.pop_word_stopRec');
                }
                LogUtil.debug("Stop record:" + success);
            },
            onPlayWord : function(){
                this.dom.find('.pop_word_playWord').hide();
                this.dom.find('.pop_word_stopWord').show();
                this.disableAllFunBtn();
                this.enableSingleFunBtn('.pop_word_stopWord');
                this.enableSingleFunBtn('.pop_pre');
                this.enableSingleFunBtn('.pop_next');

                this.popStatus    = this.Status.playWording;
                this.prePopStatus = this.Status.playWording;

                _speech.speecher.Player.loadAudio(encodeURI(this.audios[this.wordIndex]));
                _speech.speecher.Player.play();

            },
            onStopWord : function() {
                this.popStatus = this.Status.pop;
                _speech.speecher.Player.stop();
            },
            onPlayRead : function() {
                this.dom.find('.pop_word_playRead').hide();
                this.dom.find('.pop_word_stopRead').show();
                this.disableAllFunBtn();
                this.enableSingleFunBtn('.pop_word_stopRead');
                this.enableSingleFunBtn('.pop_pre');
                this.enableSingleFunBtn('.pop_next');

                this.popStatus    = this.Status.playReading;
                this.prePopStatus = this.Status.playReading;

                _speech.speecher.Recorder.loadAudio(this.records[this.wordIndex].id, false);
            },
            onStopRead : function() {
                this.popStatus = this.Status.pop;
                _speech.speecher.Recorder.stopPlay();
            },

            onPlayCom : function() {
                this.dom.find('.pop_word_playCom').hide();
                this.dom.find('.pop_word_stopCom').show();
                this.disableAllFunBtn();
                this.enableSingleFunBtn('.pop_word_stopCom');
                this.enableSingleFunBtn('.pop_pre');
                this.enableSingleFunBtn('.pop_next');

                this.popStatus    = this.Status.playComing;
                this.prePopStatus = this.Status.playComing;

                _speech.speecher.Player.loadAudio(encodeURI(this.audios[this.wordIndex]));
                _speech.speecher.Player.play();
            },
            onStopCom : function() {
                this.popStatus = this.Status.pop;
                this.forceStop = true;
                _speech.speecher.Player.stop();
                _speech.speecher.Recorder.stopPlay();
            },
            onPopNextBtn: function(){
                if(this.wordIndex < this.audios.length - 1){
                    this.wordIndex++;
                }
                this.setPopWordScore();
                _speech.speecher.Player.stop();
                _speech.speecher.Recorder.stopPlay();
                if(this.popStatus == this.Status.pop){
                    this.disableAllFunBtn();
                    this.setPopStyle();
                }else{
                    this.setPreNext();
                }
            },
            onPopPreBtn: function(){
                this.wordIndex--;
                this.setPopWordScore();
                _speech.speecher.Player.stop();
                _speech.speecher.Recorder.stopPlay();
                if(this.popStatus == this.Status.pop){
                    this.disableAllFunBtn();
                    this.setPopStyle();
                }else{
                    this.setPreNext();
                }
            }
        }
    };

    /**
     * 弹出层SpeechJS回调事件
     * @param {EnWordEvalCard} self
     * @protected
     */
    CnWordEvalCard.prototype.registerPopCallBack = function (self) {
        self.dom.find('.chk').removeAttr('checked');
        _speech.registerEvent({
            recordEvents: {
                onReady : function () {
                },
                onEvalResult : function (e) {
                    self.dom.find('.pop_word_mic').css("width", 0);

                    if(e.resultType == EvalCallbackType.ENDPOINT){
                        self.clickEvent.onStopRec.call(self);
                    }else if(e.resultType === EvalCallbackType.SCORE){
                        var wordResult = e.result.Sentences[0].Words[0];
                        var info = {};
                        var err = [] ;
                        info.py = pyUtil.PinYinUtil.getSYmu(wordResult.Symbol);
                        for(var j = 0; j < wordResult.Sylls.length; j++){
                            err[j] = wordResult.Sylls[j].ErrorCode;
                        }
                        info.error = err;
                        self.scoreArray[self.wordIndex] = info;

                        var recordInfo = {};
                        recordInfo.begin = wordResult.BegPos;
                        recordInfo.end   = wordResult.EndPos;
                        recordInfo.id    = self.recordID;
                        recordInfo.flag  = false;
                        recordInfo.time  = new Date().getTime();
                        self.records[self.wordIndex] = recordInfo;

                        for(var i = 0; i < self.records.length; i++ ){
                            if(self.records[i].id == ''){
                                self.records[i].id = self.recordID;
                            }
                        }
                        self.maskOption.type = self.maskType.top;
                        self.maskOption.flag = false;
                        mask.showMask(self.maskOption);
                        self.maskOption.type = self.maskType.card;

                        self.setPopWordScore();
                        self.disableAllFunBtn();
                        self.enableAllFunBtn();
                        self.dom.find('.pop_word_stopRec').hide();
                        self.dom.find('.pop_word_startRec').show();

                        self.popStatus = self.Status.pop;
                    }
                },
                onError : function(e){
                    if(self.popStatus == self.Status.recording   ||
                        self.popStatus == self.Status.playReading ||
                        self.popStatus == self.Status.playComing  ||
                        self.prePopStatus == self.Status.playComing){

                        if( e.errorType == 3 || (e.errorType == 2 && e.errorCode == 10118) ){
                            self.maskOption.msg = "没有检测到声音";
                        }else if( (e.errorType == 2 && e.errorCode == 11004) || (e.errorType == 1 && e.errorCode == 4002) ){
                            self.maskOption.msg = "登陆云平台失败";
                        }else if( e.errorType == 2 && (e.errorCode == 10115 || e.errorCode == 10116) ){
                            var time = new Date().getTime();
                            if( time - self.records[self.wordIndex].time < 5000 ){
                                self.maskOption.msg = "正在上传语音文件";
                            }else{
                                self.maskOption.msg = "音频加载出错";
                            }
                        }else if(e.errorType==2 && e.errorCode==20006){
                            self.maskOption.msg = "正在录制视频或录音设备被占用，不能录音";
                        }else{
                            self.maskOption.msg = "网络连接出错";
                        }
                        self.maskOption.type = self.maskType.top;
                        self.maskOption.flag = true;
                        mask.showMask(self.maskOption);
                        setTimeout(function() {
                            self.maskOption.flag = false;
                            mask.showMask(self.maskOption);
                            self.maskOption.type = self.maskType.card;
                            self.disableAllFunBtn();
                            self.showAllFunBtn();
                            self.setPopStyle();
                            self.popStatus = self.Status.pop;
                        }, 2500);
                    }
                },
                onRecording : function (e) {
                    var volume = e.energy;
                    if(volume < 50){
                        volume += 20;
                    }else if(volume>=50 && volume<60){
                        volume = 70;
                    }else if(volume>=60 && volume<80){
                        volume = 80;
                    }
                    self.dom.find('.pop_word_mic').css("width", volume);
                },
                onAudioLoaded : function(){
                    _speech.speecher.Recorder.playRange(self.records[self.wordIndex].begin, self.records[self.wordIndex].end);
                },
                onPlayStop : function(){
                    if( self.dom.find('.chk').attr('checked') ){
                        do{
                            self.wordIndex++;
                        }while( self.wordIndex < self.audios.length && self.records[self.wordIndex].flag );

                        if(self.wordIndex >= self.audios.length){
                            self.wordIndex = self.audios.length - 1;
                            self.popStatus = self.Status.pop;
                        }else{
                            if( self.popStatus == self.Status.playReading ){
                                setTimeout(function() {
                                    _speech.speecher.Recorder.loadAudio(self.records[self.wordIndex].id);
                                    self.setPopWordScore();
                                    self.setPreNext();
                                }, 500);
                            }
                            if( self.popStatus == self.Status.playComing ){
                                setTimeout(function() {
                                    _speech.speecher.Player.loadAudio(encodeURI(self.audios[self.wordIndex]));
                                    _speech.speecher.Player.play();
                                    self.setPopWordScore();
                                    self.setPreNext();
                                }, 200);
                            }
                        }
                    }
                    if(self.dom.find('.chk').attr('checked') == undefined || self.popStatus == self.Status.pop){
                        self.popStatus = self.Status.pop;
                        if(self.prePopStatus == self.Status.playReading){
                            self.dom.find('.pop_word_playRead').show();
                            self.dom.find('.pop_word_stopRead').hide();
                        }
                        if(self.prePopStatus == self.Status.playComing){
                            self.dom.find('.pop_word_playCom').show();
                            self.dom.find('.pop_word_stopCom').hide();
                        }
                        self.disableAllFunBtn();
                        self.setPopStyle();
                        self.setPopWordScore();
                    }
                    self.forceStop = false;
                }
            },
            playEvents:{
                onStop : function(){
                    if(self.dom.find('.chk').attr('checked') && self.popStatus == self.Status.playWording){
                        self.wordIndex++;
                        if(self.wordIndex >= self.audios.length){
                            self.wordIndex = self.audios.length - 1;
                            self.popStatus = self.Status.pop;
                        }else{
                            setTimeout(function(){
                                _speech.speecher.Player.loadAudio(encodeURI(self.audios[self.wordIndex]));
                                _speech.speecher.Player.play();
                                self.setPopWordScore();
                                self.setPreNext();
                            }, 500);
                        }
                    }
                    if(self.dom.find('.chk').attr('checked') && self.popStatus == self.Status.playComing){
                        _speech.speecher.Recorder.loadAudio(self.records[self.wordIndex].id, false);
                    }
                    if(self.dom.find('.chk').attr('checked') == undefined || self.popStatus == self.Status.pop){
                        if(self.prePopStatus == self.Status.playWording){
                            self.popStatus = self.Status.pop;
                            self.dom.find('.pop_word_playWord').show();
                            self.dom.find('.pop_word_stopWord').hide();
                            self.disableAllFunBtn();
                            self.setPopStyle();
                        }
                        if(self.prePopStatus == self.Status.playComing){
                            if(!self.forceStop){
                                _speech.speecher.Recorder.loadAudio(self.records[self.wordIndex].id, false);
                            }else{
                                self.dom.find('.pop_word_playCom').show();
                                self.dom.find('.pop_word_stopCom').hide();
                                self.disableAllFunBtn();
                                self.setPopStyle();
                            }
                        }
                    }
                    self.forceStop = false;
                }
            }
        });
    };

    /**
     * 中文评测结果
     */
    CnWordEvalCard.prototype.setWordScore = function () {
        for(var i = 0; i < this.scoreArray.length; i++){
            var html = '';
            var py   = this.scoreArray[i].py;
            var err  = this.scoreArray[i].error;
            var word = this.panelWord[i+1];

            var maxPyLength = 0;
            var tmpPyLength = 0;

            if(py != ''){
                if(word.length <= 15){
                    this.dom.find('.cn_eva_' + i).css("padding", "20px 4px 12px 0px");
                    this.dom.find('.chinese').css("padding","10px 4px");
                }else{
                    this.dom.find('.cn_eva_' + i).css("padding", "10px 4px 12px 0px");
                    this.dom.find('.chinese').css("padding","0px 4px");
                }
            }

            for(var j = 0; j < py.length; j++){
                if( j % 2 == 0 ){
                    html += "<span class='cn_eval'>";
                }
                html += "<span class='py_" + j + "'>" + py[j] + "</span>";
                tmpPyLength += py[j].length;
                if( j % 2 != 0 ){
                    html += "</span>";
                    maxPyLength = (tmpPyLength > maxPyLength ? tmpPyLength : maxPyLength);
                    tmpPyLength = 0;
                }
            }
            var dom = this.dom;
            var setWidth = 45;
            maxPyLength == 5 ? setWidth = 55 :
                maxPyLength == 6 ? setWidth = 60 : '';

            dom.find('.word_eval_' + i).text("").html(html);
            dom.find('.word_eval_' + i + ' > span').css({width:setWidth});
            dom.find('.word_text_' + i + ' > span').css({width:setWidth});
            this.setPY( '.word_eval_' + i, word, py, err);
        }
    };

    /**
     * 弹出层评测结果
     */
    CnWordEvalCard.prototype.setPopWordScore = function(){
        var html = '';
        var pyNum = 0;
        var py   = this.scoreArray[this.wordIndex].py;
        var err  = this.scoreArray[this.wordIndex].error;
        var word = this.panelWord[this.wordIndex+1];

        var pyTotal = 0;

        for(var i = 0; i < py.length; i++){
            html += (i % 2 == 0 ? '&nbsp;&nbsp;' : '');
            html += "<span class='py_" + i + "'>" + py[i] + "</span>";
            pyNum += py[i].length;
            if( (i+1) % 8 == 0)
            {
                html+="<br/>";
                if( pyNum > pyTotal )
                {
                    pyTotal = pyNum;
                }
                pyNum = 0;
            }
        }
        var size = pyTotal < 13 ? 30 :
                    pyTotal >41? 15 : 41 - pyTotal;
        this.dom.find('.term_word_txt').text('').text( this.wordArray[this.wordIndex+1] );
        this.dom.find('.term_py_txt').text('').html(html).css("font-size", size);
        this.dom.find('.term_result').text('').css({height:'0'});
        this.setPY( '.term_py_txt', word, py, err);
    };

    /**
     * 评测结果拼音处理
     * @param {String} select
     * @param {Array} word
     * @param {Array} py
     * @param {Array} error
     */
    CnWordEvalCard.prototype.setPY = function(select, word, py, error){
        var elem   = select + ' .py_';
        var result = '';
        var flag;
        var wordNum = 0;

        for(var i = 0; i < word.length; i ++ ){
            if( (error[i] & ErrorCode.ErrorConsonant) != 0
                || (error[i] & ErrorCode.ErrorTone) != 0
                || (error[i] & ErrorCode.ErrorVowel) != 0 ){
                flag = true;
                wordNum++;
            }
            result += ( flag == true ? word[i] : "");

            var index = (py[2*i] == ' ' ? 2*i+1 : 2*i);
            if( (error[i] & ErrorCode.ErrorVowel) != 0){
                this.setPyStyle(elem + index, 'red');
                result += "&nbsp(声母)";
            }else{
                this.setPyStyle(elem + index, 'gray');
            }

            if( (error[i] & ErrorCode.ErrorConsonant) != 0  && (error[i] & ErrorCode.ErrorTone) != 0  ){
                this.setPyStyle(elem + (2*i+1), 'red_underline');
                result += "&nbsp(韵母)&nbsp(声调)";
            }else{
                if( (error[i] & ErrorCode.ErrorConsonant) != 0){
                    this.setPyStyle(elem + (2*i+1), 'red');
                    result += "&nbsp(韵母)";
                }else if( (error[i] & ErrorCode.ErrorTone) != 0){
                    this.setPyStyle(elem + (2*i+1), 'underline');
                    result += "&nbsp(声调)";
                }else{
                    if( py[2*i] != ' ' || (error[i] & ErrorCode.ErrorVowel) == 0){
                        this.setPyStyle(elem + (2*i+1), 'gray');
                    }
                }
            }
            result += ( flag == true ? "出错<br>" : "");
            flag = false;
        }

        this.dom.find('.term_result').text('').html(result).css({height: 18*wordNum});
        var left  =  this.dom.find('.term_left');
        var right =  this.dom.find('.term_right');

        if(right.height() > 126){
            left.css({
                height : right.height()
            })
        }else{
            left.css({
                height : '126px'
            })
        }
    };

    /**
     * 评测结果拼音样式
     * @param {String} select
     * @param {String} style
     */
    CnWordEvalCard.prototype.setPyStyle = function(select, style){
        if(style == 'gray'){
            this.dom.find(select).removeClass('red').removeClass('underline').addClass('dimgray');
        }
        if(style == 'red'){
            this.dom.find(select).removeClass('dimgray').removeClass('underline').addClass('red');
        }
        if(style == 'underline'){
            this.dom.find(select).removeClass('dimgray').removeClass('red').addClass('underline');
        }
        if(style == 'red_underline'){
            this.dom.find(select).removeClass('dimgray').addClass('red').addClass('underline');
        }
    };

    /**
     * 设置单词背景颜色
     * @param {Number} index
     * @param {String} color
     */
    CnWordEvalCard.prototype.setWordPanelColor = function(index, color){
        switch(color){
            case 'green':
                this.dom.find('.word_panel_' + index).removeClass('graycard').removeClass('redcard').addClass('gncard');
                this.dom.find('.word_line_' + index).removeClass('grayline').removeClass('redline').addClass('gnline');
                break;
            case 'red':
                this.dom.find('.word_panel_' + index).removeClass('graycard').removeClass('gncard').addClass('redcard');
                this.dom.find('.word_line_' + index).removeClass('grayline').removeClass('gnline').addClass('redline');
                break;
            case 'gray':
                this.dom.find('.word_panel_' + index).removeClass('greencard').removeClass('redcard').addClass('graycard');
                this.dom.find('.word_line_' + index).removeClass('redline').removeClass('gnline').addClass('grayline');
                break;
        }
    };

    /**
     * 评测结果颜色设置
     * @param {Number} index
     */
    CnWordEvalCard.prototype.setColor = function(index){
        var color = 'green';
        if(this.scoreArray[index] != ''){
            var err = this.scoreArray[index].error;
            for(var i = 0; i < err.length; i++){
                if(err[i] != 0){
                    color = 'red';
                }
            }
        }
        return color;
    };

    /**
     * @export {speechui.cards.CnWordEvalCard.Constructor}
     */
    exports.Constructor = CnWordEvalCard;
});