!function ($, window, undefined) {

    //【整个页面的题目集合】
    var Queue = window._.Queue,
            QueObj = window._.QueObj,
            QueType = window._.QueType,
            TypeList = window._.TypeList,
            StringBuilder = window._.StringBuilder,
            stringformat = window._.stringformat,
            queues = new Queue(),
            isEditPage = (isEditPage = QueryString("pageType")) == 1 || !isEditPage ? false : true, //当前页面是否是编辑页面
            editQueKey = -1,   //当前操作是否是编辑操作，<0表示正在添加，>0表示正在编辑，并表示编辑的题目索引
            examKey = (examKey = QueryString('Key')) === 'TKNC' ? examKey || '' : examKey, //如果是编辑试卷，则是编辑的试卷ID            
txtObj, //文本框对象
    //一组数组，用于把索引转换为字母（标识题目选项）
            opArray = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
    //阻止事件冒泡，jQuery事件模型已经重写（兼容）该方法
        stopBubble = function (e) {
            // 如果传入了事件对象，那么就是非ie浏览器  
            if (e && e.stopPropagation) {
                //因此它支持W3C的stopPropagation()方法  
                e.stopPropagation();
            } else {
                //否则我们使用ie的方法来取消事件冒泡  
                window.event.cancelBubble = true;
            }
        },
        imgLoad = function (objImg, maxWidth, maxHeight) {
            ///	<summary>
            ///     根据图片对象和指定的参数按比例缩放图片
            ///     &#10;1: resizeimg(obj, maxW, maxH) - 根据图片对象和指定的参数按比例缩放图片
            ///	</summary>
            ///	<param name="obj" type="ImageObject">图片对象</param>
            ///	<param name="maxW" type="int">最大宽度</param>
            ///	<param name="maxH" type="int">最大高度</param>
            ///	<returns type="string" />
            objImg.style.visibility = 'hidden';
            var img = new Image();
            img.src = objImg.src;
            var w = img.width == 0 ? objImg.width : img.width; //chrome在图片加载的时候宽高为0，当创建Image对象的时候读取宽高，但是因为在加载所以宽高为0，于是取原对象的值
            var h = img.height == 0 ? objImg.height : img.height;
            alert(w)
            var hRatio;
            var wRatio;
            var Ratio = 1;
            wRatio = maxWidth / w;
            hRatio = maxHeight / h;
            if (maxWidth == 0 && maxHeight == 0) {
                Ratio = 1;
            } else if (maxWidth == 0) {//
                if (hRatio < 1) Ratio = hRatio;
            } else if (maxHeight == 0) {
                if (wRatio < 1) Ratio = wRatio;
            } else if (wRatio < 1 || hRatio < 1) {
                Ratio = (wRatio <= hRatio ? wRatio : hRatio);
            }
            if (Ratio < 1) {
                w = w * Ratio;
                h = h * Ratio;
            }
            objImg.height = h;
            objImg.width = w;
            objImg.style.visibility = '';
        };
    String.prototype.replaceAll = function (str1, str2) {
        var str = this;
        var result = str.replace(eval("/" + str1 + "/gi"), str2);
        return result;
    }
    //**************************出题核心业务模块***********************************//
    //**********初始化题型***********//
    var initalQueType = function () {
        /*
        这里的验证并不严谨，正则应该是动态生成的，提供一个未实现但更恰当的思路：
        1、获取该题目选项，映射出A、B、C选项（全局变量opArray可以映射）
        2、根据映射的选项动态生成正则表达式，约束范围
        3、判定答案
        */
        var regRadioCheck = /([A-J]|[a-j])((.|、|,)*){1}/, //单选题答案验证
            regMultipleCheck = /([A-J]|[a-j])((.|、|,)*){1,10}/, //多选题答案验证
            regPaixuCheck = /^[0-9]*$/, //排序题答案
            optionFilter = /\b([a-z]|\d+)(:|\uff1a|\.|\u3001)/i,
        //regTiankongCheck = new RegExp("\\((.| )+?\\)", "igm"); //得到填空题的内容
            regTiankongCheck = new RegExp("[\\（|\\(](.| )+?[\\）|\\)]", "igm"); //得到填空题的内容            

        //初始化题型数据

        //{0}，索引，{1}题号，{2}题名，{3}label要for关联过去的索引
        //其中，单选的{0}是字母(A，B，C)，其余向后推一位
        //具体需要实际开发联调
        //单选


        /*
        题目对象模型：
        id: String,
        type:QueType ,
        title: [],
        dis: string,
        score: -1,
        option: [],
        answer: [],
        html: undefined
        */
        new QueType({
            typeName: 1,
            title: '<li class="question_Ttitle" id="que_{0}">{1}、{2}<span class="op_Title">[' + lgdanxuanti + ']</span><a href="javascript:void(0)" class="editQp" op_Id="{0}">' + lgbianji + '</a><a href="javascript:void(0)" class="deleteQp" op_Id="{0}">' + lgshanchu + '</a></li>',
            option: '<li><span class="question_Ttitle">{3}:</span><input id="list_rdo_{1}{0}" type="radio" name="que_rdo_{1}" /><label for="list_rdo_{1}{0}">{2}</label></li>',
            score: '<li>' + lgfenshu + '：{0}</li>',
            //check参数：第一个参数表示正在验证的题目对象，第二个参数表示该对象的题号
            //返回false表示验证通过，否则返回验证不通过的警告字符串(或true)
            fnCheck: function (item, index) {
                if (!item.answer.length) {
                    return lglgdaanbunengweikong;
                }
                else if (!regRadioCheck.test(item.answer.join())) {
                    return lglgdaangeshibuzhengque;
                }
                else if (item.answer.join().replace(/\s/g, "").length != 1) {
                    return lgdanxuantilgdaanzhineng + ":" + item.answer.join();
                }
                else if (item.option.length < 1 || item.option.length > 10) {
                    return lgtmxxslbxw + ":" + item.option.length;
                }
                else {
                    return false;
                }
            }
        });
        //多选题
        new QueType({
            typeName: 2,
            title: '<li class="question_Ttitle" id="que_{0}">{1}、{2}<span class="op_Title">[' + lgduoxuanti + ']</span><a href="javascript:void(0)" class="editQp" op_Id="{0}">' + lgbianji + '</a><a href="javascript:void(0)" class="deleteQp" op_Id="{0}">' + lgshanchu + '</a></li>',
            option: '<li><span class="question_Ttitle">{3}：</span><input id="list_cbo_{1}{3}" type="checkbox" name="que_cbo_{1}" /><label for="list_cbo_{1}{3}">{2}</label></li>',
            score: '<li>' + lgfenshu + '：{0}</li>',
            fnCheck: function (item, index) {
                //没有答案
                if (!item.answer.length) {
                    return lglgdaanbunengweikong;
                }
                else if (!regRadioCheck.test(item.answer.join(''))) {
                    return lglgdaangeshibuzqueabc;
                }
                else if (item.option.length < 1 || item.option.length > 10) {
                    return lgtmxxslbxw + ":" + item.option.length;
                }
                else {
                    return false;
                }
            }
        });
        //问答题
        new QueType({
            typeName: 3,
            title: '<li class="question_Ttitle" id="que_{0}">{1}、{2}<span class="op_Title">[' + lgjiandati + ']</span><a href="javascript:void(0)" class="editQp" op_Id="{0}">' + lgbianji + '</a><a href="javascript:void(0)" class="deleteQp" op_Id="{0}">' + lgshanchu + '</a></li>',
            option: undefined,
            score: '<li>' + lgfenshu + '：{0}</li>',
            //check参数：第一个参数表示正在验证的题目对象，第二个参数表示该对象的题号
            //返回false表示验证通过，否则返回验证不通过的警告字符串(或true)
            fnCheck: function (item, index) {
                if (item.option.length > 0) {
                    return lgwendatixuxiang;
                }
                else {
                    return false;
                }
            }
        });
        //判断题
        new QueType({
            typeName: 4,
            title: '<li class="question_Ttitle" id="que_{0}">{1}、{2}<span class="op_Title">[' + lgpanduanti + ']</span><a href="javascript:void(0)" class="editQp" op_Id="{0}">' + lgbianji + '</a><a href="javascript:void(0)" class="deleteQp" op_Id="{0}">' + lgshanchu + '</a></li>',
            option: undefined,
            score: '<li>' + lgfenshu + '：{0}</li>',
            toHTML: function (item, index) {
                var html = new StringBuilder(), typeObj = this;
                for (var i = 0, len = item.title.length; i < len; i++) {
                    html.append(stringformat(typeObj.title, item.index, item.index + 1, item.title[i]));
                }
                for (var i = 0, len = item.option.length; i < len && len; i++) {
                    html.append(stringformat(typeObj.option, i, index, item.option[i], opArray[i]));
                }
                html.append('<li><input type="radio" name="que_jue_0" />' + lgYes + '</li><li><input type="radio" name="que_jue_1" />' + lgNo + '</li>');
                for (var i = 0, len = item.answer.length; i < len && len; i++) {
                    html.append(stringformat(typeObj.answer, item.answer[i]));
                }
                if (item.score) {
                    html.append(stringformat(typeObj.score, item.score));
                }
                if (item.dis)
                    html.append(stringformat(typeObj.dis, item.dis));
                return stringformat(typeObj.container, html.toString());
            },
            fnCheck: function (item, index) {
                var as = item.answer.join();
                if (as != lgYes && as != lgNo) {
                    return lgdanangeshizhinengwei; //答案只能为对,错;
                }
                else if (item.option.length > 0) {
                    return lgxuanzetiwuxushezhezhi; //选择题不能有选项
                }
                else {
                    return false;
                }
            }
        });
        //排序题
        new QueType({
            typeName: 5,
            title: '<li class="question_Ttitle" id="que_{0}">{1}、{2}<span class="op_Title">[' + lgpaixuti + ']</span><a href="javascript:void(0)" class="editQp" op_Id="{0}">' + lgbianji + '</a><a href="javascript:void(0)" class="deleteQp" op_Id="{0}">' + lgshanchu + '</a></li>',
            option: '<li><span class="question_Ttitle">{4}：</span><label for="list_cbo_{0}{1}">{2}</label></li>',
            score: '<li>' + lgfenshu + '：{0}</li>',
            //排序题需要重写toHTML
            toHTML: function (item, index) {
                var html = new StringBuilder(), typeObj = this;
                for (var i = 0, len = item.title.length; i < len; i++) {
                    html.append(stringformat(typeObj.title, item.index, item.index + 1, item.title[i]));
                }
                for (var i = 0, len = item.option.length; i < len && len; i++) {
                    html.append(stringformat(typeObj.option, item.index, item.index + 1, item.option[i], opArray[i], i + 1));
                }
                for (var i = 0, len = item.answer.length; i < len && len; i++) {
                    html.append(stringformat(typeObj.answer, item.answer[i]));
                }
                if (item.score) {
                    html.append(stringformat(typeObj.score, item.score));
                }
                if (item.dis)
                    html.append(stringformat(typeObj.dis, item.dis));
                return stringformat(typeObj.container, html.toString());
            },
            fnCheck: function (item, index) {
                //没有答案
                if (!item.answer.length) {
                    return lglgdaanbunengweikong;
                }
                else if (!regPaixuCheck.test(item.answer.join(''))) {
                    return lgdanangeshibuzhengq;
                }
                else if (item.option.length < 1 || item.option.length > 10) {
                    return lgtmxxslbxw + ":" + item.option.length;
                }
                else {
                    return false;
                }
            }
        });
        //填空题
        new QueType({
            typeName: 6,
            title: '<li class="question_Ttitle" id="que_{0}">{1}、{2}<span class="op_Title">[' + lgtiankongti + ']</span><a href="javascript:void(0)" class="editQp" op_Id="{0}">' + lgbianji + '</a><a href="javascript:void(0)" class="deleteQp" op_Id="{0}">' + lgshanchu + '</a></li>',
            option: undefined,
            score: '<li>' + lgfenshu + '：{0}</li>',
            toHTML: function (item, index) {
                var html = new StringBuilder(), typeObj = this;
                for (var i = 0, len = item.title.length; i < len; i++) {
                    html.append(stringformat(typeObj.title, item.index, item.index + 1, item.title[i]));
                }
                for (var i = 0, len = item.option.length; i < len && len; i++) {
                    html.append(stringformat(typeObj.option, item.index, item.index + 1, item.option[i], opArray[i], i + 1));
                }
                for (var i = 0, len = item.answer.length; i < len && len; i++) {
                    html.append(stringformat(typeObj.answer, item.answer[i]));
                }
                if (item.score) {
                    html.append(stringformat(typeObj.score, item.score));
                }

                if (item.dis)
                    html.append(stringformat(typeObj.dis, item.dis));
                return stringformat(typeObj.container, html.toString());
            },
            toObj: function (textStr, id) {
                //编辑模式下id不为空，添加模式id为空
                var data, result, item, i = j = 0;
                if (!textStr) return;
                var arr = [], newQue = new Queue(); //分割后的每一道题的数组
                if (textStr.indexOf("\n\n") >= 0) {//多题
                    if (id) return; //编辑题目的时候不允许产生多题
                    arr = textStr.split(/\n\n/g);
                } else {//一题
                    arr.push(textStr);
                }
                //多题
                while ((data = arr[i++]) !== undefined) {
                    if (!data) continue;
                    var obj = {
                        id: id,
                        type: this.typeName,
                        title: [],
                        dis: undefined,
                        score: 0,
                        option: [],
                        answer: [],
                        source: function () {
                            return data.indexOf('\n') === 0 ? data.substring(1, data.length) : data;
                        } ()
                    },
                    result = (data + '').indexOf("\n") >= 0 ? data.split(/\n/g) : [data],
                    index = -1;
                    j = 0; //重置j
                    while ((item = result[j++]) !== undefined) {
                        if (!item) continue;
                        //分解出题目
                        if (!item || !jQuery.trim(item)) continue;
                        //填空题答案与题目融合,此项无效
                        if (item.indexOf(lgdaan + "：") >= 0 || item.indexOf(lgdaan + ":") >= 0) {
                            //obj.answer.push(item.replace("答案：", "").replace("答案:", "")); //保存答案
                            continue;
                        }
                        if (item.indexOf(lgzhushi + "：") >= 0 || item.indexOf(lgzhushi + ":") >= 0) {
                            obj.dis = item.replace(lgzhushi + "：", "").replace(lgzhushi + ":", ""); //注释
                            continue;
                        }
                        if (item.indexOf(lgfenshu + "：") >= 0 || item.indexOf(lgfenshu + ":") >= 0) {
                            obj.score = item.replace(lgfenshu + "：", "").replace(lgfenshu + ":", ""); //注释
                            continue;
                        }
                        index++;
                        if (index === 0)
                            obj.title.push(item.replace(optionFilter, '')); //将标题中的题号去掉
                        else
                            obj.option.push(item.replace(optionFilter, '')); //过滤A之类的东西
                    }
                    //通标题中解析出答案
                    var daan = obj.title.join().match(regTiankongCheck);
                    if (daan != null && daan.length > 0) {
                        var daanstr = "";
                        for (var da = 0; da < daan.length; da++) {
                            var daanstr1 = jQuery.trim(daan[da].replace("（", "").replace("）", "").replace("(", "").replace(")", ""));
                            if (daanstr1 != undefined && daanstr1 != null && daanstr1 != "") {
                                daanstr += daanstr1 + "、"; ;
                            } else {
                                showTipsMsg(lgtktansw);
                                break;
                            }
                        }
                        daan = daanstr.substr(0, daanstr.length - 1);
                    }
                    obj.answer.push(daan);
                    //添加到数组中
                    newQue.add(new QueObj(obj));
                }
                return newQue;
            },
            fnCheck: function (item, index) {
                //alert(item.title.join());
                var daan = item.title.join().match(regTiankongCheck);
                if (daan == null) {
                    return lgtikongtizhongzhishaohaiyou;
                }
                else {
                    return false;
                }
            }
        });
        //综合题
        new QueType({
            typeName: 7,
            title: '<li class="question_Ttitle" id="que_{0}">{1}、{2}<span class="op_Title">[' + lgzongheti + ']</span> <a href="javascript:void(0)" class="deleteQp" op_Id="{0}">' + lgshanchu + '</a><a  href="javascript:void(0)" class="qtdanxuan" op_Id="{0}">' + lgdanxuanti + '</a><a  href="javascript:void(0)" class="qtduoxuan" op_Id="{0}">' + lgduoxuanti + '</a><a  href="javascript:void(0)" class="qtwenda" op_Id="{0}">' + lgjiandati + '</a></li>',
            option: undefined,
            answer: undefined,
            toHTML: function (item, index) {
                var html = new StringBuilder(), typeObj = this;
                for (var i = 0, len = item.title.length; i < len; i++) {
                    html.append(stringformat(typeObj.title, item.index, item.index + 1, item.title[i]));
                }
                //显示子题目
                if (item.child != null && item.child != undefined) {
                    //将模板程序处理下，让外面知道这是哪个的子集
                    var chtml = item.child.toHTML().replaceAll("class=\"editQp\"", "class=\"editQp\"  fid=\"" + item.index + "\" ");
                    html.append(chtml.replaceAll("class=\"deleteQp\"", "class=\"deleteQp\" fid=\"" + item.index + "\""));

                }
                if (item.dis)
                    html.append(stringformat(typeObj.dis, item.dis));
                return stringformat('<ul style="background:#f4f4f4; border:1px #ccc solid; padding:5px;" class="zht">{0}</ul>', html.toString());
            },
            toObj: function (textStr, id) {
                //重写文字转对象（综合题特殊，全部每日都为标题）
                if (!textStr) return;
                var newQue = new Queue();
                var obj = {};
                obj.id = id;
                obj.type = this.typeName;
                obj.title = [];
                obj.title.push(textStr.replaceAll(/\r\n/g, "<br>"));
                newQue.add(new QueObj(obj));
                return newQue;
            },
            fnCheck: function (item, index) {
                var daan = item.child;
                if (daan == undefined) {
                    return lgzonghetizhishao;
                }
                else if (daan.check().length > 0) {
                    var errlist = daan.check();
                    var errhtml = new StringBuilder();
                    for (var i = 0; i < errlist.length; i++) {
                        errhtml.append("<li>" + (parseInt(errlist[i].key) + 1) + lgticuowu + "：" + errlist[i].value + "</li>");
                    }
                    return "【" + lgzigeshicuowu + "：" + errhtml.toString() + "】";
                }
                else {
                    return false;
                }
            }
        });

        //B型题(选项)
        new QueType({
            typeName: 8,
            title: '<li class="question_Ttitle" id="que_{0}">{1}、{2}<span class="op_Title">[' + lgbxingti + ']</span> <a href="javascript:void(0)" class="deleteQp" op_Id="{0}">' + lgshanchu + '</a><a  href="javascript:void(0)" class="qtbtype" op_Id="{0}">' + lgbxingtigan + '</a></li>',
            option: undefined,
            answer: undefined,
            toHTML: function (item, index) {
                var html = new StringBuilder(), typeObj = this;
                for (var i = 0, len = item.title.length; i < len; i++) {
                    html.append(stringformat(typeObj.title, item.index, item.index + 1, item.title[i]));
                }
                //显示题目
                if (item.child != null && item.child != undefined) {
                    //将模板程序处理下，让外面知道这是哪个的子集
                    var chtml = item.child.toHTML().replaceAll("class=\"editQp\"", "class=\"editQp\"  fid=\"" + item.index + "\" ");
                    html.append(chtml.replaceAll("class=\"deleteQp\"", "class=\"deleteQp\" fid=\"" + item.index + "\""));

                }
                //if (item.dis)
                //html.append(stringformat(typeObj.dis, item.dis));
                return stringformat('<ul style="background:#f4f4f4; border:1px #ccc solid; padding:5px;" class="zht">{0}</ul>', html.toString());
            },
            toObj: function (textStr, id) {
                //重写文字转对象（综合题特殊，全部每日都为标题）
                if (!textStr) return;
                var newQue = new Queue();
                var obj = {};
                obj.id = id;
                obj.type = this.typeName;
                obj.title = [];
                //                obj.title.push(textStr.replaceAll(/\r\n/g, "<br>"));
                //(textStr + '').indexOf("\n") >= 0 ? textStr.split(/\n/g)  : [textStr]
                obj.title.push(textStr.replace(/\n/g, "<br/>"));
                newQue.add(new QueObj(obj));
                return newQue;
            },
            fnCheck: function (item, index) {
                var daan = item.child;
                if (daan == undefined) {
                    return lgbxingtizhishaozengjia;
                }
                else if (daan.check().length > 0) {
                    var errlist = daan.check();
                    var errhtml = new StringBuilder();
                    for (var i = 0; i < errlist.length; i++) {
                        errhtml.append("<li>" + (parseInt(errlist[i].key) + 1) + lgticuowu + "：" + errlist[i].value + "</li>");
                    }
                    return "【" + lgtimugeshicuowu + "：" + errhtml.toString() + "】";
                }
                else {
                    return false;
                }
            }
        });

        //B型题(题干)
        new QueType({
            typeName: 9,
            title: '<li class="question_Ttitle" id="que_{0}">{1}、{2}<span class="op_Title">[' + lgbxingtigan + ']</span><a href="javascript:void(0)" class="editQp" op_Id="{0}">' + lgbianji + '</a><a href="javascript:void(0)" class="deleteQp" op_Id="{0}">' + lgshanchu + '</a></li>',
            option: undefined,
            score: '<li>' + lgfenshu + '：{0}</li>',
            toHTML: function (item, index) {
                var html = new StringBuilder(), typeObj = this;
                for (var i = 0, len = item.title.length; i < len; i++) {
                    html.append(stringformat(typeObj.title, item.index, item.index + 1, item.title[i]));
                }
                item.option = ["A", "B", "C", "D", "E"];
                html.append('<li><input type="radio" name="que_btype" />A</li><li><input type="radio" name="que_btype" />B</li><li><input type="radio" name="que_btype" />C</li><li><input type="radio" name="que_btype" />D</li><li><input type="radio" name="que_btype" />E</li>');
                for (var i = 0, len = item.answer.length; i < len && len; i++) {
                    html.append(stringformat(typeObj.answer, item.answer[i]));
                }
                if (item.score) {
                    html.append(stringformat(typeObj.score, item.score));
                }
                if (item.dis)
                    html.append(stringformat(typeObj.dis, item.dis));
                return stringformat(typeObj.container, html.toString());
            },
            toObj: function (textStr, id) {
                //编辑模式下id不为空，添加模式id为空
                var data, result, item, i = j = 0;
                if (!textStr) return;
                var arr = [], newQue = new Queue(); //分割后的每一道题的数组            
                var vvvv = new RegExp('\\n(\\s)+?\\n');
                var daan = textStr.match(vvvv);
                if (textStr.indexOf("\n\n") >= 0) {//多题
                    if (id) return; //编辑题目的时候不允许产生多题
                    arr = textStr.split(/\n\n/g);
                } else if (vvvv.test(textStr)) {
                    if (id) return; //编辑题目的时候不允许产生多题
                    arr = textStr.split(daan[0]);
                } else {//一题
                    arr.push(textStr);
                }
                //多题
                while ((data = arr[i++]) !== undefined) {
                    if (!data) continue;
                    var obj = {
                        id: id,
                        type: this.typeName,
                        title: [],
                        dis: undefined,
                        score: 0,
                        option: [],
                        answer: [],
                        source: function () {
                            return data.indexOf('\n') === 0 ? data.substring(1, data.length) : data;
                        } ()
                    },
                    result = (data + '').indexOf("\n") >= 0 ? data.split(/\n/g) : [data],
                    index = -1;
                    j = 0; //重置j
                    while ((item = result[j++]) !== undefined) {
                        if (!item) continue;

                        //分解出题目
                        if (!item || !jQuery.trim(item)) continue;
                        if (item.indexOf(lgdaan + "：") >= 0 || item.indexOf(lgdaan + ":") >= 0) {
                            item = item.replace(/\s/g, "");
                            obj.answer.push(item.replace(lgdaan + "：", "").replace(lgdaan + ":", "")); //保存答案
                            continue;
                        }
                        if (item.indexOf(lgzhushi + "：") >= 0 || item.indexOf(lgzhushi + ":") >= 0) {
                            obj.dis = item.replace(lgzhushi + "：", "").replace(lgzhushi + ":", ""); //注释
                            continue;
                        }
                        if (item.indexOf(lgfenshu + "：") >= 0 || item.indexOf(lgfenshu + ":") >= 0) {
                            obj.score = item.replace(lgfenshu + "：", "").replace(lgfenshu + ":", ""); //注释
                            continue;
                        }
                        index++;
                        if (index === 0) {
                            obj.title.push(item.replace(optionFilter, '')); //将标题中的题号去掉
                        }
                    }
                    obj.option = ["A", "B", "C", "D", "E"];
                    //添加到数组中
                    newQue.add(new QueObj(obj));
                }
                return newQue;
            },
            fnCheck: function (item, index) {
                if (!item.answer.length) {
                    return lglgdaanbunengweikong;
                }
                else if (!regRadioCheck.test(item.answer.join())) {
                    return lglgdaangeshibuzhengque;
                }
                else if (item.answer.join().replace(/\s/g, "").length != 1) {
                    return lgbxingtilgdaanzhinengyou + ":" + item.answer.join();
                }
                else {
                    return false;
                }
            }
        });

    },
    //题目处理，这个方法是整个题目处理的入口
         getQuestionByPage = function (fid) {
             var textStr = txtObj.val(); //文本
             if (!textStr || !$.trim(textStr)) {
                 showTipsMsg(lgmeiyousuhruneirong, 2000, 3);
                 return;
             }
             if (fid == undefined || fid == null) {
                 //这里处理结束，注意采用check()检测一下数据安全，并在check()中修剪掉选项里面的A、B、C等数据，正则已经写好
                 if (editQueKey > -1) { //编辑
                     if (queues.child(editQueKey).id != undefined && queues.child(editQueKey).id != null && queues.child(editQueKey).id != "") {
                         queues.replace(editQueKey, TypeList[type].toObj(textStr, queues.child(editQueKey).id));
                     } else {
                         queues.replace(editQueKey, TypeList[type].toObj(textStr));
                     }
                 } else {
                     //这里不是queues，这里是针对大题目的子项目追加，应该是
                     //queues.child(索引).add(TypeList[type].toObj(textStr))
                     queues.add(TypeList[type].toObj(textStr));
                 }
             }
             else {
                 //....
                 //alert(editQueKey);
                 if (editQueKey > -1) { //编辑
                     queues.child(fid).child.replace(parseInt(editQueKey), TypeList[type].toObj(textStr));
                 } else {
                     queues.child(fid, TypeList[type].toObj(textStr));
                 }
             }
             showHTML();
         },
    //显示编辑窗口
         showEdit = function (title, key, fid) { //创建对话框
             if (editQueKey > -1)
                 $("#addQuesionContainer").css("width", "800");
             else
                 $("#addQuesionContainer").css("width", "auto");
             var $discriptionObjs = $(".questionDiscription"), config = [];
             $discriptionObjs.removeClass("activeDiscription");
             if (key) {
                 switch (key) {
                     case "addsingle":
                         $discriptionObjs.eq(0).addClass("activeDiscription");
                         title += lgdanxuanti;
                         type = 1;
                         break;
                     case "addmultiple":
                         $discriptionObjs.eq(1).addClass("activeDiscription");
                         title += lgduoxuanti;
                         type = 2;
                         break;
                     case "addanswer":
                         $discriptionObjs.eq(2).addClass("activeDiscription");
                         title += lgjiandati;
                         type = 3;
                         break;
                     case "addjudge":
                         $discriptionObjs.eq(3).addClass("activeDiscription");
                         title += lgpanduanti;
                         type = 4;
                         break;
                     case "addsort":
                         $discriptionObjs.eq(4).addClass("activeDiscription");
                         title += lgpaixuti;
                         type = 5;
                         break;
                     case "addfill":
                         $discriptionObjs.eq(5).addClass("activeDiscription");
                         title += lgtiankongti;
                         type = 6;
                         break;
                     case "addbig":
                         $discriptionObjs.eq(6).addClass("activeDiscription");
                         title += lgzongheti;
                         type = 7;
                         break;
                     case "addbtypeop":
                         $discriptionObjs.eq(7).addClass("activeDiscription");
                         title += lgbxingti;
                         type = 8;
                         break;
                     case "addbtypequedry":
                         $discriptionObjs.eq(8).addClass("activeDiscription");
                         title += lgbxingtigan;
                         type = 9;
                         break;

                 }
             }
             if ($.browser.msie) {//ie上传文件不允许用按钮模拟
                 $("#uploadImgContainer").css({ "width": "auto", "height": "auto" });
                 //artDialog提示框
                 config.push({ name: lgqd, callback: function () { getQuestionByPage(fid) }, focus: true });
                 config.push({ name: lggongshibianjiqi, callback: function () { $("#mathquill").show(); return false; } });
                 config.push({ name: lgqx, callback: function () { editQueKey = -1; } });
             } else {
                 config.push({ name: lgshangchuanwenjian, callback: function () { $("#uploadImg").click(); return false; } });
                 config.push({ name: lggongshibianjiqi, callback: function () { $("#mathquill").show(); return false; } });
                 config.push({ name: lgqd, callback: function () { getQuestionByPage(fid) }, focus: true });
                 config.push({ name: lgqx, callback: function () { editQueKey = -1; } });
             }
             //artDialog提示框
             art.dialog({
                 content: document.getElementById("addQuesionContainer"),
                 padding: 0,
                 button: config,
                 lock: true, opacity: 0.1, title: title
             });
             return false;
         },
    //显示预览
         showHTML = function () { //将题目显示到页面
             check();
             var txt = queues.toHTML();
             $("#pc_View").html(txt); //添加题目  
             pc_View();
         },
    //**************************出题辅助工具************************************************//
    //格式验证
         check = function () {//检测数据是否合法
             //从这里将之前check()方法逆行的逻辑转换正常
             var showBox = $("#handleIcon"), check;
             showBox.show(0);
             if (!queues.length()) {
                 showTipsMsg(lghaimeiyoulgtianjia);
                 showBox.fadeOut(200);
                 return false;
             };
             var errlist = queues.check();
             if (errlist.length > 0) {
                 var errhtml = new StringBuilder();
                 for (var i = 0; i < errlist.length; i++) {
                     errhtml.append(lgjiancedao + (parseInt(errlist[i].key) + 1) + lgtimugeshicuowucuowuneirong + "：" + errlist[i].value + "<br />");
                 }
                 showFaceMsg(errhtml.toString());
                 showBox.fadeOut(200);
                 return false;
             }
             showBox.fadeOut(200);
             return true;
         },
    //动态插入
         inserTxt = function (textObj, textStr) {//插入文本到txt框
             //插入文本到光标
             textObj.focus();
             var topic = textStr, value = textObj.value, index = value.indexOf(topic);
             if (index === -1) {
                 //匹配
                 funTextAsTopic(textObj, topic);
             }
             value = textObj.value;
             index = value.indexOf(topic);
             if (textObj.createTextRange) {
                 var range = textObj.createTextRange();
                 range.moveEnd("character", (index + textStr.length) - value.length);
                 range.moveStart("character", index);
                 range.select();
             } else {
                 textObj.setSelectionRange(index, index + textStr.length);
                 textObj.focus();
             }
             function funTextAsTopic(textObj, textFeildValue) {
                 if (textObj.createTextRange) {
                     if (document.selection == undefined) {
                         var rangeStart = textObj.selectionStart;
                         var rangeEnd = textObj.selectionEnd;
                         var tempStr1 = textObj.value.substring(0, rangeStart);
                         var tempStr2 = textObj.value.substring(rangeEnd);
                         textObj.value = tempStr1 + textFeildValue + tempStr2;
                         textObj.blur();
                     }
                     else {
                         var caretPos = document.selection.createRange().duplicate();
                         document.selection.empty();
                         caretPos.text = textFeildValue;
                     }

                 } else if (textObj.setSelectionRange) {
                     var rangeStart = textObj.selectionStart;
                     var rangeEnd = textObj.selectionEnd;
                     var tempStr1 = textObj.value.substring(0, rangeStart);
                     var tempStr2 = textObj.value.substring(rangeEnd);
                     textObj.value = tempStr1 + textFeildValue + tempStr2;
                     textObj.blur();
                 }
             }
         },
         funInsertTopic = function (textObj, textStr) {
             textObj.focus();
             var topic = textStr, value = textObj.value, index = value.indexOf(topic);
             if (index === -1) {
                 //匹配
                 inserTxt(textObj, topic);
             }
             value = textObj.value;
             index = value.indexOf(topic);
             if (textObj.createTextRange) {
                 var range = textObj.createTextRange();
                 range.moveEnd("character", (index + textStr.length) - value.length);
                 range.moveStart("character", index);
                 range.select();
             } else {
                 textObj.setSelectionRange(index, index + textStr.length);
                 textObj.focus();
             }
         };
    //上传文件
    uploadImg = function (fileName, form, url, fn) {//上传文件
        var imgSrc = "";
        //上传文件
        //        if (fileName.length < 1) {//不合法
        //            showTipsMsg("请选择要上传的文件", 2000, 3);
        //            return false;
        //        } else {
        //            var extension = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length).toLowerCase(); //获取扩展名
        //            if (extension == "bmp" || extension == "jpg" || extension == "jpge" || extension == "gif") {//合法
        $.ajaxFileUpload({
            url: url,
            secureuri: false,
            fileElementId: 'uploadImg',
            data: "",
            dataType: 'text',
            type: 'POST',
            //form.ajaxSubmit({
            //type: "post",
            //url: url,
            success: function (data) {
                if (data) {
                    switch (data) {
                        //                            case "1":                                                       
                        //                                showTipsMsg("文件不正确，请重新选择文件", 2000, 3);                                                       
                        //                                return false;                                                       
                        case "2":
                            showTipsMsg(lgwenjianchaoguodaxiao, 2000, 3);
                            return false;
                            //                            case "3":
                            //                                showTipsMsg("文件格式不正确，只允许jpg、jpge、bmp、gif的图片文件", 2000, 3);
                            //                                return false;
                        case "4":
                            showTipsMsg(lgwangluochuanshuyichang, 2000, 5);
                            return false;
                        default:
                            //插入图片
                            fn(data);
                            return true;
                    }
                } else {
                    showTipsMsg(lgwangluochuanshuyichang, 3000, 5);
                    return false;
                }
            }
        });
        //            } else {
        //                showTipsMsg("文件格式不正确，只允许jpg、jpge、bmp、gif的图片文件", 2000, 3);
        //                return true;
        //            }
        //        }
    },
    //回到顶部
         bindbackTop = function () {
             var $backToTopEle = $('<div class="backToTop" style="cursor: pointer;_right: auto; width: 50px; color:#4Db6E8; height: 50px; background: url(\'/Themes/Images/BackTop_default.png\') no-repeat 0px 0px; position: fixed; _position: absolute; bottom: 88px; right: 8.6%; z-index: 1280;"></div>').appendTo($("body")).click(function () {
                 $("#priviewContent").animate({ scrollTop: 0 }, 120);
             }).hover(function () {
                 $(this).css({ "background-position": "-50px 0px" });
             }, function () {
                 $(this).css({ "background-position": "0px 0px" });
             }), $backToTopFun = function () {
                 var st = $("#priviewContent").scrollTop(), winh = $("#priviewContent").height();
                 (st > 600) ? $backToTopEle.show() : $backToTopEle.hide(); //显示backToTop
             };
             $("#priviewContent").bind("scroll", $backToTopFun);
             $backToTopFun();
         },
    //扩展接口
         extend = function (obj) {//扩展题型
             new QueType(obj);
         },

    //***************************从数据库选题目******************************************//
        bindChoiseEvent = function (currIndex, quesTypekey, quesKeywords) {
            //异步加载数据方法
            $("#choiseBody").html('<tr><td colspan="6" style="color:#32b775; background-color:#FAFAFA!important;">' + lgzhengzaijiazai + '...</td></tr>');
            if (quesTypekey == 'notChoise')
                quesTypekey = '';

            var items_type = $("input[name='items_type']:checked").val();
            var rank = $("input[name='rank']:checked").val();
            var items_tag = $("input[name='items_tag']:checked").val();

            if (items_type == undefined) { items_type = "-1"; }
            if (rank == undefined) { rank = "-1"; }
            if (items_tag == undefined) { items_tag = "0"; }

            //异步加载列表
            queryQuestionData({ "iD": currIndex, "tY": quesTypekey, "kW": quesKeywords, items_type: items_type, rank: rank, items_tag: encodeURI(items_tag) }, function (data) {
                if (data) {
                    //                        setTimeout(function () {
                    var choiseBody = $("#choiseBody");
                    if (data.sumCount == 0) {
                        $("#choiseBody").html('<tr><td colspan="6" style="color:red;">' + lgmeiyouxiangguanshuju + '</td></tr>');
                        return;
                    }
                    //设置页码
                    $("#choiseCurrIndex").text(currIndex);
                    $("#choiseUpPage").attr('data', currIndex == 1 ? 1 : currIndex - 1);
                    $("#choiseDownPage").attr('data', currIndex >= data.sumCount ? data.sumCount : currIndex + 1);
                    $("#choiseSumCount").text(data.sumCount);
                    //循环数据
                    choiseBody.html('');
                    for (var i = 0; i < data.list.length; i++) {
                        var qtitl = "";
                        var qdis = "";
                        var qans = "";
                        var qid = "";
                        if (data.list[i].Questions_Title != null) {
                            qtitl = data.list[i].Questions_Title.replace(/</g, '&lt').replace(/>/g, '&gt').replace(/'/g, '\'');
                        }
                        if (data.list[i].TKS_QuestionTypes != null) {
                            qdis = data.list[i].TKS_QuestionTypes.QuestionTypes_Name.replace(/</g, '&lt').replace(/>/g, '&gt').replace(/'/g, '\'');
                        }
                        if (data.list[i].Questions_Answer != null) {
                            qans = data.list[i].Questions_Answer.replace(/</g, '&lt').replace(/>/g, '&gt').replace(/'/g, '\'');
                        }
                        if (data.list[i].Questions_Id != null) {
                            qid = data.list[i].Questions_Id;
                        }

                        choiseBody.append('<tr><td class="cohoiseKey"><input type="checkbox" value="' + qid + '" onclick="Zuduan(this)"/></td><td class="choiseQuesTitle" title="' + qtitl + '">' + qtitl + '</td><td>' + qdis + '</td><td>' + qans + '</td><td data="' + qid + '">' + lgNullWu + '</td></tr>');
                    }
                    //绑定一系列事件
                    $(".choiseTable tr:odd").children("td").addClass("ciTd");
                    $(".choiseTable tr:even").children("td").addClass("ciTds");
                    $("#choiseBody tr").unbind("click");
                    $("#choiseBody tr").bind("click", function () {
                        var inputObj = $(this).find("input");
                        if (inputObj.attr("checked")) {
                            inputObj.removeAttr("checked");
                            $(this).children("td").removeClass("ciTdCheck");
                        } else {
                            $(this).children("td").addClass("ciTdCheck");
                            inputObj.attr("checked", "checked");
                        }
                    });
                    //                        }, 3000);

                } else {
                    showTipsMsg(lgshujujiazaiyichang, 3000, 5);
                }
            }, function () {
                showTipsMsg(lgshujujiazaiyichang, 3000, 5);
            });
        },
        load = function () { },
    //无参数获取Event对象方法 
        GetEvent = function GetEvent() {
            if (document.all) // IE
            {
                return window.event;
            }
            func = GetEvent.caller; // 返回调用本函数的函数
            while (func != null) {
                // Firefox 中一个隐含的对象 arguments，第一个参数为 event 对象
                var arg0 = func.arguments[0];
                // alert('参数长度：' + func.arguments.length);
                if (arg0) {
                    if ((arg0.constructor == Event || arg0.constructor == MouseEvent) || (typeof (arg0) == "object" && arg0.preventDefault && arg0.stopPropagation)) {
                        return arg0;
                    }
                }
                func = func.caller;
            }
            return null;
        },
        getQues = function (clickObj) {
            $("#choiseBody").html('<tr><td colspan="6" style="color:#32b775;">' + lgzhengzaijiazai + '...</td></tr>');
            stopBubble(GetEvent());
            //快速显示
            $("#choiseQuestion").css({ left: clickObj.offsetLeft, top: clickObj.offsetTop + clickObj.offsetHeight }).show(300).click(function (e) {
                stopBubble(e);
            });
            if ($("#choiseQuesionTypeList>option").length <= 1) {//异步加载下拉列表，然后不再加载
                queryQuestionData({ "aT": 1 }, function (data) {
                    if (data) {
                        for (var i = 0; i < data.length; i++) {
                            $("#choiseQuesionTypeList").append("<option value='" + data[i].Value + "'>" + data[i].Name + "</option>");
                        }
                        $("#choiseQuestion").css({ left: clickObj.offsetLeft, top: clickObj.offsetTop + clickObj.offsetHeight }).show(300).click(function (e) {
                            stopBubble(e);
                        });
                    }
                }, function () {
                    showTipsMsg(lgxialakuangbangdingshuju, 3000, 5);
                });
            }

            queryQuestionData({ "aT": 4 }, function (data) { $("#items_tag").html("<em>" + lgtagname + "：</em><label><input class=\"items_tag\" name=\"items_tag\" value=\"-1\" type=\"radio\" checked=\"checked\" />" + lgquanbu + "</label>" + data); });

            queryQuestionData({ "aT": 5 }, function (data) { $("#items_type").html("<em>" + lgqtype + "：</em><label><input class=\"items_type\" name=\"items_type\" value=\"0\" type=\"radio\" checked=\"checked\" />" + lgquanbu + "</label>" + data); });

            bindChoiseEvent(1, "", ""); //不进行异步加载则加载别的数据
            $(document).click(function () {
                $("#choiseQuestion").hide(300);
            });
        },

    //***************************保存试卷方法******************************************//
        save = function () {
            //保存试卷到服务器方法
            if (queues.length() < 1) {
                showTipsMsg(lghaimeiyoulgtianjiatimuxinx, 2000, 3);
                return false;
            }

            if (!check()) {
                //验证不通过禁止存入数据库
                return false;
            }
            //TODO
            //开始异步提交，后端接受逻辑需要调整
            var qarr = queues.toArray();
            var json = JSON.stringify(qarr);
            //$("#aaaa").val(json);
            var exam_CsKey; //课件ID
            var pageType = false;   //页面类型：表示是添加问卷还是添加试卷。true：添加问卷、false：添加试卷
            //获取地址栏参数
            var temp = QueryString("pageType");
            pageType = temp && parseInt(temp) == 1 ? true : false; //查询地址栏参数，得到页面类型，true为问卷，false为试卷
            temp = QueryString("exam_CsKey");
            exam_CsKey = (!temp || temp == "TKNC") ? "" : temp;
            var url = QueryString("key") == "" ? "AddQuestions.ashx" : "SaveQuestionByEdit.ashx";
            if (QueryString("key") == "importword") {
                url = "/Training/ExamImportWord/ExamImportWordSave.ashx"; //word导入题目
            }
            $.ajax({
                url: url,
                type: "post",
                data: { "array": json, "pageType": pageType, "exam_CsKey": exam_CsKey, "exKey": QueryString("key") },
                dataType: "json",
                success: function (data) {
                    $("#handleIcon").hide(0);
                    var resultStr = "";
                    if (data) {//不为空
                        if (data.error || data.error.length > 0) {//有异常
                            resultStr = data.error;
                        } else {
                            if (data.errorNums || data.errorNums.length > 0) { //存在题目未能录取成功
                                resultStr = lgbianhaowei + '：' + data.errorNums + lgtimuweinengluruchengg + '... ';
                            } else {
                                if (data.examId || data.length > 0) {//试卷ID
                                    if (pageType) {
                                        var url = "/Training/QuesNaire/Questionnaire_Form.aspx?ExamKey=" + data.examId;
                                        top.openDialog(url, "ExaminationPaper_Form", lgwenjuanxinx + " -  " + lgtianjia, 800, 500, 50, 50); //录入试卷信息
                                    } else {
                                        var url = "/Training/TrainingTest/ExaminationPaper_Form.aspx?ExamKey=" + data.examId;
                                        top.openDialog(url, "ExaminationPaper_Form", lgshijuanxinx + " -  " + lgtianjia, 800, 500, 50, 50); //录入试卷信息
                                    }
                                    return;
                                } else {
                                    if (data.isok == "ok") {//导入成功
                                        var url = "/Training/Exam/ExamImport_List.aspx";
                                        location.href = url;
                                        return;
                                    } else {
                                        resultStr = lgshujuyichangqingjiance;
                                    }

                                }
                            }
                        }
                        showTipsMsg(resultStr, 3000, 5);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    showTipsMsg(lgwangluoyichang + XMLHttpRequest.status.toString(), 3000, 5);
                    $("#handleIcon").fadeOut(200);
                }
            });

            return true;
        },
        queryQuestionData = function queryQuestionData(parm, callBack, errCallBack) {
            //可以从这里开始异步加载
            $.ajax({
                url: "/Training/TrainingTest/GetQuestionList.ashx",
                type: "post",
                data: parm,
                dataType: "json",
                success: function (data) {
                    callBack(data);
                },
                error: function () {
                    if (errCallBack) errCallBack();
                    else {
                        showTipsMsg(lgshujuyichangqingjiance, 1500, 5);
                    }
                }
            });
        },
        Zuduan = function (obj) {
            if (obj.checked) {
                obj.checked = false;
            }
            else {
                obj.checked = true;
            }
        },
        Obj2Text = function (Obj) {
            /// <summary>
            /// 将题目对象转成插入文本框的内容
            /// </summary>
            //id, type, title, dis, score, option, answer, child, index
            var text = new StringBuilder();
            text.append(Obj.title[0] + "\n");
            for (var i = 0; i < Obj.option.length; i++) {
                text.append(Obj.option[i] + "\n");
            }
            text.append(lgdaan + "：" + Obj.answer[0] + "\n");
            if (Obj.score && Obj.score != 'undefined') {
                text.append(lgfenshu + "：" + Obj.score + "\n");
            }
            if (Obj.dis && Obj.dis != 'undefined') {
                text.append(lgzhushi + "：" + Obj.dis + "\n");
            }
            return text.toString();
        },
        Json2HTML = function (data) {
            /// <summary>
            ///     1: 将Json数据转换显示到界面上
            /// </summary>
            //异步查询
            // alert(data.length);
            if (data && parseInt(data) != -1) {
                indexNum = 0;
                $("ul").each(function () {
                    if ($(this).parent().hasClass("zht")) { } else {
                        indexNum++;
                    }
                });
                for (var i = 0; i < data.length; i++) {
                    var obj = {};
                    obj.id = data[i].id;
                    obj.title = [];
                    obj.title.push(data[i].title);
                    obj.option = data[i].option;
                    obj.answer = [];
                    obj.answer.push(data[i].answer);
                    obj.score = data[i].Score;
                    obj.type = data[i].qtid;
                    obj.dis = data[i].dis;
                    obj.index = i;
                    obj.child = new Queue();
                    queues.add(new QueObj(obj));
                    if (data[i].child != null && data[i].child != undefined) {
                        for (var j = 0; j < data[i].child.length; j++) {
                            var objchild = data[i].child[j];
                            var obj2 = {};
                            obj2.id = objchild.id;
                            obj2.title = [];
                            obj2.title.push(objchild.title);
                            obj2.option = objchild.option;
                            obj2.answer = [];
                            obj2.answer.push(objchild.answer);
                            obj2.score = objchild.Score;
                            obj2.type = objchild.qtid;
                            obj2.dis = objchild.dis;
                            queues.child(indexNum, new QueObj(obj2));
                        }
                    }
                    indexNum++;
                }
                showHTML();
                $(document).click();
                $("#handleIcon").hide(0);
                //showTipsMsg("插入成功", 3000, 4);
            } else {
                $("#handleIcon").hide(0);
                showTipsMsg(lgtagyichang2, 3000, 5);
            }
        };
    var indexNum = 0;
    var queTags = "";
    var queCt = "";
    $(function () {
        //***************************页面程序执行起点***************************************//
        !function (window) {
            $("body").append("<div id=\"priviewContainer\" style=\"height:80%;\"  ><fieldset id=\"priviewContext\" style=\"height:100%;\" ><legend>" + lgyulan + "</legend><div id=\"priviewContent\"><div id=\"pc_View\"></div></div></fieldset></div><div id=\"addQuesionContainer\"><div id=\"questionForm\"><textarea id=\"questionText\" spellcheck></textarea></div><div class=\"clear\"><form method=\"post\" action=\"\" id=\"uploadForm\" enctype=\"multipart/form-data\"><div id=\"uploadImgContainer\"><span>" + lgshangchuanwenjian + "：</span><input type=\"file\" name=\"imgFile\" id=\"uploadImg\"></div></form><input type=\"hidden\" id=\"page_OpType\" optype=\"-1\" opratertype=\"1\"></div></div><div id=\"handleIcon\">" + lgzhengzaijiazai + "</div><div id=\"mathquill\" style=\"width:600px;position:absolute;height:300px;left:0;bottom:0;background-color:#fff;display:none;z-index:9999\"><iframe src=\"/Training/TrainingTest/gs/mathdialog.html\" width=\"600\" height=\"300\" scrolling=\"no\" frameborder=\"0\" style=\"padding:0\"></iframe></div>");
            //页面所有的初始化
            initalQueType();
            //回到顶部
            bindbackTop();
            //上传文件

            /* document.getElementById('uploadImg').onchange = function () {
            alert("");
            uploadImg($(this).val(), $("#uploadForm"), "/Training/TrainingTest/UploadImg.ashx", function (data) {
            //alert(data);
            var textObj = $("#questionText").get(0);
            funInsertTopic(textObj, '<annex>' + data + '</annex>');
            $("#uploadImg").val('');
            });
            };
            */
            $("#uploadImg").live("change", function () {
                uploadImg($(this).val(), $("#uploadForm"), "/Training/TrainingTest/UploadImg.ashx", function (data) {
                    //alert(data);
                    var textObj = $("#questionText").get(0);
                    funInsertTopic(textObj, '<label class="annex" >' + data + '</label>');
                    $("#uploadImg").val('');
                });
            });

            //初始化文本框对象
            txtObj = $("#questionText");
            //监听题目里所有编辑按钮
            $(".editQp").live("click", function () {
                //alert($(this).attr('fid'));
                var fid = $(this).attr('fid');
                var editKey = $(this).attr('op_id');
                if (fid && !isNaN(parseInt(fid))) {//当这个删除按钮时子集项目时
                    editQueKey = editKey;
                    type = queues.child(fid).child.child(editKey).type;
                    var source = queues.child(fid).child.child(editKey).source;
                    if (source == "" || source == undefined) {
                        source = Obj2Text(queues.child(fid).child.child(editKey));
                    }
                    txtObj.val(source);
                    showEdit(lgbianji, null, fid);
                }
                else {
                    if (editKey && !isNaN(editKey = parseInt(editKey))) {
                        editQueKey = editKey;
                        type = queues.child(editKey).type;
                        var source = queues.child(editKey).source;
                        if (source == "" || source == undefined) {
                            source = Obj2Text(queues.child(editKey));
                        }
                        txtObj.val(source);
                    }
                    showEdit(lgbianji);
                }

                return false;
            });
            //监听删除按钮
            $(".deleteQp").live("click", function () { //删除按钮
                var fid = $(this).attr('fid');
                var op_Id = $(this).attr("op_id");
                if (fid && !isNaN(parseInt(fid))) {//当这个删除按钮时子集项目时
                    showConfirmMsg(lgquedinglgshanchuma, function () {
                        //alert(fid + "|" + op_Id);
                        queues.child(fid).child.remove(parseInt(op_Id), 1);
                        showHTML();
                    });
                }
                else {
                    if (op_Id && !isNaN(parseInt(op_Id))) {
                        showConfirmMsg(lgquedinglgshanchuma, function () {
                            //删除方法与重新显示方法
                            queues.remove(parseInt(op_Id), 1);
                            //$("#que_" + op_Id).remove();
                            //$("#pc_View").html("");
                            showHTML();
                        });
                    }
                }
                return false;
            });
            //*********************综合提按钮*****************************//
            $(".qtdanxuan").live("click", function () {
                //alert($(this).attr('op_id'));
                var editKey = $(this).attr('op_id');
                if (editKey && !isNaN(editKey = parseInt(editKey))) {
                    txtObj.val("");
                    showEdit(lgtianjia, "addsingle", editKey);
                }
                return false;
            });
            $(".qtduoxuan").live("click", function () {
                //alert($(this).attr('op_id'));
                var editKey = $(this).attr('op_id');
                if (editKey && !isNaN(editKey = parseInt(editKey))) {
                    txtObj.val("");
                    showEdit(lgtianjia, "addmultiple", editKey);
                }
                return false;
            });
            $(".qtwenda").live("click", function () {
                //alert($(this).attr('op_id'));
                var editKey = $(this).attr('op_id');
                if (editKey && !isNaN(editKey = parseInt(editKey))) {
                    txtObj.val("");
                    showEdit(lgtianjia, "addanswer", editKey);
                }
                return false;
            });
            //*********************B型题按钮*****************************//
            $(".qtbtype").live("click", function () {
                //alert($(this).attr('op_id'));
                var editKey = $(this).attr('op_id');
                if (editKey && !isNaN(editKey = parseInt(editKey))) {
                    txtObj.val("");
                    showEdit(lgtianjia, "addbtypequedry", editKey);
                }
                return false;
            });

            $(".choiseTable tr").live("mouseenter", function () {//鼠标悬浮样式
                $(this).children("td").addClass("ciTdHover");
            }).live("mouseleave", function () {//鼠标移除样式
                $(this).children("td").removeClass("ciTdHover");
            });


        } ();

        //*************************题目搜索**********************************//

        var bodyStr = "<div id=\"choiseQuestion\"><div id=\"choiseWhere\"><span>" + lgqfenlei + " </span><select id=\"choiseQuesionTypeList\"><option value=\"notChoise\">" + lgbuxuanze + "</option></select> <input id=\"choiseSearch\"><a href=\"javascript:void();\" id=\"searchChoiseInfo\">" + lgsousuotimu + "</a>";
        bodyStr += "<div id=\"items_tag\" ></div>";

        bodyStr += "<div id=\"items_type\"></div>";

        bodyStr += "<div ><em>" + lgqnandu + "：</em><label><input class=\"rank\" name=\"rank\" value=\"-1\" CHECKED=\"checked\" type=\"radio\">" + lgquanbu + "</label><label><input class=\"rank\" name=\"rank\" value=\"0\" type=\"radio\">" + lgjiandan + "</label><label><input class=\"rank\" name=\"rank\" value=\"1\" type=\"radio\">" + lgyiban + "</label><label><input class=\"rank\" name=\"rank\" value=\"2\" type=\"radio\">" + lgnan1 + "</label><label><input class=\"rank\" name=\"rank\" value=\"3\" type=\"radio\">" + lgkunnan + "</label><label><input class=\"rank\" name=\"rank\" value=\"4\" type=\"radio\">" + lghennan + "</label></div>";

        bodyStr += "</div><table class=\"choiseTable\"><thead class=\"choiseTitle\"><tr><th class=\"choiseAllKey\"></th><th class=\"choiseQuesTitle\">" + lgbiaoti + "</th><th>" + lgtixing + "</th><th>" + lgdaan + "</th><th>" + lgcaozuo + "</th></tr></thead><tbody id=\"choiseBody\"></tbody></table><div id=\"choisePage\"><a href=\"javascript:;\" id=\"addChoiseQues\">" + lgcharu + "</a> <a href=\"javascript:;\" id=\"choiseUpPage\" data=\"1\">" + lgshangyiye + "</a><span id=\"choiseCurrIndex\">1</span>/<span id=\"choiseSumCount\">1</span> <a href=\"javascript:;\" id=\"choiseDownPage\" data=\"1\">" + lgxiayiye + "</a></div></div>";

        $("body").append(bodyStr);

        $("#choiseUpPage").click(function () {//上一页
            var upPage = parseInt($(this).attr('data'));
            bindChoiseEvent(upPage <= 1 ? 1 : upPage, $("#choiseQuesionTypeList").val(), jQuery.trim($("#choiseSearch").val()));
        });
        $("#choiseDownPage").click(function () {//下一页
            var downPage = parseInt($(this).attr('data'));
            var sumPage = parseInt($("#choiseSumCount").text());
            bindChoiseEvent(downPage >= sumPage ? sumPage : downPage, $("#choiseQuesionTypeList").val(), jQuery.trim($("#choiseSearch").val()));
        });
        $("#choiseSearch").keydown(function (e) {
            var event = e || event; //兼容性处理
            if (e.keyCode == 13) $("#searchChoiseInfo").click();
        });
        $("#searchChoiseInfo").click(function () { //搜索
            bindChoiseEvent(1, $("#choiseQuesionTypeList").val(), jQuery.trim($("#choiseSearch").val()));
        });
        $("#addChoiseQues").click(function () {
            var keyList = $("#choiseBody").find("input[checked=checked]"); //获取选种项
            if (keyList.length == 0) {
                showTipsMsg(lgnihaimeiyouxuanze, 1500, 3);
                return;
            }
            var keyStr = ""; //累加成'主键','主键'格式的字符串
            keyList.each(function () {
                keyStr += "'" + $(this).val() + "',";
            });
            keyStr = keyStr.substring(0, keyStr.length - 1);
            queryQuestionData({ aT: 3, kL: keyStr }, function (data) {
                $("#handleIcon").show(0);
                Json2HTML(data);
            });
        });
        $(".choiseAllKey").click(function () {

            if (!$(this).attr("checked")) {
                $(".choiseTable input[type=checkbox]").attr("checked", "checked");
                $(this).attr("checked", "checked");
            } else {
                $(".choiseTable input[type=checkbox]").removeAttr("checked");
                $(this).removeAttr("checked", "checked");
            }
        });
    });

    //对外开放（右上角不同题型按钮开放的接口）
    window.btnClickEvent = function (key) {
        editQueKey = -1;
        $("#questionText").val("");
        showEdit(lgtianjia, key);
    };
    //保存试卷对外开放（右上角保存试卷）
    window.savaAndToExamEvent = function () {
        save();
    };
    window.imgLoad = imgLoad;
    window.funInsertTopic = funInsertTopic;
    //从题库中选题
    window.btnClickChoiseQuestion = getQues;
    //将JSON转成html
    window.jsontohtml = function (data) {
        /// <summary>
        ///     1: 将Json数据转换显示到界面上
        /// </summary>
        //异步查询
        //Json2HTML(data);
        if (data && parseInt(data) != -1) {
            for (var i = 0; i < data.length; i++) {
                var obj = {};
                obj.id = data[i].id;
                obj.title = [];
                obj.title.push(data[i].title);
                obj.option = data[i].option;
                obj.answer = [];
                obj.answer.push(data[i].answer);
                obj.score = data[i].Score;
                obj.type = data[i].qtid;
                obj.dis = data[i].dis;
                obj.index = i;
                obj.child = new Queue();
                queues.add(new QueObj(obj));
                if (data[i].child != null && data[i].child != undefined) {
                    for (var j = 0; j < data[i].child.length; j++) {
                        var objchild = data[i].child[j];
                        var obj2 = {};
                        obj2.id = objchild.id;
                        obj2.title = [];
                        obj2.title.push(objchild.title);
                        obj2.option = objchild.option;
                        obj2.answer = [];
                        obj2.answer.push(objchild.answer);
                        obj2.score = objchild.Score;
                        obj2.type = objchild.qtid;
                        obj2.dis = objchild.dis;
                        queues.child(i, new QueObj(obj2));
                    }
                }
            }
            showHTML();
            $(document).click();
            $("#handleIcon").hide(0);
        }
        else {
            $("#handleIcon").hide(0);
            showTipsMsg(lgtagyichang2, 3000, 5);
        }
    };
    String.prototype.trim = function () {
        return this.replace(/(^\s*)|(\s*$)/g, "");
    }
} (jQuery, window);