/**
 *  IFLYTEK Education Division Architecture Team
 *
 *  @author:        shenghe <shenghe@iflytek.com>
 *  @license:       (C) 2013, iFlyTEK CO.Ltd. All rights reserved.
IFLYTEK Education Division Architecture Team
 *  @version:       $Id$
 *  @module         speechui/cards
 *  @description    情景对话模块
 */

define(function (require, exports, module) {
    require('../../view/css/dialogue.css');

    var $ = require('jquery');
    var cardbase = require('./cardbase');
    var define = require('../define');
    var speech = require('../common/speech');
    var tplparse = require('../thirdparty/template');
    var mask = require('../common/mask');

    var RoleEnum = {
        'A' : 'A',                    //角色A
        'B' : 'B'                     //角色B
    };

    var ModeEnum = {
        'MANTOMACHINE' : 0,         //人机对答模式
        'MANTOMAN' : 1              //人人对答模式
    };

    var StatusEnum = {
        'DEFAULT': 0,            //默认状态
        'RECORDING': 1,          //正在录音
        'READING': 2,            //正在播放标准音
        'PLAYBACKING': 3,         //正在回放录音
        'CONSTRAST': 4          //对比朗读
    };

    /**
     * create a new recordid, will used by play
     * @return {[string]} [recordid]
     */
    function getRecordID() {
        var id = 'dialogue-';
        d = new Date();
        id += d.getHours();
        id += d.getMinutes();
        id += d.getSeconds();
        id += d.getMilliseconds();
        id += Math.ceil(Math.random() * 1000);
        return(id);
    }

    function isEmptyObject(obj) {
        for(var n in obj)
        {
            return false;
        }
        return true;
    }

    function SettingsDialog(self) {
        this.dialogue = self;
        this.mode = this.dialogue.mode;
        this.role = this.dialogue.role;
        this.registerCallback();
        this.registerDomEvents();
    }

    SettingsDialog.prototype.registerCallback = function() {
        this.callback = {
            'onClose': function(e) {
                var self = e.data.self;
                self.mode = self.dialogue.mode;
                self.role = self.dialogue.role;
                $('#dialogue-bg').hide();
                $('#dialogue-settings-dialog').hide();
            },

            'onSubmit': function(e) {
                var self = e.data.self;
                self.dialogue.mode = self.mode;
                self.dialogue.role = self.role;

                $('#dialogue-read').removeClass('gray');
                $('#dialogue-record').removeClass('gray');
                $('#dialogue-settings').removeClass('gray');
                $('#dialogue-playback').addClass('gray');

                self.dialogue.records = {};
                self.dialogue.status = StatusEnum.DEFAULT;
                self.dialogue.curLine = -1;
                self.dialogue.isreset = false;

                for (var i in self.dialogue.option.sens) {
                    self.dialogue.option.sens[i].score = 0;
                    self.dialogue.option.sens[i].cssClass = 'red';
                    self.dialogue.option.sens[i].recordid = '';
                }
                $('.dialogue-score').hide();
                $('#dialogue-bg').hide();
                $('#dialogue-settings-dialog').hide();
                $('#dialogue-face').removeClass('face-bad').addClass('face-good');
                $('#dialogue-totalscore').hide();
            },

            'onClickOption': function(e) {
                var self = e.data.self;
                var id = e.data.id;
                if (id === 'man2machine') {
                    $('.dialogue-rolea').css('background-image','url(./js-debug/speechui/view/images/jsA.png)');
                    $('.dialogue-roleb').css('background-image','url(./js-debug/speechui/view/images/jsB.png)');
                    $('.dialogue-rolea + div').removeClass('gray');
                    $('.dialogue-roleb + div').removeClass('gray');

                    self.mode = ModeEnum.MANTOMACHINE;
                    $('#man2man').attr('class', 'options_normal').children('.options_right').remove();
                    $('#man2machine').attr('class', 'options_current').prepend('<div class="options_right"></div>');
                    if (self.role === RoleEnum.A) {
                        $('#rolea').attr('class', 'options_current').prepend('<div class="options_right"></div>');
                        $('#roleb').removeClass('gray');
                    } else {
                        $('#roleb').attr('class', 'options_current').prepend('<div class="options_right"></div>');
                        $('#rolea').removeClass('gray');
                    }
                } else if (id === 'man2man') {
                    self.mode = ModeEnum.MANTOMAN;
                    $('#man2machine').attr('class', 'options_normal').children('.options_right').remove();
                    $('#man2man').attr('class', 'options_current').prepend('<div class="options_right"></div>');
                    $('#roleb').attr('class', 'options_normal gray').children('.options_right').remove();
                    $('#rolea').attr('class', 'options_normal gray').children('.options_right').remove();

                    $('.dialogue-rolea').css('background-image','url(./js-debug/speechui/view/images/jsA_dis.png)');
                    $('.dialogue-roleb').css('background-image','url(./js-debug/speechui/view/images/jsB_dis.png)');
                    $('.dialogue-rolea + div').addClass('gray');
                    $('.dialogue-roleb + div').addClass('gray');
                } else if (id === 'rolea') {
                    if (self.mode === ModeEnum.MANTOMAN) return;
                    self.role = RoleEnum.A;
                    $('#roleb').attr('class', 'options_normal').children('.options_right').remove();
                    $('#rolea').attr('class', 'options_current').prepend('<div class="options_right"></div>');
                } else if (id === 'roleb') {
                    if (self.mode === ModeEnum.MANTOMAN) return;
                    self.role = RoleEnum.B;
                    $('#rolea').attr('class', 'options_normal').children('.options_right').remove();
                    $('#roleb').attr('class', 'options_current').prepend('<div class="options_right"></div>');
                }
            }
        };
    };

    SettingsDialog.prototype.registerDomEvents = function() {
        $('#btn_close_settings').bind('click', {self : this}, this.callback.onClose);
        $('#btn_submit').bind('click', {'self': this}, this.callback.onSubmit);
        $('#man2machine').bind('click', {'self': this, 'id': 'man2machine'}, this.callback.onClickOption);
        $('#man2man').bind('click', {'self': this, 'id': 'man2man'}, this.callback.onClickOption);
        $('#rolea').bind('click', {'self': this, 'id': 'rolea'}, this.callback.onClickOption);
        $('#roleb').bind('click', {'self': this, 'id': 'roleb'}, this.callback.onClickOption);
    };

    SettingsDialog.prototype.open = function() {
        $('#dialogue-bg').show();
        $('#dialogue-settings-dialog').show();

        $('#man2man').attr('class', 'options_normal').children('.options_right').remove();
        $('#man2machine').attr('class', 'options_normal').children('.options_right').remove();
        $('#roleb').attr('class', 'options_normal').children('.options_right').remove();
        $('#rolea').attr('class', 'options_normal').children('.options_right').remove();

        var info = {};
        info.data = {};

        var self = {
            mode : this.dialogue.mode,
            role : this.dialogue.role
        }
        var id = ( this.dialogue.mode ==  ModeEnum.MANTOMACHINE ? 'man2machine' :  'man2man');
        info.data.self = self;
        info.data.id = id;
        this.callback.onClickOption(info);
    };

    function ScoreDetailsDialog(dialogue) {
        this.dialogue = dialogue;

        /**
         * the dialog's first line to be showed.-1 means that can't be showed
         * @type {Number}
         */
        this.startline = -1;
        if (dialogue.option.sens.length > 0) {
            this.startline = 0;
        }

        this.curLine = -1;
        this.isreset = false;
        this.persistent = false;
        this.status = StatusEnum.DEFAULT;

        this.score = {
            info : []
        };

        this.registerCallback();
        this.registerDomEvents();
    }

    ScoreDetailsDialog.prototype.open = function(line) {
        this.startline = line || 0;
        if (1 === line % 2) {
            this.startline = line - 1;
        }
        $('#dialogue-scoreinfo-dialog').show();
        $('#dialogue-bg').show();
        this.render();
        this.registerSpeechEvents();
    };

    ScoreDetailsDialog.prototype.close = function(e) {
        var self = e.data.self;
        $('#dialogue-scoreinfo-dialog').hide();
        $('#dialogue-bg').hide();

        var info = self.score.info;
        for(var obj in info){
            var score = info[obj].score;
            var line = info[obj].line;
            var tipclass = score < 60 ? 'red dialogue-score' : 'green dialogue-score';
            $('#dialogue-line' + line + '-score').show().attr('class', tipclass).text(score +'分');
        }

        var totalScore = 0;
        var finalNum = 0;
        var dialogueInfo = self.dialogue;
        var sens = dialogueInfo.option.sens;
        if(dialogueInfo.mode == ModeEnum.MANTOMAN){
            for(var i = 0; i<sens.length; i++){
                if(sens[i].recordid != ''){
                    totalScore += sens[i].score;
                    finalNum++;
                }
            }
        }else{
            for(var i = 0; i<sens.length; i++){
                if(sens[i].role == dialogueInfo.role && sens[i].recordid != ''){
                    totalScore += sens[i].score;
                    finalNum++;
                }
            }
        }
        var finalScore = parseInt(totalScore / finalNum, 10);
        var finalclass = finalScore < 60 ? 'left total-score-red' : 'left total-score-green';
        if (finalScore < 60) {
            $('#dialogue-face').removeClass('face-good').addClass('face-bad');
        } else {
            $('#dialogue-face').removeClass('face-bad').addClass('face-good');
        }
        $('#dialogue-totalscore').show().attr('class', finalclass).text(finalScore +' 分');
        self.dialogue.registerSpeechEvents();
    };

    ScoreDetailsDialog.prototype.render = function() {
        var sens = this.dialogue.option.sens;
        var line = this.startline;
        var nline = line + 1;
        var text = '';

        if (line > -1) {
            if(line < sens.length){
                text += '<dd id="dialogue-dialog-line0"><span>'+ sens[line].role +':</span> <span>'+ sens[line].text +'</span>';
                if (sens[line].role === this.dialogue.role || this.dialogue.mode == 1) {
                    text += '<span class="'+ sens[line].cssClass +'">'+ sens[line].score +'分</span></dd>';
                }
            }

            if (sens.length > line && nline < sens.length) {
                text += '<dd id="dialogue-dialog-line1"><span>'+ sens[nline].role +':</span> <span>'+ sens[nline].text +'</span>';
                if (sens[nline].role === this.dialogue.role || this.dialogue.mode == 1) {
                    text += '<span class="'+ sens[nline].cssClass +'">'+ sens[nline].score +'分</span></dd>';
                }
            }

            text += '<dd><div class="clear"></div></dd>';
        }
        $('#dialogue-dialog-score').empty().append(text);

        if (line === 0) {
//            $('.page_prev').addClass('gray');
            $('.page_prev').css('background-image','url(./js-debug/speechui/view/images/arrow_cs2_dis.png)');
        } else {
//            $('.page_prev').removeClass('gray');
            $('.page_prev').css('background-image','url(./js-debug/speechui/view/images/arrow_cs2.png)');
        }

        if (line === sens.length - 1 || line === sens.length - 2) {
//            $('.page_next').addClass('gray');
            $('.page_next').css('background-image','url(./js-debug/speechui/view/images/arrow_cs_dis.png)');
        } else {
//            $('.page_next').removeClass('gray');
            $('.page_next').css('background-image','url(./js-debug/speechui/view/images/arrow_cs.png)');
        }

        if (this.persistent) {
            $('#dialogue-dialog-persistent').attr('checked', 'checked');
        } else {
            $('#dialogue-dialog-persistent').removeAttr('checked');
        }

        if (this.status === StatusEnum.DEFAULT)  {
            $('#dialogue-dialog-persistent').removeAttr('disabled');
        } else {
            $('#dialogue-dialog-persistent').attr('disabled', 'true');
        }
    };

    ScoreDetailsDialog.prototype.resetBtns = function() {
        $('#dialogue-dialog-record').removeClass('gray').attr('class', 'popbtn_normal');
        $('#dialogue-dialog-recordtext').text('重新对话');
        $('#dialogue-dialog-read').removeClass('gray').attr('class', 'popbtn_normal');
        $('#dialogue-dialog-readtext').text('示范朗读');
        $('#dialogue-dialog-playback').removeClass('gray').attr('class', 'popbtn_normal');
        $('#dialogue-dialog-playbacktext').text('对话回放');
        $('#dialogue-dialog-constrast').removeClass('gray').attr('class', 'popbtn_normal');
        $('#dialogue-dialog-constrasttext').text('对比朗读');
        $("#dialogue-dialog-voicebar").hide();
    };

    ScoreDetailsDialog.prototype.openPrevPage = function(e) {
        var self = e.data.self;
        if (self.startline > 1 && self.status === StatusEnum.DEFAULT) {
            self.startline -= 2;
            self.render();
        }
    };

    ScoreDetailsDialog.prototype.openNextPage = function(e) {
        var self = e.data.self;
        if (self.startline < self.dialogue.option.sens.length - 2 && self.status === StatusEnum.DEFAULT) {
            self.startline += 2;
            self.render();
        }
    };

    ScoreDetailsDialog.prototype.changePersistent = function(e) {
        var self = e.data.self;
        self.persistent = $('#dialogue-dialog-persistent').attr('checked') === 'checked' ? true : false;
    };

    ScoreDetailsDialog.prototype.registerCallback = function() {
        this.callback = {
            'onRecord': function() {
                var nline = this.curLine + 1;

                if (nline < this.dialogue.option.sens.length) {
                    this.dialogue.recordid = getRecordID();
                    speech.speecher.Recorder.record({
                        evalType : SeEvalType.ReadSentence,
                        evalText : this.dialogue.option.sens[nline].text,
                        evalParams : "autoTrack=true,trackType=easy,vadEnable=true,vadSpeechTail=1000",
                        sndId : this.dialogue.recordid
                    });
                }
            },

            'onClickRecord': function(e) {
                var self = e.data.self;
                if (self.status === StatusEnum.DEFAULT && self.startline > -1) {
                    var startrecord = false;
                    if (self.dialogue.mode === ModeEnum.MANTOMAN || self.dialogue.option.sens[self.startline].role === self.dialogue.role) {
                        self.curLine = self.startline - 1;
                        startrecord = true;
                    } else if (
                        self.startline < self.dialogue.option.sens.length - 1 &&
                        self.dialogue.option.sens[self.startline + 1].role === self.dialogue.role
                    ) {
                        self.curLine = self.startline;
                        startrecord = true;
                    }

                    if (startrecord) {
                        self.status = StatusEnum.RECORDING;
                        $('#dialogue-dialog-record').attr('class', 'popbtn_current');
                        $('#dialogue-dialog-recordtext').text('停止对话');
                        $('#dialogue-dialog-read').addClass('gray');
                        $('#dialogue-dialog-playback').addClass('gray');
                        $('#dialogue-dialog-constrast').addClass('gray');
                        $('#dialogue-dialog-persistent').attr('disabled', 'true');
                        self.callback.onRecord.call(self);
                    }
                } else if (self.status === StatusEnum.RECORDING) {
                    self.isreset = true;
                    speech.speecher.Recorder.stop();
                    speech.speecher.Player.stop();
                }
            },

            'onClickRead': function(e) {
                var self = e.data.self;
                if (self.status === StatusEnum.DEFAULT && self.startline > -1) {
                    self.status = StatusEnum.READING;
                    $('#dialogue-dialog-read').attr('class', 'popbtn_current');
                    $('#dialogue-dialog-readtext').text('停止朗读');
                    $('#dialogue-dialog-record').addClass('gray');
                    $('#dialogue-dialog-playback').addClass('gray');
                    $('#dialogue-dialog-constrast').addClass('gray');
                    $('#dialogue-dialog-persistent').attr('disabled', 'true');
                    self.curLine = self.startline - 1;
                    var audio = self.dialogue.option.sens[self.startline].audio;
                    speech.speecher.Player.loadAudio(encodeURI(audio));
                    speech.speecher.Player.play();
                } else if (self.status === StatusEnum.READING) {
                    self.isreset = true;
                    speech.speecher.Player.stop();
                }
            },

            'onClickPlayback': function(e) {
                var self = e.data.self;
                if (self.status === StatusEnum.DEFAULT && self.startline > -1) {
                    self.status = StatusEnum.PLAYBACKING;
                    $('#dialogue-dialog-playback').attr('class', 'popbtn_current');
                    $('#dialogue-dialog-playbacktext').text('停止回放');
                    $('#dialogue-dialog-record').addClass('gray');
                    $('#dialogue-dialog-read').addClass('gray');
                    $('#dialogue-dialog-constrast').addClass('gray');
                    $('#dialogue-dialog-persistent').attr('disabled', 'true');
                    self.curLine = self.startline - 1;
                    if (self.dialogue.option.sens[self.startline].role === self.dialogue.role ||
                        self.dialogue.mode == 1
                        ) {
//                        self.callback.onRecord.call(self);
                        var audio = self.dialogue.option.sens[self.startline].recordid;
                        speech.speecher.Recorder.loadAudio(audio, false);
                    } else {
                        var audio = self.dialogue.option.sens[self.startline].audio;
                        speech.speecher.Player.loadAudio(encodeURI(audio));
                        speech.speecher.Player.play();
                    }
                } else if (self.status === StatusEnum.PLAYBACKING) {
                    self.isreset = true;
                    speech.speecher.Player.stop();
                    speech.speecher.Recorder.stopPlay();
                }
            },

            'onClickConstrast': function(e) {
                var self = e.data.self;
                if (self.status === StatusEnum.DEFAULT && self.startline > -1) {
                    var startread = false;
                    if (self.dialogue.mode === ModeEnum.MANTOMAN || self.dialogue.option.sens[self.startline].role === self.dialogue.role) {
                        self.curLine = self.startline - 1;
                        startread = true;
                    } else if (
                        self.startline < self.dialogue.option.sens.length - 1 &&
                        self.dialogue.option.sens[self.startline + 1].role === self.dialogue.role
                    ) {
                        self.curLine = self.startline;
                        startread = true;
                    }

                    if (startread) {
                        self.status = StatusEnum.CONSTRAST;
                        $('#dialogue-dialog-constrast').attr('class', 'popbtn_current');
                        $('#dialogue-dialog-constrasttext').text('停止对比');
                        $('#dialogue-dialog-record').addClass('gray');
                        $('#dialogue-dialog-read').addClass('gray');
                        $('#dialogue-dialog-playback').addClass('gray');
                        $('#dialogue-dialog-persistent').attr('disabled', 'true');
                        var audio = self.dialogue.option.sens[self.curLine + 1].audio;
                        speech.speecher.Player.loadAudio(encodeURI(audio));
                        speech.speecher.Player.play();
                    }
                } else if (self.status === StatusEnum.CONSTRAST) {
                    self.isreset = true;
                    speech.speecher.Player.stop();
                    speech.speecher.Recorder.stopPlay();
                }
            }
        };
    };

    ScoreDetailsDialog.prototype.registerDomEvents = function() {
        $('#dialogue-dialog-close').bind('click', {'self': this}, this.close);
        $('.page_prev').bind('click', {'self': this}, this.openPrevPage);
        $('.page_next').bind('click', {'self': this}, this.openNextPage);
        $('#dialogue-dialog-persistent').bind('click', {'self': this}, this.changePersistent);
        $('#dialogue-dialog-record').bind('click', {'self': this}, this.callback.onClickRecord);
        $('#dialogue-dialog-read').bind('click', {'self': this}, this.callback.onClickRead);
        $('#dialogue-dialog-playback').bind('click', {'self': this}, this.callback.onClickPlayback);
        $('#dialogue-dialog-constrast').bind('click', {'self': this}, this.callback.onClickConstrast);
    };

    ScoreDetailsDialog.prototype.registerSpeechEvents = function() {
        var self = this;

        this.events = {
            recordEvents: {
                onEvalResult : function (e) {
                    if(e.resultType == EvalCallbackType.ENDPOINT)   {
                        speech.speecher.Recorder.stop();
                    } else {
                        var line = self.startline;
                        var cline = self.curLine;
                        var score = 0;

                        if ('result' in e && e.result && 'TotalScore' in e.result) {
                            score = parseInt(e.result.TotalScore * 20, 10);
                        }

                        self.dialogue.option.sens[cline].score = score;
                        self.dialogue.option.sens[cline].cssClass = score > 60 ? 'green' : 'red';

                        self.score.info.push({
                            line: cline,
                            score:score
                        })
                        $('#dialogue-dialog-line'+ (cline % 2)).css('color', '#333');
                        if(self.dialogue.mode == 1){
                            self.render();
                        }

                        //0: stop all; 1: record; 2:play; 3:record play
                        var nextStepType = 0;

                        if (self.isreset || cline > line || self.dialogue.option.sens[line + 1].role !== self.dialogue.role) {
                            nextStepType = 0;
                        } else if (self.dialogue.mode === ModeEnum.MANTOMAN || self.dialogue.option.sens[cline + 1].role === self.dialogue.role){
                            nextStepType = 1;
                        }

                        switch (nextStepType) {
                            case 1:
                                setTimeout(function(){
                                    self.callback.onRecord.call(self);
                                },100);
                                break;
                            default:
                                self.resetBtns();
                                self.render();
                                self.curLine = line;
                                self.isreset = false;
                                self.status = StatusEnum.DEFAULT;
                                $('#dialogue-dialog-persistent').removeAttr('disabled');
                        }
                    }
                },

                onRecording : function (e) {
                    var node = $("#dialogue-dialog-voice");

                    node.css('width', e.energy +'%').css('background', '-webkit-gradient(linear, 0 0, 0 100%, from(#a6d77b),to(#9bce65))');
                    if (e.energy < 20) {
                        node.css('background', '-webkit-gradient(linear, 0 0, 0 100%, from(#B86060),to(#F50808))');
                    }
                },

                onAudioLoaded : function() {
                    self.curLine += 1;
                    $('#dialogue-dialog-line'+ (self.curLine % 2)).css('color', '#2fb4d6');
                    speech.speecher.Recorder.play();
                },

                onPlayBegin: function(e) {
                    if (0 === self.curLine % 2) {
                        var _startline = self.startline;
                        self.startline = self.curLine;
                        self.render();
                        $('#dialogue-dialog-line0').css('color', '#2fb4d6');
                        self.startline = _startline;
                    } else {
                        if (self.status === StatusEnum.CONSTRAST) {
                            var _startline = self.startline;
                            self.startline = self.curLine - 1;
                            self.render();
                            $('#dialogue-dialog-line1').css('color', '#2fb4d6');
                            self.startline = _startline;
                        } else {
                            $('#dialogue-dialog-line1').css('color', '#2fb4d6');
                        }
                    }
                    $('.page_prev').addClass('gray');
                    $('.page_next').addClass('gray');
                },

                onPlayStop : function(e) {
                    var nextStepType = 0;
                    if(!self.persistent &&
                        self.dialogue.mode != 1 &&
                        self.dialogue.role == 'A' &&
                        self.status == StatusEnum.CONSTRAST
                        ){
                            nextStepType = 0;
                    }else{
                        if (
                            self.isreset ||
                                self.curLine === self.dialogue.option.sens.length - 1 ||
                                (!self.persistent && self.curLine > self.startline)
                            ) {
                            nextStepType = 0;
                        } else if (self.status !== StatusEnum.CONSTRAST) {
                            if (
                                self.mode === StatusEnum.MANTOMAN ||
                                    self.dialogue.option.sens[self.curLine + 1].role === self.dialogue.role
                                ){
                                //防止录音记录里不存在此句的录音,就是用标准音
                                if (self.dialogue.option.sens[self.curLine + 1].recordid !== '') {
                                    nextStepType = 3;
                                } else {
                                    nextStepType = 2;
                                }
                            } else {
                                nextStepType = 2;
                            }
                        } else {
                            if (self.dialogue.mode !== ModeEnum.MANTOMAN) {
                                for(var i in self.dialogue.option.sens) {
                                    if (i > self.curLine && self.dialogue.option.sens[i].role === self.dialogue.role) {
                                        nextStepType = 2;
                                        self.curLine = i - 1;
                                        break;
                                    }
                                }
                            } else {
                                nextStepType = 2;
                            }
                        }
                    }
                    $('#dialogue-dialog-line'+ (self.curLine % 2)).css('color', '#333');
                    switch (nextStepType) {
                        case 2:
                            var audio = self.dialogue.option.sens[self.curLine + 1].audio;
                            speech.speecher.Player.loadAudio(encodeURI(audio));
                            speech.speecher.Player.play();
                            break;
                        case 3:
                            speech.speecher.Recorder.loadAudio(self.dialogue.option.sens[self.curLine + 1].recordid, false);
                            break;
                        default:
                            self.resetBtns();
                            self.render();
                            self.curLine = self.startline;
                            self.isreset = false;
                            self.status = StatusEnum.DEFAULT;
                            $('#dialogue-dialog-persistent').removeAttr('disabled');
                    }
                },

                onRecordBegin : function(e) {
                    self.curLine += 1;
                    self.dialogue.records[self.curLine] = self.dialogue.recordid;
                    self.dialogue.option.sens[self.curLine].recordid = self.dialogue.recordid;
                    $('#dialogue-dialog-voicebar').show();
                    if (0 === self.curLine % 2) {
                        $('#dialogue-dialog-line0').css('color', '#2fb4d6');
                    } else {
                        $('#dialogue-dialog-line1').css('color', '#2fb4d6');
                    }
                    $('.page_prev').addClass('gray');
                    $('.page_next').addClass('gray');
                },

                onError : function(e) {
                    if (self.status === StatusEnum.RECORDING) {
                        self.events.recordEvents.onEvalResult(e);
                    } else if (self.status === StatusEnum.PLAYBACKING || self.status === StatusEnum.CONSTRAST) {
                        self.curLine += 1;
                        var num = self.curLine % 2;
                        $('#dialogue-dialog-line' + num).css('color', '#2fb4d6');

                        setTimeout(function(){
                            self.events.recordEvents.onPlayStop(e);
                        },500);
                    }
                }
            },

            playEvents:{
                onStop : function(e) {
                    $('#dialogue-dialog-line'+ (self.curLine % 2)).css('color', '#333');

                    var nextStepType = 0;
                    //点击关闭按钮；读完最后一句；非连续模式下读完两句话停止
                    if (
                        self.isreset ||
                        (self.status !== StatusEnum.CONSTRAST && self.curLine === self.dialogue.option.sens.length - 1) ||
                        (!self.persistent && self.status !== StatusEnum.CONSTRAST && self.curLine > self.startline)
                    ) {
                        nextStepType = 0;
                    } else {
                        if (self.status === StatusEnum.READING) {
                            nextStepType = 2;
                        } else if (self.status === StatusEnum.PLAYBACKING) {
                            if (self.mode === StatusEnum.MANTOMAN || self.dialogue.option.sens[self.curLine + 1].role === self.dialogue.role) {
                                if (self.dialogue.option.sens[self.curLine + 1].recordid !== '') {
                                    nextStepType = 3;
                                } else {
                                    nextStepType = 2;
                                }
                            } else {
                                nextStepType = 2;
                            }
                        } else if (self.status === StatusEnum.CONSTRAST) {
                            if (self.dialogue.option.sens[self.curLine].recordid !== '') {
                                nextStepType = 3;
                                self.curLine -= 1;
                            } else {
                                for(var i in self.dialogue.option.sens) {
                                    if (i > self.curLine && self.dialogue.option.sens[i].role === self.dialogue.role) {
                                        nextStepType = 2;
                                        self.curLine = i - 1;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    switch(nextStepType) {
                        case 2:
                            var audio = self.dialogue.option.sens[self.curLine + 1].audio;
                            speech.speecher.Player.loadAudio(encodeURI(audio));
                            speech.speecher.Player.play();
                            break;
                        case 3:
                            speech.speecher.Recorder.loadAudio(self.dialogue.option.sens[self.curLine + 1].recordid, false);
                            break;
                        default:
                            self.resetBtns();
                            self.render();
                            self.curLine = self.startline;
                            self.isreset = false;
                            self.status = StatusEnum.DEFAULT;
                            $('#dialogue-dialog-persistent').removeAttr('disabled');
                    }
                },

                onPlayBegin: function(e) {
                    self.curLine += 1;
                    if (0 === self.curLine % 2) {
                        var _startline = self.startline;
                        self.startline = self.curLine;
                        self.render();
                        $('#dialogue-dialog-line0').css('color', '#2fb4d6');
                        self.startline = _startline;
                    } else {
                        if (self.status === StatusEnum.CONSTRAST) {
                            var _startline = self.startline;
                            self.startline = self.curLine - 1;
                            self.render();
                            $('#dialogue-dialog-line1').css('color', '#2fb4d6');
                            self.startline = _startline;
                        } else {
                            $('#dialogue-dialog-line1').css('color', '#2fb4d6');
                        }
                    }
                    $('.page_prev').addClass('gray');
                    $('.page_next').addClass('gray');
                },

                onError : function(e) {
                    self.events.playEvents.onStop(e);
                }
            }
        };
        speech.registerEvent(this.events);
    };

    /**
     * 情景对话卡片的初始化
     * @param {[type]} option 接受的参数
     * {
     *  "img": '',
     *  "sens": [
     *         {
     *             "role": "A",
     *             "audio": 'E:/audio/0.wav',
     *             "hotArea": [],
     *             'text': ''
     *         },
     *         {
     *             "role": "B",
     *             "audio": 'E:/audio/1.wav',
     *             "hotArea": [],
     *             'text': ''
     *         }
     *     ]
     * }
     */
    function Dialogue(option) {
        //ensure that use 'new' to create instance, instead of a direct call function
        if (!(this instanceof Dialogue)) {
            throw new Error('The object not instanceof Poetry, please use `new` create it.');
        }
        /**
         * the card's ID, one dialogue instance has one ID
         */
        this.id = Dialogue.Counts + 1;

        /**
         * the infomation of records that seted on recording
         * @type {Object}
         */
        this.records = {};
        this.iserror = false;

        this.option = option;

        for (var i in this.option.sens) {
            this.option.sens[i].score = 0;
            this.option.sens[i].cssClass = 'red';
            this.option.sens[i].recordid = '';
        }

        this.maskOption = {
            self    : '',
            type    : 'dialogue',
            msg     : '资源加载中，请稍候',
            lagTime : 1,
            flag    : true
        };

        this.curLine = -1;

        /**
         * the status
         * @type {[Object]}
         */
        this.status = StatusEnum.DEFAULT;

        /**
         * reset the ui to the default
         * @type {Boolean}
         */
        this.isreset = false;

        /**
         * set the role of user for the dialogue
         */
        this.role = RoleEnum.B;

        /**
         * set the dialogue's mode, example: Man to Machine, Man To Man
         */
        this.mode = ModeEnum.MANTOMACHINE;

        this.render();

        /**
         * tools function
         */
        this.registerCallback(this);

        /**
         * DOM点击事件
         */
        this.registerDomEvents();

        /**
         * 真正的回调函数
         */
        this.registerSpeechEvents(this);

        /**
         * The card's setting dialog
         * @type {SettingDialog}
         */
        this.settingsDialog = new SettingsDialog(this);

        /**
         * The card's score details dialog
         * @type {ScoreDetailsDialog}
         */
        this.scoreDetailsDialog = new ScoreDetailsDialog(this);

    }

    Dialogue.Counts = 0;

    Dialogue.prototype = new cardbase.CardBase();
    Dialogue.prototype.constructor = Dialogue;

    Dialogue.prototype.getCardName = function () {
        return define.CardName.Situ;
    };

    Dialogue.prototype.render = function() {
        //for more cards, just load template at the first time
        if (this.id === 1) {
            $('body').append(tplparse.render(this.getTemplate(), this.option));
        }
        $('#dialogue-content').append(this._getContent());
        $("#backImg").attr("src",this.option.backgroundimg);
        mask.showMask(this.maskOption);
    };

    Dialogue.prototype.registerCallback = function(self) {
        var _this = this;
        this.callback = {
            'onRecord': function(e) {
                this.recordid = getRecordID();
                var success = speech.speecher.Recorder.record({
                    evalType : SeEvalType.ReadSentence,
                    evalText : e.text,
                    evalParams : "autoTrack=true,trackType=easy,vadEnable=true,vadSpeechTail=1000",
                    sndId : this.recordid
                });
                if(!success){
                    _this.callback.onRecordedAll.call(_this, {});
                }
            },
            onRecorded: function(e) {
                var role = this.option.sens[this.curLine].role;
                if (this.mode === ModeEnum.MANTOMACHINE && this.role !== role) {
                    return;
                }

                var score = 0;
                if ('result' in e && 'TotalScore' in e.result) {
                    score = parseInt(e.result.TotalScore * 20, 10);
                    this.option.sens[this.curLine].score = score;
                    this.option.sens[this.curLine].cssClass = score > 60 ? 'green' : 'red';
                }

                var tipclass = score < 60 ? 'red dialogue-score' : 'green dialogue-score';
                if (role === RoleEnum.B) {
                    $('#dialogue-line'+ this.curLine).css('border', '1px solid #65CCEE');
                } else {
                    $('#dialogue-line'+ this.curLine).css('border', '1px solid #CEC2AC');
                }

                $('#dialogue-line'+ this.curLine +'-score').show().attr('class', tipclass).text(score +'分');
                $('#dialogue-line'+ this.curLine +'-tip').hide();
                $('#dialogue-main-voicebar').hide();
            },

            'onRecordedAll': function(e) {
                if(this.iserror == false && ('score' in e)){
                    var tipclass = e.score < 60 ? 'left total-score-red' : 'left total-score-green';
                    if (e.score < 60) {
                        $('#dialogue-face').removeClass('face-good').addClass('face-bad');
                    } else {
                        $('#dialogue-face').removeClass('face-bad').addClass('face-good');
                    }
                    $('#dialogue-totalscore').show().attr('class', tipclass).text(e.score +' 分');
                }else{
                    $('.dialogue-score').hide();
                }

                $("#dialogue-record-text").text('开始录音');
                $('#dialogue-record').attr('class', 'popbtn_normal');
                $('#dialogue-read').attr('class', 'popbtn_normal');
                if (!isEmptyObject(this.records)) {
                    $('#dialogue-playback').attr('class', 'popbtn_normal');
                } else {
                    $('#dialogue-playback').attr('class', 'popbtn_normal gray');
                }
                $('#dialogue-read').removeClass('gray');
                $('#dialogue-settings').removeClass('gray');
                this.status = StatusEnum.DEFAULT;
                this.curLine = -1;
                this.isreset = false;
            },

            'onPlay': function(e) {
                speech.speecher.Player.loadAudio(encodeURI(e.audio));
                speech.speecher.Player.play();
            },

            'onPlayed': function(score) {
                //TODO:根据状态的不同进行不同的处理,主要是把相应的按钮返回常态
                if (this.status === StatusEnum.RECORDING) {
                    $('#dialogue-record').attr('class', 'popbtn_normal');
                    $('#dialogue-record-text').text('开始对话');

                    if(!isNaN(score)){
                        var tipclass = score < 60 ? 'left total-score-red' : 'left total-score-green';
                        if (score < 60) {
                            $('#dialogue-face').removeClass('face-good').addClass('face-bad');
                        } else {
                            $('#dialogue-face').removeClass('face-bad').addClass('face-good');
                        }
                        $('#dialogue-totalscore').show().attr('class', tipclass).text(score +' 分');
                    }

                } else if (this.status === StatusEnum.READING) {
                    $('#dialogue-read').attr('class', 'popbtn_normal');
                    $('#dialogue-read-text').text('示范朗读');
                } else if (this.status === StatusEnum.PLAYBACKING) {
                    $('#dialogue-playback').attr('class', 'popbtn_normal');
                    $('#dialogue-playback-text').text('对话回放');
                }

                $('#dialogue-read').removeClass('gray');
                $('#dialogue-settings').removeClass('gray');
                if (!isEmptyObject(this.records)) {
                    $('#dialogue-playback').removeClass('gray');
                }
                $('#dialogue-record').removeClass('gray');
                this.status = StatusEnum.DEFAULT;
                this.curLine = -1;
                this.isreset = false;
            },

            'onPlayback': function(e) {
                setTimeout(function(){
                    var recordid = e.recordid;
                    speech.speecher.Recorder.loadAudio(recordid);
                },200)
            },

            'onPlaybacked': function(e) {
                var role = this.option.sens[this.curLine].role;
                if (role === RoleEnum.B) {
                    $('#dialogue-line'+ this.curLine).css('border', '1px solid #65CCEE');
                } else {
                    $('#dialogue-line'+ this.curLine).css('border', '1px solid #CEC2AC');
                }
            },

            'onPlaybackedAll': function(e) {
                $('#dialogue-playback').attr('class', 'popbtn_normal');
                $('#dialogue-playback-text').text('对话回放');
                $('#dialogue-read').removeClass('gray');
                $('#dialogue-record').removeClass('gray');
                $('#dialogue-settings').removeClass('gray');
                this.status = StatusEnum.DEFAULT;
                this.curLine = -1;
                this.isreset = false;
            },

            'onClickRecordBtn': function(e) {
                var self = e.data.self;
                if (!speech.speecher.Player || !speech.speecher.Recorder) {
                    alert('网络错误， 请检查网络是否正常！');
                    return;
                }
                if (self.status === StatusEnum.DEFAULT && self.option.sens.length > 0) {
                    self.status = StatusEnum.RECORDING;
                    self.records = {};
                    $('#dialogue-record').attr('class', 'popbtn_current');
                    $('#dialogue-record-text').text('停止对话');
                    $('.dialogue-score').hide();
                    $('#dialogue-read').addClass('gray');
                    $('#dialogue-playback').addClass('gray');
                    $('#dialogue-settings').addClass('gray');
                    if (self.mode === ModeEnum.MANTOMAN || self.option.sens[0].role === self.role) {
                        var text = self.option.sens[0].text;
                        self.callback.onRecord.call(self, {'text': text});
                    } else {
                        var audio = self.option.sens[0].audio;
                        self.callback.onPlay({'audio': audio});
                    }
                } else if (self.status === StatusEnum.RECORDING) {
                    self.isreset = true;
                    speech.speecher.Recorder.stop();
                    speech.speecher.Player.stop();
                }
            },

            'onClickReadBtn': function(e) {
                var self = e.data.self;
                if (!speech.speecher.Player || !speech.speecher.Recorder) {
                    alert('网络错误， 请检查网络是否正常！');
                    return;
                }
                if (self.status === StatusEnum.DEFAULT && self.option.sens.length > 0) {
                    self.status = StatusEnum.READING;
                    $('#dialogue-read').attr('class', 'popbtn_current');
                    $('#dialogue-read-text').text('停止朗读');
//                    $('.dialogue-score').hide();
                    $('#dialogue-record').addClass('gray');
                    $('#dialogue-playback').addClass('gray');
                    $('#dialogue-settings').addClass('gray');
                    var audio = self.option.sens[0].audio;
                    self.callback.onPlay({'audio': audio});
                } else if (self.status === StatusEnum.READING) {
                    self.isreset = true;
                    speech.speecher.Player.stop();
                }
            },

            'onClickPlaybackBtn': function(e) {
                var self = e.data.self;
                if (!speech.speecher.Player || !speech.speecher.Recorder) {
                    alert('网络错误， 请检查网络是否正常！');
                    return;
                }

                if(isEmptyObject(self.records)) {
                    return;
                }

                if (self.status === StatusEnum.DEFAULT && self.option.sens.length > 0) {
                    self.status = StatusEnum.PLAYBACKING;
                    $('#dialogue-playback').attr('class', 'popbtn_current');
                    $('#dialogue-playback-text').text('停止回放');
   //                 $('.dialogue-score').hide();
                    $('#dialogue-read').addClass('gray');
                    $('#dialogue-record').addClass('gray');
                    $('#dialogue-settings').addClass('gray');
                    if (self.mode === ModeEnum.MANTOMAN || self.option.sens[0].role === self.role) {
                        var recordid = self.records[0];
                        self.callback.onPlayback({'recordid': recordid});
                    } else {
                        var audio = self.option.sens[0].audio;
                        self.callback.onPlay({'audio': audio});
                    }
                } else if (self.status === StatusEnum.PLAYBACKING) {
                    self.isreset = true;
                    speech.speecher.Player.stop();
                    speech.speecher.Recorder.stopPlay();
                }
            },

            'onClickSettingsBtn': function(e) {
                var self = e.data.self;
                if (self.status === StatusEnum.DEFAULT) {
                    var bw = $('body').width();
                    var bh = $('body').height();
                    $('#dialogue-bg').css({
                        width : bw,
                        height : bh
                        //width:"100%",
                        //height:"100%"
                    });
                    self.settingsDialog.open();
                }
            },

            'onClickSentence': function(e) {
                var self = e.data.self;
                if (!speech.speecher.Player || !speech.speecher.Recorder) {
                    alert('网络错误， 请检查网络是否正常！');
                    return;
                }
                var line = $('#'+ e.target.id).parent().data('line');
                if ( self.status === StatusEnum.DEFAULT && !isEmptyObject(self.records) ) {
                    self.scoreDetailsDialog.registerSpeechEvents();
                    self.scoreDetailsDialog.open(line);

                    var bw = $('body').width();
                    var bh = $('body').height();
                    $('#dialogue-bg').css({
                        width : bw,
                        height : bh
                    });
                   // $('#dialogue-scoreinfo-dialog').css("margin-left",0.18*bw);
                }
            }
        };
    };

    Dialogue.prototype.registerDomEvents = function() {
        $('#dialogue-record').bind('click', {'self': this}, this.callback.onClickRecordBtn);
        $('#dialogue-read').bind('click', {'self': this}, this.callback.onClickReadBtn);
        $('#dialogue-playback').bind('click', {'self': this}, this.callback.onClickPlaybackBtn);
        $('#dialogue-settings').bind('click', {'self': this}, this.callback.onClickSettingsBtn);
        $('.dialogue-sentence').bind('click', {'self': this}, this.callback.onClickSentence);
    };

    Dialogue.prototype.registerSpeechEvents = function(self) {
        var self = this;
        var totalRecordScore = 0;
        var count = 0;

        this.events = {
            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) {
                    if(e.resultType == EvalCallbackType.ENDPOINT)   {
                        speech.speecher.Recorder.stop();
                    } else {
                        if ('result' in e && 'TotalScore' in e.result) {
                            totalRecordScore += e.result.TotalScore * 20;
                            count += 1;
                            console.log(self.curLine);
                        }

                        self.callback.onRecorded.call(self, e);

                        if (self.isreset || self.curLine === self.option.sens.length - 1) {
                            count = count === 0 ? 1 : count;
                            e.score = parseInt(totalRecordScore / count, 10);
                            self.callback.onRecordedAll.call(self, e);
                            totalRecordScore = 0;
                            count = 0;
                            return;
                        }

                        var nextLine = self.curLine + 1;
                        if (self.mode === ModeEnum.MANTOMAN || self.option.sens[nextLine].role === self.role){
                            var text = self.option.sens[nextLine].text;
                            setTimeout(function(){
                                self.callback.onRecord.call(self, {text:text});
                            }, 200);

                        } else {
                            e.audio = self.option.sens[nextLine].audio;
                            self.callback.onPlay.call(self, e);
                        }
                        self.iserror = false;
                    }
                },

                onRecording : function (e) {
                    var node = $("#dialogue-main-voice");

                    node.css('width', e.energy +'%').css('background', '-webkit-gradient(linear, 0 0, 0 100%, from(#a6d77b),to(#9bce65))');
                    if (e.energy < 20) {
                        node.css('background', '-webkit-gradient(linear, 0 0, 0 100%, from(#B86060),to(#F50808))');
                    }
                },

                onAudioLoaded : function() {
                    self.curLine += 1;
                    $('#dialogue-line'+ self.curLine).css('border', '1px solid #F01515');
                    speech.speecher.Recorder.play();
                },

                onPlayStop : function(e) {
                    self.callback.onPlaybacked.call(self, e);
                    if (self.isreset || self.curLine === self.option.sens.length - 1) {
                        self.callback.onPlaybackedAll.call(self, e);
                        return;
                    }
                    var nextLine = self.curLine + 1;
                    if (
                        (self.mode === ModeEnum.MANTOMAN || self.option.sens[nextLine].role === self.role) &&
                        nextLine in self.records
                    ){
                        e.recordid = self.records[nextLine];
                        self.callback.onPlayback.call(self, e);
                    } else {
                        e.audio = self.option.sens[nextLine].audio;
                        self.callback.onPlay.call(self, e);
                    }
                },

                onRecordBegin : function(e) {
                    self.curLine += 1;
                    self.records[self.curLine] = self.recordid;
                    self.option.sens[self.curLine].recordid = self.recordid;
                    $('#dialogue-main-voicebar').show();
                    $('#dialogue-line'+ self.curLine).css('border', '1px solid #F01515');
                    $('#dialogue-line'+ self.curLine +'-tip').show();
                },

                onError : function(e) {
                    //录音或播放出错，继续下一句，直到录制完
                    if (self.status === StatusEnum.RECORDING) {
                        if( (e.errorType == 2 && (e.errorCode == 11004 || e.errorCode == 120106)) ||
                            (e.errorType == 1 && e.errorCode == 4002) )
                        {
                            self.iserror = true;
                            self.isreset = true;
                            var maskOption = {
                                self    : '',
                                type    : 'dialogue',
                                msg     : '登陆云平台出错',
                                lagTime : 1,
                                flag    : true
                            };
                            mask.showMask(maskOption);
                            setTimeout(function(){
                                maskOption.flag = false;
                                mask.showMask(maskOption);
                            },2000)
                        }
                        self.events.recordEvents.onEvalResult(e);
                    } else if (self.status === StatusEnum.PLAYBACKING) {
                        self.curLine += 1;
                        $('#dialogue-line'+ self.curLine).css('border', '1px solid #F01515');
                        setTimeout(function(){
                            self.events.recordEvents.onPlayStop(e);
                        },500);
                    }
                }
            },

            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(e) {
                    $('#dialogue-line'+ self.curLine).css('border', '1px solid #CEC2AC');

                    if (self.isreset || self.curLine === self.option.sens.length - 1) {
                        var score = parseInt(totalRecordScore / count, 10);
                        totalRecordScore = 0;
                        count = 0;
                        self.callback.onPlayed.call(self, score);
                        return;
                    }

                    var nextLine = self.curLine + 1;
                    if (self.status === StatusEnum.RECORDING && self.option.sens[nextLine].role === self.role){
                        self.callback.onRecord.call(self, {"text": self.option.sens[nextLine].text});
                    } else if (self.status === StatusEnum.PLAYBACKING && self.option.sens[nextLine].role === self.role && nextLine in self.records) {
                        self.callback.onPlayback.call(self, {"recordid": self.records[nextLine]});
                    } else {
                        self.callback.onPlay.call(self, {"audio": self.option.sens[nextLine].audio});
                    }
                },

                onPlayBegin: function(e) {
                    self.curLine += 1;
                    $('#dialogue-line'+ self.curLine).css('border', '1px solid #F01515');
                },

                onError : function(e) {
                    self.events.playEvents.onStop(e);
                }
            }
        };
        speech.registerEvent(self.events);
    };

    Dialogue.prototype._getContent = function() {
        var text = '';
        var sens = this.option.sens;
        for (var i in sens) {
            if (sens[i].role === this.role) {
                text += '<dd id="dialogue-line'+i +'" class="dialogue-sentence" data-line="'+i+'"> <span id="dialogue-line'+i+'-title">'+sens[i].text+'</span><span style="display:none;" class="green dialogue-score" id="dialogue-line'+i+'-score">0分</span> <b class="dialogue-ddarrow"></b> <font style="display:none;" id="dialogue-line'+i+'-tip" class="btn_gray" onMouseDown="this.className=\'btn_gray_pressed\'" onmouseout="this.className=\'btn_gray\'"/> </font> </dd>';
            } else {
                text += '<dt id="dialogue-line'+i +'" class="dialogue-sentence" data-line="'+i+'"> <span id="dialogue-line'+i+'-title">'+sens[i].text+'</span><span style="display:none;" class="green dialogue-score" id="dialogue-line'+i+'-score">0分</span> <b class="dialogue-dtarrow"></b> <font style="display:none;" id="dialogue-line'+i+'-tip" class="btn_gray" onMouseDown="this.className=\'btn_gray_pressed\'" onmouseout="this.className=\'btn_gray\'"/> </font> </dt>';
            }
        }
        return text;
    };

    exports.Constructor = Dialogue;
});
